(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('jquery')) :
	typeof define === 'function' && define.amd ? define(['jquery'], factory) :
	(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.$));
})(this, (function (require$$0$1) { 'use strict';

	var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

	function getDefaultExportFromCjs (x) {
		return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
	}

	function getAugmentedNamespace(n) {
	  if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
	  var f = n.default;
		if (typeof f == "function") {
			var a = function a () {
				var isInstance = false;
	      try {
	        isInstance = this instanceof a;
	      } catch (e) {}
				if (isInstance) {
	        return Reflect.construct(f, arguments, this.constructor);
				}
				return f.apply(this, arguments);
			};
			a.prototype = f.prototype;
	  } else a = {};
	  Object.defineProperty(a, '__esModule', {value: true});
		Object.keys(n).forEach(function (k) {
			var d = Object.getOwnPropertyDescriptor(n, k);
			Object.defineProperty(a, k, d.get ? d : {
				enumerable: true,
				get: function () {
					return n[k];
				}
			});
		});
		return a;
	}

	var jqueryUi = {};

	var hasRequiredJqueryUi;function requireJqueryUi(){if(hasRequiredJqueryUi)return jqueryUi;hasRequiredJqueryUi=1;(function(factory){{// Browser globals
	factory(jQuery);}})(function($){$.ui=$.ui||{};$.ui.version="1.14.2";/*!
		 * jQuery UI Widget 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Widget
	//>>group: Core
	//>>description: Provides a factory for creating stateful widgets with a common API.
	//>>docs: https://api.jqueryui.com/jQuery.widget/
	//>>demos: https://jqueryui.com/widget/
	var widgetUuid=0;var widgetHasOwnProperty=Array.prototype.hasOwnProperty;var widgetSlice=Array.prototype.slice;$.cleanData=function(orig){return function(elems){var events,elem,i;for(i=0;(elem=elems[i])!=null;i++){// Only trigger remove when necessary to save time
	events=$._data(elem,"events");if(events&&events.remove){$(elem).triggerHandler("remove");}}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];if(name==="__proto__"||name==="constructor"){return $.error("Invalid widget name: "+name);}var fullName=namespace+"-"+name;if(!prototype){prototype=base;base=$.Widget;}if(Array.isArray(prototype)){prototype=$.extend.apply(null,[{}].concat(prototype));}// Create selector for plugin
	$.expr.pseudos[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||!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(typeof value!=="function"){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(widgetHasOwnProperty.call(input[inputIndex],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(typeof instance[options]!=="function"||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 bindRemoveEvent(){var nodesToBind=[];options.element.each(function(_,element){var isTracked=$.map(that.classesElementLookup,function(elements){return elements;}).some(function(elements){return elements.is(element);});if(!isTracked){nodesToBind.push(element);}});that._on($(nodesToBind),{remove:"_untrackClassesElement"});}function processClassString(classes,checkOption){var current,i;for(i=0;i<classes.length;i++){current=that.classesElementLookup[classes[i]]||$();if(options.add){bindRemoveEvent();current=$($.uniqueSort(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]]);}}}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());}});this._off($(event.target));},_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);// 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 !(typeof callback==="function"&&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};}else if(options===true){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();});}};});$.widget;/*!
		 * jQuery UI Position 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *
		 * https://api.jqueryui.com/position/
		 *///>>label: Position
	//>>group: Core
	//>>description: Positions elements relative to other elements.
	//>>docs: https://api.jqueryui.com/position/
	//>>demos: https://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 isWindow(obj){return obj!=null&&obj===obj.window;}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:200px;height:200px;overflow:hidden;'>"+"<div style='height:300px;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),isElemWindow=isWindow(withinElement[0]),isDocument=!!withinElement[0]&&withinElement[0].nodeType===9,hasOffset=!isElemWindow&&!isDocument;return {element:withinElement,isWindow:isElemWindow,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,// Make sure string options are treated as CSS selectors
	target=typeof options.of==="string"?$(document).find(options.of):$(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);}}};})();$.ui.position;/*!
		 * jQuery UI :data 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: :data Selector
	//>>group: Core
	//>>description: Selects elements which have data stored under the specified key.
	//>>docs: https://api.jqueryui.com/data-selector/
	$.extend($.expr.pseudos,{data:$.expr.createPseudo(function(dataName){return function(elem){return !!$.data(elem,dataName);};})});/*!
		 * jQuery UI Disable Selection 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: disableSelection
	//>>group: Core
	//>>description: Disable selection of text content within the set of matched elements.
	//>>docs: https://api.jqueryui.com/disableSelection/
	// This file is deprecated
	$.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");}});// Create a local jQuery because jQuery Color relies on it and the
	// global may not exist with AMD and a custom build (#10199).
	// This module is a noop if used as a regular AMD module.
	// eslint-disable-next-line no-unused-vars
	var jQuery=$;/*!
		 * jQuery Color Animations v3.0.0
		 * https://github.com/jquery/jquery-color
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *
		 * Date: Wed May 15 16:49:44 2024 +0200
		 */var stepHooks="backgroundColor borderBottomColor borderLeftColor borderRightColor "+"borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",class2type={},toString=class2type.toString,// 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})([a-f0-9]{2})?/,parse:function(execResult){return [parseInt(execResult[1],16),parseInt(execResult[2],16),parseInt(execResult[3],16),execResult[4]?(parseInt(execResult[4],16)/255).toFixed(2):1];}},{// this regex ignores A-F because it's compared against an already lowercased string
	re:/#([a-f0-9])([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),execResult[4]?(parseInt(execResult[4]+execResult[4],16)/255).toFixed(2):1];}},{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}},// colors = jQuery.Color.names
	colors,// local aliases of functions called often
	each=jQuery.each;// 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};});// 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 getType(obj){if(obj==null){return obj+"";}return typeof obj==="object"?class2type[toString.call(obj)]||"object":typeof obj;}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);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 Math.min(type.max,Math.max(0,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=getType(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
	if(inst[cache][3]==null){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){if(v!=null){return v;}return i>2?1:0;});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
	return ("0"+(v||0).toString(16)).substr(-2);}).join("");},toString:function(){return 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=getType(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 local,cur,match,fn,vtype=getType(value);if(key==="alpha"){fn=this._hsla?"hsla":"rgba";}else {fn=spaceName;}local=this[fn]();cur=local[prop.idx];if(vtype==="undefined"){return cur;}if(vtype==="function"){value=value.call(this,cur);vtype=getType(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;if(value!=="transparent"&&(getType(value)!=="string"||(parsed=stringParse(value)))){value=color(parsed||value);value=value.toRgbaString();}elem.style[hook]=value;}};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 UI Effects 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Effects Core
	//>>group: Effects
	//>>description: Extends the internal jQuery effects. Includes morphing and easing. Required by all other effects.
	//>>docs: https://api.jqueryui.com/category/effects-core/
	//>>demos: https://jqueryui.com/effect/
	var dataSpace="ui-effects-",dataSpaceStyle="ui-effects-style",dataSpaceAnimated="ui-effects-animated";$.effects={effect:{}};/******************************************************************************//****************************** 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 camelCase(string){return string.replace(/-([\da-z])/gi,function(all,letter){return letter.toUpperCase();});}function getElementStyles(elem){var key,len,style=elem.ownerDocument.defaultView.getComputedStyle(elem),styles={};len=style.length;while(len--){key=style[len];if(typeof style[key]==="string"){styles[camelCase(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;}$.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.pseudos&&$.expr.pseudos.animated){$.expr.pseudos.animated=function(orig){return function(elem){return !!$(elem).data(dataSpaceAnimated)||orig(elem);};}($.expr.pseudos.animated);}if($.uiBackCompat===true){$.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{// eslint-disable-next-line no-unused-expressions
	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.14.2",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: https://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(typeof options==="function"){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(typeof speed==="function"){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(typeof option==="function"){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 pseudo-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.14
	if(defaultMode&&(normalizedMode==="show"||normalizedMode===defaultMode&&normalizedMode==="hide")){el.show();}if(!defaultMode||normalizedMode!=="none"){$.effects.saveStyle(el);}if(typeof next==="function"){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(typeof complete==="function"){complete.call(elem[0]);}if(typeof next==="function"){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===true&&!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>");transfer.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(typeof done==="function"){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://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;};});})();$.effects;/*!
		 * jQuery UI Effects Blind 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Blind Effect
	//>>group: Effects
	//>>description: Blinds the element.
	//>>docs: https://api.jqueryui.com/blind-effect/
	//>>demos: https://jqueryui.com/effect/
	$.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.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Bounce Effect
	//>>group: Effects
	//>>description: Bounces an element horizontally or vertically n times.
	//>>docs: https://api.jqueryui.com/bounce-effect/
	//>>demos: https://jqueryui.com/effect/
	$.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.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Clip Effect
	//>>group: Effects
	//>>description: Clips the element on and off like an old TV.
	//>>docs: https://api.jqueryui.com/clip-effect/
	//>>demos: https://jqueryui.com/effect/
	$.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.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Drop Effect
	//>>group: Effects
	//>>description: Moves an element in one direction and hides it at the same time.
	//>>docs: https://api.jqueryui.com/drop-effect/
	//>>demos: https://jqueryui.com/effect/
	$.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.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Explode Effect
	//>>group: Effects
	//>>description: Explodes an element in all directions into n pieces. Implodes an element to its original wholeness.
	//>>docs: https://api.jqueryui.com/explode-effect/
	//>>demos: https://jqueryui.com/effect/
	$.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.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Fade Effect
	//>>group: Effects
	//>>description: Fades the element.
	//>>docs: https://api.jqueryui.com/fade-effect/
	//>>demos: https://jqueryui.com/effect/
	$.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.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Fold Effect
	//>>group: Effects
	//>>description: Folds an element first horizontally and then vertically.
	//>>docs: https://api.jqueryui.com/fold-effect/
	//>>demos: https://jqueryui.com/effect/
	$.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.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Highlight Effect
	//>>group: Effects
	//>>description: Highlights the background of an element in a defined color for a custom duration.
	//>>docs: https://api.jqueryui.com/highlight-effect/
	//>>demos: https://jqueryui.com/effect/
	$.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.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Size Effect
	//>>group: Effects
	//>>description: Resize an element to a specified width and height.
	//>>docs: https://api.jqueryui.com/size-effect/
	//>>demos: https://jqueryui.com/effect/
	$.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;}delete from.outerHeight;delete from.outerWidth;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.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Scale Effect
	//>>group: Effects
	//>>description: Grows or shrinks an element and its content.
	//>>docs: https://api.jqueryui.com/scale-effect/
	//>>demos: https://jqueryui.com/effect/
	$.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.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://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: https://api.jqueryui.com/puff-effect/
	//>>demos: https://jqueryui.com/effect/
	$.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.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Pulsate Effect
	//>>group: Effects
	//>>description: Pulsates an element n times by changing the opacity to zero and back.
	//>>docs: https://api.jqueryui.com/pulsate-effect/
	//>>demos: https://jqueryui.com/effect/
	$.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.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Shake Effect
	//>>group: Effects
	//>>description: Shakes an element horizontally or vertically n times.
	//>>docs: https://api.jqueryui.com/shake-effect/
	//>>demos: https://jqueryui.com/effect/
	$.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.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Slide Effect
	//>>group: Effects
	//>>description: Slides an element in and out of the viewport.
	//>>docs: https://api.jqueryui.com/slide-effect/
	//>>demos: https://jqueryui.com/effect/
	$.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.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Transfer Effect
	if($.uiBackCompat===true){$.effects.define("transfer",function(options,done){$(this).transfer(options,done);});}//>>group: Core
	//>>description: Selects elements which can be focused.
	//>>docs: https://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")&&$(element).css("visibility")==="visible";};$.extend($.expr.pseudos,{focusable:function(element){return $.ui.focusable(element,$.attr(element,"tabindex")!=null);}});$.ui.focusable;/*!
		 * jQuery UI Form Reset Mixin 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Form Reset Mixin
	//>>group: Core
	//>>description: Refresh input widgets when their form is reset
	//>>docs: https://api.jqueryui.com/form-reset-mixin/
	$.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.prop("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 Legacy jQuery Core patches 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *
		 *///>>label: Legacy jQuery Core patches
	//>>group: Core
	//>>description: Backport `.even()`, `.odd()` and `$.escapeSelector` to older jQuery Core versions (deprecated)
	// Support: jQuery 2.2.x or older.
	// This method has been defined in jQuery 3.0.0.
	// Code from https://github.com/jquery/jquery/blob/e539bac79e666bba95bba86d690b4e609dca2286/src/selector/escapeSelector.js
	if(!$.escapeSelector){$.escapeSelector=function(id){return CSS.escape(id+"");};}// Support: jQuery 3.4.x or older
	// These methods have been defined in jQuery 3.5.0.
	if(!$.fn.even||!$.fn.odd){$.fn.extend({even:function(){return this.filter(function(i){return i%2===0;});},odd:function(){return this.filter(function(i){return i%2===1;});}});}//>>group: Core
	//>>description: Provide keycodes as keynames
	//>>docs: https://api.jqueryui.com/jQuery.ui.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};/*!
		 * jQuery UI Labels 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: labels
	//>>group: Core
	//>>description: Find all the labels associated with a given input
	//>>docs: https://api.jqueryui.com/labels/
	$.fn.labels=function(){var ancestor,selector,id,labels,ancestors;if(!this.length){return this.pushStack([]);}// Check control.labels first
	if(this[0].labels&&this[0].labels.length){return this.pushStack(this[0].labels);}// If `control.labels` is empty - e.g. inside of document fragments - find
	// the labels manually
	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='"+CSS.escape(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.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: scrollParent
	//>>group: Core
	//>>description: Get the closest ancestor element that is scrollable.
	//>>docs: https://api.jqueryui.com/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.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: :tabbable Selector
	//>>group: Core
	//>>description: Selects elements which can be tabbed to.
	//>>docs: https://api.jqueryui.com/tabbable-selector/
	$.extend($.expr.pseudos,{tabbable:function(element){var tabIndex=$.attr(element,"tabindex"),hasTabindex=tabIndex!=null;return (!hasTabindex||tabIndex>=0)&&$.ui.focusable(element,hasTabindex);}});/*!
		 * jQuery UI Unique ID 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: uniqueId
	//>>group: Core
	//>>description: Functions to generate and remove uniqueId's
	//>>docs: https://api.jqueryui.com/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");}});}});/*!
		 * jQuery UI Accordion 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Accordion
	//>>group: Widgets
	//>>description: Displays collapsible content panels for presenting information in a limited amount of space.
	//>>docs: https://api.jqueryui.com/accordion/
	//>>demos: https://jqueryui.com/accordion/
	//>>css.structure: ../../themes/base/core.css
	//>>css.structure: ../../themes/base/accordion.css
	//>>css.theme: ../../themes/base/theme.css
	$.widget("ui.accordion",{version:"1.14.2",options:{active:0,animate:{},classes:{"ui-accordion-header":"ui-corner-top","ui-accordion-header-collapsed":"ui-corner-all","ui-accordion-content":"ui-corner-bottom"},collapsible:false,event:"click",header:function(elem){return elem.find("> li > :first-child").add(elem.find("> :not(li)")// Support: jQuery <3.5 only
	// We could use `.even()` but that's unavailable in older jQuery.
	.filter(function(i){return i%2===0;}));},heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},// Callbacks
	activate:null,beforeActivate:null},hideProps:{borderTopWidth:"hide",borderBottomWidth:"hide",paddingTop:"hide",paddingBottom:"hide",height:"hide"},showProps:{borderTopWidth:"show",borderBottomWidth:"show",paddingTop:"show",paddingBottom:"show",height:"show"},_create:function(){var options=this.options;this.prevShow=this.prevHide=$();this._addClass("ui-accordion","ui-widget ui-helper-reset");this.element.attr("role","tablist");// Don't allow collapsible: false and active: false / null
	if(!options.collapsible&&(options.active===false||options.active==null)){options.active=0;}this._processPanels();// handle negative values
	if(options.active<0){options.active+=this.headers.length;}this._refresh();},_getCreateEventData:function(){return {header:this.active,panel:!this.active.length?$():this.active.next()};},_createIcons:function(){var icon,children,icons=this.options.icons;if(icons){icon=$("<span>");this._addClass(icon,"ui-accordion-header-icon","ui-icon "+icons.header);icon.prependTo(this.headers);children=this.active.children(".ui-accordion-header-icon");this._removeClass(children,icons.header)._addClass(children,null,icons.activeHeader)._addClass(this.headers,"ui-accordion-icons");}},_destroyIcons:function(){this._removeClass(this.headers,"ui-accordion-icons");this.headers.children(".ui-accordion-header-icon").remove();},_destroy:function(){var contents;// Clean up main element
	this.element.removeAttr("role");// Clean up headers
	this.headers.removeAttr("role aria-expanded aria-selected aria-controls tabIndex").removeUniqueId();this._destroyIcons();// Clean up content panels
	contents=this.headers.next().css("display","").removeAttr("role aria-hidden aria-labelledby").removeUniqueId();if(this.options.heightStyle!=="content"){contents.css("height","");}},_setOption:function(key,value){if(key==="active"){// _activate() will handle invalid values and update this.options
	this._activate(value);return;}if(key==="event"){if(this.options.event){this._off(this.headers,this.options.event);}this._setupEvents(value);}this._super(key,value);// Setting collapsible: false while collapsed; open first panel
	if(key==="collapsible"&&!value&&this.options.active===false){this._activate(0);}if(key==="icons"){this._destroyIcons();if(value){this._createIcons();}}},_setOptionDisabled:function(value){this._super(value);this.element.attr("aria-disabled",value);this._toggleClass(null,"ui-state-disabled",!!value);},_keydown:function(event){if(event.altKey||event.ctrlKey){return;}var keyCode=$.ui.keyCode,length=this.headers.length,currentIndex=this.headers.index(event.target),toFocus=false;switch(event.keyCode){case keyCode.RIGHT:case keyCode.DOWN:toFocus=this.headers[(currentIndex+1)%length];break;case keyCode.LEFT:case keyCode.UP:toFocus=this.headers[(currentIndex-1+length)%length];break;case keyCode.SPACE:case keyCode.ENTER:this._eventHandler(event);break;case keyCode.HOME:toFocus=this.headers[0];break;case keyCode.END:toFocus=this.headers[length-1];break;}if(toFocus){$(event.target).attr("tabIndex",-1);$(toFocus).attr("tabIndex",0);$(toFocus).trigger("focus");event.preventDefault();}},_panelKeyDown:function(event){if(event.keyCode===$.ui.keyCode.UP&&event.ctrlKey){$(event.currentTarget).prev().trigger("focus");}},refresh:function(){var options=this.options;this._processPanels();// Was collapsed or no panel
	if(options.active===false&&options.collapsible===true||!this.headers.length){options.active=false;this.active=$();// active false only when collapsible is true
	}else if(options.active===false){this._activate(0);// was active, but active panel is gone
	}else if(this.active.length&&!$.contains(this.element[0],this.active[0])){// all remaining panel are disabled
	if(this.headers.length===this.headers.find(".ui-state-disabled").length){options.active=false;this.active=$();// activate previous panel
	}else {this._activate(Math.max(0,options.active-1));}// was active, active panel still exists
	}else {// make sure active index is correct
	options.active=this.headers.index(this.active);}this._destroyIcons();this._refresh();},_processPanels:function(){var prevHeaders=this.headers,prevPanels=this.panels;if(typeof this.options.header==="function"){this.headers=this.options.header(this.element);}else {this.headers=this.element.find(this.options.header);}this._addClass(this.headers,"ui-accordion-header ui-accordion-header-collapsed","ui-state-default");this.panels=this.headers.next().filter(":not(.ui-accordion-content-active)").hide();this._addClass(this.panels,"ui-accordion-content","ui-helper-reset ui-widget-content");// Avoid memory leaks (#10056)
	if(prevPanels){this._off(prevHeaders.not(this.headers));this._off(prevPanels.not(this.panels));}},_refresh:function(){var maxHeight,options=this.options,heightStyle=options.heightStyle,parent=this.element.parent();this.active=this._findActive(options.active);this._addClass(this.active,"ui-accordion-header-active","ui-state-active")._removeClass(this.active,"ui-accordion-header-collapsed");this._addClass(this.active.next(),"ui-accordion-content-active");this.active.next().show();this.headers.attr("role","tab").each(function(){var header=$(this),headerId=header.uniqueId().attr("id"),panel=header.next(),panelId=panel.uniqueId().attr("id");header.attr("aria-controls",panelId);panel.attr("aria-labelledby",headerId);}).next().attr("role","tabpanel");this.headers.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}).next().attr({"aria-hidden":"true"}).hide();// Make sure at least one header is in the tab order
	if(!this.active.length){this.headers.eq(0).attr("tabIndex",0);}else {this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}).next().attr({"aria-hidden":"false"});}this._createIcons();this._setupEvents(options.event);if(heightStyle==="fill"){maxHeight=parent.height();this.element.siblings(":visible").each(function(){var elem=$(this),position=elem.css("position");if(position==="absolute"||position==="fixed"){return;}maxHeight-=elem.outerHeight(true);});this.headers.each(function(){maxHeight-=$(this).outerHeight(true);});this.headers.next().each(function(){$(this).height(Math.max(0,maxHeight-$(this).innerHeight()+$(this).height()));}).css("overflow","auto");}else if(heightStyle==="auto"){maxHeight=0;this.headers.next().each(function(){var isVisible=$(this).is(":visible");if(!isVisible){$(this).show();}maxHeight=Math.max(maxHeight,$(this).css("height","").height());if(!isVisible){$(this).hide();}}).height(maxHeight);}},_activate:function(index){var active=this._findActive(index)[0];// Trying to activate the already active panel
	if(active===this.active[0]){return;}// Trying to collapse, simulate a click on the currently active header
	active=active||this.active[0];this._eventHandler({target:active,currentTarget:active,preventDefault:$.noop});},_findActive:function(selector){return typeof selector==="number"?this.headers.eq(selector):$();},_setupEvents:function(event){var events={keydown:"_keydown"};if(event){$.each(event.split(" "),function(index,eventName){events[eventName]="_eventHandler";});}this._off(this.headers.add(this.headers.next()));this._on(this.headers,events);this._on(this.headers.next(),{keydown:"_panelKeyDown"});this._hoverable(this.headers);this._focusable(this.headers);},_eventHandler:function(event){var activeChildren,clickedChildren,options=this.options,active=this.active,clicked=$(event.currentTarget),clickedIsActive=clicked[0]===active[0],collapsing=clickedIsActive&&options.collapsible,toShow=collapsing?$():clicked.next(),toHide=active.next(),eventData={oldHeader:active,oldPanel:toHide,newHeader:collapsing?$():clicked,newPanel:toShow};event.preventDefault();if(// click on active header, but not collapsible
	clickedIsActive&&!options.collapsible||// allow canceling activation
	this._trigger("beforeActivate",event,eventData)===false){return;}options.active=collapsing?false:this.headers.index(clicked);// When the call to ._toggle() comes after the class changes
	// it causes a very odd bug in IE 8 (see #6720)
	this.active=clickedIsActive?$():clicked;this._toggle(eventData);// Switch classes
	// corner classes on the previously active header stay after the animation
	this._removeClass(active,"ui-accordion-header-active","ui-state-active");if(options.icons){activeChildren=active.children(".ui-accordion-header-icon");this._removeClass(activeChildren,null,options.icons.activeHeader)._addClass(activeChildren,null,options.icons.header);}if(!clickedIsActive){this._removeClass(clicked,"ui-accordion-header-collapsed")._addClass(clicked,"ui-accordion-header-active","ui-state-active");if(options.icons){clickedChildren=clicked.children(".ui-accordion-header-icon");this._removeClass(clickedChildren,null,options.icons.header)._addClass(clickedChildren,null,options.icons.activeHeader);}this._addClass(clicked.next(),"ui-accordion-content-active");}},_toggle:function(data){var toShow=data.newPanel,toHide=this.prevShow.length?this.prevShow:data.oldPanel;// Handle activating a panel during the animation for another activation
	this.prevShow.add(this.prevHide).stop(true,true);this.prevShow=toShow;this.prevHide=toHide;if(this.options.animate){this._animate(toShow,toHide,data);}else {toHide.hide();toShow.show();this._toggleComplete(data);}toHide.attr({"aria-hidden":"true"});toHide.prev().attr({"aria-selected":"false","aria-expanded":"false"});// if we're switching panels, remove the old header from the tab order
	// if we're opening from collapsed state, remove the previous header from the tab order
	// if we're collapsing, then keep the collapsing header in the tab order
	if(toShow.length&&toHide.length){toHide.prev().attr({"tabIndex":-1,"aria-expanded":"false"});}else if(toShow.length){this.headers.filter(function(){return parseInt($(this).attr("tabIndex"),10)===0;}).attr("tabIndex",-1);}toShow.attr("aria-hidden","false").prev().attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0});},_animate:function(toShow,toHide,data){var total,easing,duration,that=this,adjust=0,boxSizing=toShow.css("box-sizing"),down=toShow.length&&(!toHide.length||toShow.index()<toHide.index()),animate=this.options.animate||{},options=down&&animate.down||animate,complete=function(){that._toggleComplete(data);};if(typeof options==="number"){duration=options;}if(typeof options==="string"){easing=options;}// fall back from options to animation in case of partial down settings
	easing=easing||options.easing||animate.easing;duration=duration||options.duration||animate.duration;if(!toHide.length){return toShow.animate(this.showProps,duration,easing,complete);}if(!toShow.length){return toHide.animate(this.hideProps,duration,easing,complete);}total=toShow.show().outerHeight();toHide.animate(this.hideProps,{duration:duration,easing:easing,step:function(now,fx){fx.now=Math.round(now);}});toShow.hide().animate(this.showProps,{duration:duration,easing:easing,complete:complete,step:function(now,fx){fx.now=Math.round(now);if(fx.prop!=="height"){if(boxSizing==="content-box"){adjust+=fx.now;}}else if(that.options.heightStyle!=="content"){fx.now=Math.round(total-toHide.outerHeight()-adjust);adjust=0;}}});},_toggleComplete:function(data){var toHide=data.oldPanel,prev=toHide.prev();this._removeClass(toHide,"ui-accordion-content-active");this._removeClass(prev,"ui-accordion-header-active")._addClass(prev,"ui-accordion-header-collapsed");this._trigger("activate",null,data);}});/*!
		 * jQuery UI Menu 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Menu
	//>>group: Widgets
	//>>description: Creates nestable menus.
	//>>docs: https://api.jqueryui.com/menu/
	//>>demos: https://jqueryui.com/menu/
	//>>css.structure: ../../themes/base/core.css
	//>>css.structure: ../../themes/base/menu.css
	//>>css.theme: ../../themes/base/theme.css
	$.widget("ui.menu",{version:"1.14.2",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.lastMousePosition={x:null,y:null};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();this._activateItem(event);},"click .ui-menu-item":function(event){var target=$(event.target);var active=$(this.document[0].activeElement);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":"_activateItem","mousemove .ui-menu-item":"_activateItem",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._menuItems().first();if(!keepActiveItem){this.focus(event,item);}},blur:function(event){this._delay(function(){var notContained=!$.contains(this.element[0],this.document[0].activeElement);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,true);}// Reset the mouseHandled flag
	this.mouseHandled=false;}});},_activateItem: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;}// If the mouse didn't actually move, but the page was scrolled, ignore the event (#9356)
	if(event.clientX===this.lastMousePosition.x&&event.clientY===this.lastMousePosition.y){return;}this.lastMousePosition={x:event.clientX,y:event.clientY};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;}// If the item is already active, there's nothing to do
	if(target.is(".ui-state-active")){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);},_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;},all?0: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._menuItems(this.active.children(".ui-menu")).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;},_menuItems:function(menu){return (menu||this.element).find(this.options.items).filter(".ui-menu-item");},_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").last();}else {next=this.active[direction+"All"](".ui-menu-item").first();}}if(!next||!next.length||!this.active){next=this._menuItems(this.activeMenu)[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.innerHeight();// jQuery 3.2 doesn't include scrollbars in innerHeight, add it back.
	if($.fn.jquery.indexOf("3.2.")===0){height+=this.element[0].offsetHeight-this.element.outerHeight();}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._menuItems(this.activeMenu)[!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.innerHeight();// jQuery 3.2 doesn't include scrollbars in innerHeight, add it back.
	if($.fn.jquery.indexOf("3.2.")===0){height+=this.element[0].offsetHeight-this.element.outerHeight();}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._menuItems(this.activeMenu).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(String.prototype.trim.call($(this).children(".ui-menu-item-wrapper").text()));});}});/*!
		 * jQuery UI Autocomplete 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Autocomplete
	//>>group: Widgets
	//>>description: Lists suggested words as the user is typing.
	//>>docs: https://api.jqueryui.com/autocomplete/
	//>>demos: https://jqueryui.com/autocomplete/
	//>>css.structure: ../../themes/base/core.css
	//>>css.structure: ../../themes/base/autocomplete.css
	//>>css.theme: ../../themes/base/theme.css
	$.widget("ui.autocomplete",{version:"1.14.2",defaultElement:"<input>",options:{appendTo:null,autoFocus:false,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,// Callbacks
	change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,liveRegionTimer:null,_create:function(){// Some browsers only repeat keydown events, not keypress events,
	// so we use the suppressKeyPress flag to determine if we've already
	// handled the keydown event. #7269
	// Unfortunately the code for & in keypress is the same as the up arrow,
	// so we use the suppressKeyPressRepeat flag to avoid handling keypress
	// events when we know the keydown event was used to modify the
	// search term. #7799
	var suppressKeyPress,suppressKeyPressRepeat,suppressInput,nodeName=this.element[0].nodeName.toLowerCase(),isTextarea=nodeName==="textarea",isInput=nodeName==="input";// Textareas are always multi-line
	// Inputs are always single-line, even if inside a contentEditable element
	// All other element types are determined by whether they're contentEditable
	this.isMultiLine=isTextarea||!isInput&&this.element.prop("contentEditable")==="true";this.valueMethod=this.element[isTextarea||isInput?"val":"text"];this.isNewMenu=true;this._addClass("ui-autocomplete-input");this.element.attr("autocomplete","off");this._on(this.element,{keydown:function(event){if(this.element.prop("readOnly")){suppressKeyPress=true;suppressInput=true;suppressKeyPressRepeat=true;return;}suppressKeyPress=false;suppressInput=false;suppressKeyPressRepeat=false;var keyCode=$.ui.keyCode;switch(event.keyCode){case keyCode.PAGE_UP:suppressKeyPress=true;this._move("previousPage",event);break;case keyCode.PAGE_DOWN:suppressKeyPress=true;this._move("nextPage",event);break;case keyCode.UP:suppressKeyPress=true;this._keyEvent("previous",event);break;case keyCode.DOWN:suppressKeyPress=true;this._keyEvent("next",event);break;case keyCode.ENTER:// when menu is open and has focus
	if(this.menu.active){// #6055 - Opera still allows the keypress to occur
	// which causes forms to submit
	suppressKeyPress=true;event.preventDefault();this.menu.select(event);}break;case keyCode.TAB:if(this.menu.active){this.menu.select(event);}break;case keyCode.ESCAPE:if(this.menu.element.is(":visible")){if(!this.isMultiLine){this._value(this.term);}this.close(event);// Different browsers have different default behavior for escape
	// Single press can mean undo or clear
	event.preventDefault();}break;default:suppressKeyPressRepeat=true;// search timeout should be triggered before the input value is changed
	this._searchTimeout(event);break;}},keypress:function(event){if(suppressKeyPress){suppressKeyPress=false;if(!this.isMultiLine||this.menu.element.is(":visible")){event.preventDefault();}return;}if(suppressKeyPressRepeat){return;}// Replicate some key handlers to allow them to repeat in Firefox and Opera
	var keyCode=$.ui.keyCode;switch(event.keyCode){case keyCode.PAGE_UP:this._move("previousPage",event);break;case keyCode.PAGE_DOWN:this._move("nextPage",event);break;case keyCode.UP:this._keyEvent("previous",event);break;case keyCode.DOWN:this._keyEvent("next",event);break;}},input:function(event){if(suppressInput){suppressInput=false;event.preventDefault();return;}this._searchTimeout(event);},focus:function(){this.selectedItem=null;this.previous=this._value();},blur:function(event){clearTimeout(this.searching);this.close(event);this._change(event);}});this._initSource();this.menu=$("<ul>").appendTo(this._appendTo()).menu({// disable ARIA support, the live region takes care of that
	role:null}).hide().menu("instance");this._addClass(this.menu.element,"ui-autocomplete","ui-front");this._on(this.menu.element,{mousedown:function(event){// Prevent moving focus out of the text field
	event.preventDefault();},menufocus:function(event,ui){var label,item;// Support: Firefox
	// Prevent accidental activation of menu items in Firefox (#7024 #9118)
	if(this.isNewMenu){this.isNewMenu=false;if(event.originalEvent&&/^mouse/.test(event.originalEvent.type)){this.menu.blur();this.document.one("mousemove",function(){$(event.target).trigger(event.originalEvent);});return;}}item=ui.item.data("ui-autocomplete-item");if(false!==this._trigger("focus",event,{item:item})){// use value to match what will end up in the input, if it was a key event
	if(event.originalEvent&&/^key/.test(event.originalEvent.type)){this._value(item.value);}}// Announce the value in the liveRegion
	label=ui.item.attr("aria-label")||item.value;if(label&&String.prototype.trim.call(label).length){clearTimeout(this.liveRegionTimer);this.liveRegionTimer=this._delay(function(){this.liveRegion.html($("<div>").text(label));},100);}},menuselect:function(event,ui){var item=ui.item.data("ui-autocomplete-item"),previous=this.previous;// Only trigger when focus was lost (click on menu)
	if(this.element[0]!==this.document[0].activeElement){this.element.trigger("focus");this.previous=previous;}if(false!==this._trigger("select",event,{item:item})){this._value(item.value);}// reset the term after the select event
	// this allows custom select handling to work properly
	this.term=this._value();this.close(event);this.selectedItem=item;}});this.liveRegion=$("<div>",{role:"status","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body);this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible");// Turning off autocomplete prevents the browser from remembering the
	// value when navigating through history, so we re-enable autocomplete
	// if the page is unloaded before the widget is destroyed. #7790
	this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete");}});},_destroy:function(){clearTimeout(this.searching);this.element.removeAttr("autocomplete");this.menu.element.remove();this.liveRegion.remove();},_setOption:function(key,value){this._super(key,value);if(key==="source"){this._initSource();}if(key==="appendTo"){this.menu.element.appendTo(this._appendTo());}if(key==="disabled"&&value&&this.xhr){this.xhr.abort();}},_isEventTargetInWidget:function(event){var menuElement=this.menu.element[0];return event.target===this.element[0]||event.target===menuElement||$.contains(menuElement,event.target);},_closeOnClickOutside:function(event){if(!this._isEventTargetInWidget(event)){this.close();}},_appendTo:function(){var element=this.options.appendTo;if(element){element=element.jquery||element.nodeType?$(element):this.document.find(element).eq(0);}if(!element||!element[0]){element=this.element.closest(".ui-front, dialog");}if(!element.length){element=this.document[0].body;}return element;},_initSource:function(){var array,url,that=this;if(Array.isArray(this.options.source)){array=this.options.source;this.source=function(request,response){response($.ui.autocomplete.filter(array,request.term));};}else if(typeof this.options.source==="string"){url=this.options.source;this.source=function(request,response){if(that.xhr){that.xhr.abort();}that.xhr=$.ajax({url:url,data:request,dataType:"json",success:function(data){response(data);},error:function(){response([]);}});};}else {this.source=this.options.source;}},_searchTimeout:function(event){clearTimeout(this.searching);this.searching=this._delay(function(){// Search if the value has changed, or if the user retypes the same value (see #7434)
	var equalValues=this.term===this._value(),menuVisible=this.menu.element.is(":visible"),modifierKey=event.altKey||event.ctrlKey||event.metaKey||event.shiftKey;if(!equalValues||equalValues&&!menuVisible&&!modifierKey){this.selectedItem=null;this.search(null,event);}},this.options.delay);},search:function(value,event){value=value!=null?value:this._value();// Always save the actual value, not the one passed as an argument
	this.term=this._value();if(value.length<this.options.minLength){return this.close(event);}if(this._trigger("search",event)===false){return;}return this._search(value);},_search:function(value){this.pending++;this._addClass("ui-autocomplete-loading");this.cancelSearch=false;this.source({term:value},this._response());},_response:function(){var index=++this.requestIndex;return function(content){if(index===this.requestIndex){this.__response(content);}this.pending--;if(!this.pending){this._removeClass("ui-autocomplete-loading");}}.bind(this);},__response:function(content){if(content){content=this._normalize(content);}this._trigger("response",null,{content:content});if(!this.options.disabled&&content&&content.length&&!this.cancelSearch){this._suggest(content);this._trigger("open");}else {// use ._close() instead of .close() so we don't cancel future searches
	this._close();}},close:function(event){this.cancelSearch=true;this._close(event);},_close:function(event){// Remove the handler that closes the menu on outside clicks
	this._off(this.document,"mousedown");if(this.menu.element.is(":visible")){this.menu.element.hide();this.menu.blur();this.isNewMenu=true;this._trigger("close",event);}},_change:function(event){if(this.previous!==this._value()){this._trigger("change",event,{item:this.selectedItem});}},_normalize:function(items){// assume all items have the right format when the first item is complete
	if(items.length&&items[0].label&&items[0].value){return items;}return $.map(items,function(item){if(typeof item==="string"){return {label:item,value:item};}return $.extend({},item,{label:item.label||item.value,value:item.value||item.label});});},_suggest:function(items){var ul=this.menu.element.empty();this._renderMenu(ul,items);this.isNewMenu=true;this.menu.refresh();// Size and position menu
	ul.show();this._resizeMenu();ul.position($.extend({of:this.element},this.options.position));if(this.options.autoFocus){this.menu.next();}// Listen for interactions outside of the widget (#6642)
	this._on(this.document,{mousedown:"_closeOnClickOutside"});},_resizeMenu:function(){var ul=this.menu.element;ul.outerWidth(Math.max(// Firefox wraps long text (possibly a rounding bug)
	// so we add 1px to avoid the wrapping (#7513)
	ul.width("").outerWidth()+1,this.element.outerWidth()));},_renderMenu:function(ul,items){var that=this;$.each(items,function(index,item){that._renderItemData(ul,item);});},_renderItemData:function(ul,item){return this._renderItem(ul,item).data("ui-autocomplete-item",item);},_renderItem:function(ul,item){return $("<li>").append($("<div>").text(item.label)).appendTo(ul);},_move:function(direction,event){if(!this.menu.element.is(":visible")){this.search(null,event);return;}if(this.menu.isFirstItem()&&/^previous/.test(direction)||this.menu.isLastItem()&&/^next/.test(direction)){if(!this.isMultiLine){this._value(this.term);}this.menu.blur();return;}this.menu[direction](event);},widget:function(){return this.menu.element;},_value:function(){return this.valueMethod.apply(this.element,arguments);},_keyEvent:function(keyEvent,event){if(!this.isMultiLine||this.menu.element.is(":visible")){this._move(keyEvent,event);// Prevents moving cursor to beginning/end of the text field in some browsers
	event.preventDefault();}}});$.extend($.ui.autocomplete,{escapeRegex:function(value){return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&");},filter:function(array,term){var matcher=new RegExp($.ui.autocomplete.escapeRegex(term),"i");return $.grep(array,function(value){return matcher.test(value.label||value.value||value);});}});// Live region extension, adding a `messages` option
	// NOTE: This is an experimental API. We are still investigating
	// a full solution for string manipulation and internationalization.
	$.widget("ui.autocomplete",$.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(amount){return amount+(amount>1?" results are":" result is")+" available, use up and down arrow keys to navigate.";}}},__response:function(content){var message;this._superApply(arguments);if(this.options.disabled||this.cancelSearch){return;}if(content&&content.length){message=this.options.messages.results(content.length);}else {message=this.options.messages.noResults;}clearTimeout(this.liveRegionTimer);this.liveRegionTimer=this._delay(function(){this.liveRegion.html($("<div>").text(message));},100);}});$.ui.autocomplete;/*!
		 * jQuery UI Controlgroup 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Controlgroup
	//>>group: Widgets
	//>>description: Visually groups form control widgets
	//>>docs: https://api.jqueryui.com/controlgroup/
	//>>demos: https://jqueryui.com/controlgroup/
	//>>css.structure: ../../themes/base/core.css
	//>>css.structure: ../../themes/base/controlgroup.css
	//>>css.theme: ../../themes/base/theme.css
	var controlgroupCornerRegex=/ui-corner-([a-z]){2,6}/g;$.widget("ui.controlgroup",{version:"1.14.2",defaultElement:"<div>",options:{direction:"horizontal",disabled:null,onlyVisible:true,items:{"button":"input[type=button], input[type=submit], input[type=reset], button, a","controlgroupLabel":".ui-controlgroup-label","checkboxradio":"input[type='checkbox'], input[type='radio']","selectmenu":"select","spinner":".ui-spinner-input"}},_create:function(){this._enhance();},// To support the enhanced option in jQuery Mobile, we isolate DOM manipulation
	_enhance:function(){this.element.attr("role","toolbar");this.refresh();},_destroy:function(){this._callChildMethod("destroy");this.childWidgets.removeData("ui-controlgroup-data");this.element.removeAttr("role");if(this.options.items.controlgroupLabel){this.element.find(this.options.items.controlgroupLabel).find(".ui-controlgroup-label-contents").contents().unwrap();}},_initWidgets:function(){var that=this,childWidgets=[];// First we iterate over each of the items options
	$.each(this.options.items,function(widget,selector){var labels;var options={};// Make sure the widget has a selector set
	if(!selector){return;}if(widget==="controlgroupLabel"){labels=that.element.find(selector);labels.each(function(){var element=$(this);if(element.children(".ui-controlgroup-label-contents").length){return;}element.contents().wrapAll("<span class='ui-controlgroup-label-contents'></span>");});that._addClass(labels,null,"ui-widget ui-widget-content ui-state-default");childWidgets=childWidgets.concat(labels.get());return;}// Make sure the widget actually exists
	if(!$.fn[widget]){return;}// We assume everything is in the middle to start because we can't determine
	// first / last elements until all enhancments are done.
	if(that["_"+widget+"Options"]){options=that["_"+widget+"Options"]("middle");}else {options={classes:{}};}// Find instances of this widget inside controlgroup and init them
	that.element.find(selector).each(function(){var element=$(this);var instance=element[widget]("instance");// We need to clone the default options for this type of widget to avoid
	// polluting the variable options which has a wider scope than a single widget.
	var instanceOptions=$.widget.extend({},options);// If the button is the child of a spinner ignore it
	// TODO: Find a more generic solution
	if(widget==="button"&&element.parent(".ui-spinner").length){return;}// Create the widget if it doesn't exist
	if(!instance){instance=element[widget]()[widget]("instance");}if(instance){instanceOptions.classes=that._resolveClassesValues(instanceOptions.classes,instance);}element[widget](instanceOptions);// Store an instance of the controlgroup to be able to reference
	// from the outermost element for changing options and refresh
	var widgetElement=element[widget]("widget");$.data(widgetElement[0],"ui-controlgroup-data",instance?instance:element[widget]("instance"));childWidgets.push(widgetElement[0]);});});this.childWidgets=$($.uniqueSort(childWidgets));this._addClass(this.childWidgets,"ui-controlgroup-item");},_callChildMethod:function(method){this.childWidgets.each(function(){var element=$(this),data=element.data("ui-controlgroup-data");if(data&&data[method]){data[method]();}});},_updateCornerClass:function(element,position){var remove="ui-corner-top ui-corner-bottom ui-corner-left ui-corner-right ui-corner-all";var add=this._buildSimpleOptions(position,"label").classes.label;this._removeClass(element,null,remove);this._addClass(element,null,add);},_buildSimpleOptions:function(position,key){var direction=this.options.direction==="vertical";var result={classes:{}};result.classes[key]={"middle":"","first":"ui-corner-"+(direction?"top":"left"),"last":"ui-corner-"+(direction?"bottom":"right"),"only":"ui-corner-all"}[position];return result;},_spinnerOptions:function(position){var options=this._buildSimpleOptions(position,"ui-spinner");options.classes["ui-spinner-up"]="";options.classes["ui-spinner-down"]="";return options;},_buttonOptions:function(position){return this._buildSimpleOptions(position,"ui-button");},_checkboxradioOptions:function(position){return this._buildSimpleOptions(position,"ui-checkboxradio-label");},_selectmenuOptions:function(position){var direction=this.options.direction==="vertical";return {width:direction?"auto":false,classes:{middle:{"ui-selectmenu-button-open":"","ui-selectmenu-button-closed":""},first:{"ui-selectmenu-button-open":"ui-corner-"+(direction?"top":"tl"),"ui-selectmenu-button-closed":"ui-corner-"+(direction?"top":"left")},last:{"ui-selectmenu-button-open":direction?"":"ui-corner-tr","ui-selectmenu-button-closed":"ui-corner-"+(direction?"bottom":"right")},only:{"ui-selectmenu-button-open":"ui-corner-top","ui-selectmenu-button-closed":"ui-corner-all"}}[position]};},_resolveClassesValues:function(classes,instance){var result={};$.each(classes,function(key){var current=instance.options.classes[key]||"";current=String.prototype.trim.call(current.replace(controlgroupCornerRegex,""));result[key]=(current+" "+classes[key]).replace(/\s+/g," ");});return result;},_setOption:function(key,value){if(key==="direction"){this._removeClass("ui-controlgroup-"+this.options.direction);}this._super(key,value);if(key==="disabled"){this._callChildMethod(value?"disable":"enable");return;}this.refresh();},refresh:function(){var children,that=this;this._addClass("ui-controlgroup ui-controlgroup-"+this.options.direction);if(this.options.direction==="horizontal"){this._addClass(null,"ui-helper-clearfix");}this._initWidgets();children=this.childWidgets;// We filter here because we need to track all childWidgets not just the visible ones
	if(this.options.onlyVisible){children=children.filter(":visible");}if(children.length){// We do this last because we need to make sure all enhancment is done
	// before determining first and last
	$.each(["first","last"],function(index,value){var instance=children[value]().data("ui-controlgroup-data");if(instance&&that["_"+instance.widgetName+"Options"]){var options=that["_"+instance.widgetName+"Options"](children.length===1?"only":value);options.classes=that._resolveClassesValues(options.classes,instance);instance.element[instance.widgetName](options);}else {that._updateCornerClass(children[value](),value);}});// Finally call the refresh method on each of the child widgets.
	this._callChildMethod("refresh");}}});/*!
		 * jQuery UI Checkboxradio 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Checkboxradio
	//>>group: Widgets
	//>>description: Enhances a form with multiple themeable checkboxes or radio buttons.
	//>>docs: https://api.jqueryui.com/checkboxradio/
	//>>demos: https://jqueryui.com/checkboxradio/
	//>>css.structure: ../../themes/base/core.css
	//>>css.structure: ../../themes/base/button.css
	//>>css.structure: ../../themes/base/checkboxradio.css
	//>>css.theme: ../../themes/base/theme.css
	$.widget("ui.checkboxradio",[$.ui.formResetMixin,{version:"1.14.2",options:{disabled:null,label:null,icon:true,classes:{"ui-checkboxradio-label":"ui-corner-all","ui-checkboxradio-icon":"ui-corner-all"}},_getCreateOptions:function(){var disabled,labels,labelContents;var options=this._super()||{};// We read the type here, because it makes more sense to throw a element type error first,
	// rather then the error for lack of a label. Often if its the wrong type, it
	// won't have a label (e.g. calling on a div, btn, etc)
	this._readType();labels=this.element.labels();// If there are multiple labels, use the last one
	this.label=$(labels[labels.length-1]);if(!this.label.length){$.error("No label found for checkboxradio widget");}this.originalLabel="";// We need to get the label text but this may also need to make sure it does not contain the
	// input itself.
	// The label contents could be text, html, or a mix. We wrap all elements
	// and read the wrapper's `innerHTML` to get a string representation of
	// the label, without the input as part of it.
	labelContents=this.label.contents().not(this.element[0]);if(labelContents.length){this.originalLabel+=labelContents.clone().wrapAll("<div></div>").parent().html();}// Set the label option if we found label text
	if(this.originalLabel){options.label=this.originalLabel;}disabled=this.element[0].disabled;if(disabled!=null){options.disabled=disabled;}return options;},_create:function(){var checked=this.element[0].checked;this._bindFormResetHandler();if(this.options.disabled==null){this.options.disabled=this.element[0].disabled;}this._setOption("disabled",this.options.disabled);this._addClass("ui-checkboxradio","ui-helper-hidden-accessible");this._addClass(this.label,"ui-checkboxradio-label","ui-button ui-widget");if(this.type==="radio"){this._addClass(this.label,"ui-checkboxradio-radio-label");}if(this.options.label&&this.options.label!==this.originalLabel){this._updateLabel();}else if(this.originalLabel){this.options.label=this.originalLabel;}this._enhance();if(checked){this._addClass(this.label,"ui-checkboxradio-checked","ui-state-active");}this._on({change:"_toggleClasses",focus:function(){this._addClass(this.label,null,"ui-state-focus ui-visual-focus");},blur:function(){this._removeClass(this.label,null,"ui-state-focus ui-visual-focus");}});},_readType:function(){var nodeName=this.element[0].nodeName.toLowerCase();this.type=this.element[0].type;if(nodeName!=="input"||!/radio|checkbox/.test(this.type)){$.error("Can't create checkboxradio on element.nodeName="+nodeName+" and element.type="+this.type);}},// Support jQuery Mobile enhanced option
	_enhance:function(){this._updateIcon(this.element[0].checked);},widget:function(){return this.label;},_getRadioGroup:function(){var group;var name=this.element[0].name;var nameSelector="input[name='"+CSS.escape(name)+"']";if(!name){return $([]);}if(this.form.length){group=$(this.form[0].elements).filter(nameSelector);}else {// Not inside a form, check all inputs that also are not inside a form
	group=$(nameSelector).filter(function(){return $($(this).prop("form")).length===0;});}return group.not(this.element);},_toggleClasses:function(){var checked=this.element[0].checked;this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",checked);if(this.options.icon&&this.type==="checkbox"){this._toggleClass(this.icon,null,"ui-icon-check ui-state-checked",checked)._toggleClass(this.icon,null,"ui-icon-blank",!checked);}if(this.type==="radio"){this._getRadioGroup().each(function(){var instance=$(this).checkboxradio("instance");if(instance){instance._removeClass(instance.label,"ui-checkboxradio-checked","ui-state-active");}});}},_destroy:function(){this._unbindFormResetHandler();if(this.icon){this.icon.remove();this.iconSpace.remove();}},_setOption:function(key,value){// We don't allow the value to be set to nothing
	if(key==="label"&&!value){return;}this._super(key,value);if(key==="disabled"){this._toggleClass(this.label,null,"ui-state-disabled",value);this.element[0].disabled=value;// Don't refresh when setting disabled
	return;}this.refresh();},_updateIcon:function(checked){var toAdd="ui-icon ui-icon-background ";if(this.options.icon){if(!this.icon){this.icon=$("<span>");this.iconSpace=$("<span> </span>");this._addClass(this.iconSpace,"ui-checkboxradio-icon-space");}if(this.type==="checkbox"){toAdd+=checked?"ui-icon-check ui-state-checked":"ui-icon-blank";this._removeClass(this.icon,null,checked?"ui-icon-blank":"ui-icon-check");}else {toAdd+="ui-icon-blank";}this._addClass(this.icon,"ui-checkboxradio-icon",toAdd);if(!checked){this._removeClass(this.icon,null,"ui-icon-check ui-state-checked");}this.icon.prependTo(this.label).after(this.iconSpace);}else if(this.icon!==undefined){this.icon.remove();this.iconSpace.remove();delete this.icon;}},_updateLabel:function(){// Remove the contents of the label ( minus the icon, icon space, and input )
	var contents=this.label.contents().not(this.element[0]);if(this.icon){contents=contents.not(this.icon[0]);}if(this.iconSpace){contents=contents.not(this.iconSpace[0]);}contents.remove();this.label.append(this.options.label);},refresh:function(){var checked=this.element[0].checked,isDisabled=this.element[0].disabled;this._updateIcon(checked);this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",checked);if(this.options.label!==null){this._updateLabel();}if(isDisabled!==this.options.disabled){this._setOptions({"disabled":isDisabled});}}}]);$.ui.checkboxradio;/*!
		 * jQuery UI Button 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Button
	//>>group: Widgets
	//>>description: Enhances a form with themeable buttons.
	//>>docs: https://api.jqueryui.com/button/
	//>>demos: https://jqueryui.com/button/
	//>>css.structure: ../../themes/base/core.css
	//>>css.structure: ../../themes/base/button.css
	//>>css.theme: ../../themes/base/theme.css
	$.widget("ui.button",{version:"1.14.2",defaultElement:"<button>",options:{classes:{"ui-button":"ui-corner-all"},disabled:null,icon:null,iconPosition:"beginning",label:null,showLabel:true},_getCreateOptions:function(){var disabled,// This is to support cases like in jQuery Mobile where the base widget does have
	// an implementation of _getCreateOptions
	options=this._super()||{};this.isInput=this.element.is("input");disabled=this.element[0].disabled;if(disabled!=null){options.disabled=disabled;}this.originalLabel=this.isInput?this.element.val():this.element.html();if(this.originalLabel){options.label=this.originalLabel;}return options;},_create:function(){if(!this.option.showLabel&!this.options.icon){this.options.showLabel=true;}// We have to check the option again here even though we did in _getCreateOptions,
	// because null may have been passed on init which would override what was set in
	// _getCreateOptions
	if(this.options.disabled==null){this.options.disabled=this.element[0].disabled||false;}this.hasTitle=!!this.element.attr("title");// Check to see if the label needs to be set or if its already correct
	if(this.options.label&&this.options.label!==this.originalLabel){if(this.isInput){this.element.val(this.options.label);}else {this.element.html(this.options.label);}}this._addClass("ui-button","ui-widget");this._setOption("disabled",this.options.disabled);this._enhance();if(this.element.is("a")){this._on({"keyup":function(event){if(event.keyCode===$.ui.keyCode.SPACE){event.preventDefault();// If a native click is available use it, so we
	// actually cause navigation. Otherwise, just trigger
	// a click event.
	if(this.element[0].click){this.element[0].click();}else {this.element.trigger("click");}}}});}},_enhance:function(){if(!this.element.is("button")){this.element.attr("role","button");}if(this.options.icon){this._updateIcon("icon",this.options.icon);this._updateTooltip();}},_updateTooltip:function(){this.title=this.element.attr("title");if(!this.options.showLabel&&!this.title){this.element.attr("title",this.options.label);}},_updateIcon:function(option,value){var icon=option!=="iconPosition",position=icon?this.options.iconPosition:value,displayBlock=position==="top"||position==="bottom";// Create icon
	if(!this.icon){this.icon=$("<span>");this._addClass(this.icon,"ui-button-icon","ui-icon");if(!this.options.showLabel){this._addClass("ui-button-icon-only");}}else if(icon){// If we are updating the icon remove the old icon class
	this._removeClass(this.icon,null,this.options.icon);}// If we are updating the icon add the new icon class
	if(icon){this._addClass(this.icon,null,value);}this._attachIcon(position);// If the icon is on top or bottom we need to add the ui-widget-icon-block class and remove
	// the iconSpace if there is one.
	if(displayBlock){this._addClass(this.icon,null,"ui-widget-icon-block");if(this.iconSpace){this.iconSpace.remove();}}else {// Position is beginning or end so remove the ui-widget-icon-block class and add the
	// space if it does not exist
	if(!this.iconSpace){this.iconSpace=$("<span> </span>");this._addClass(this.iconSpace,"ui-button-icon-space");}this._removeClass(this.icon,null,"ui-wiget-icon-block");this._attachIconSpace(position);}},_destroy:function(){this.element.removeAttr("role");if(this.icon){this.icon.remove();}if(this.iconSpace){this.iconSpace.remove();}if(!this.hasTitle){this.element.removeAttr("title");}},_attachIconSpace:function(iconPosition){this.icon[/^(?:end|bottom)/.test(iconPosition)?"before":"after"](this.iconSpace);},_attachIcon:function(iconPosition){this.element[/^(?:end|bottom)/.test(iconPosition)?"append":"prepend"](this.icon);},_setOptions:function(options){var newShowLabel=options.showLabel===undefined?this.options.showLabel:options.showLabel,newIcon=options.icon===undefined?this.options.icon:options.icon;if(!newShowLabel&&!newIcon){options.showLabel=true;}this._super(options);},_setOption:function(key,value){if(key==="icon"){if(value){this._updateIcon(key,value);}else if(this.icon){this.icon.remove();if(this.iconSpace){this.iconSpace.remove();}}}if(key==="iconPosition"){this._updateIcon(key,value);}// Make sure we can't end up with a button that has neither text nor icon
	if(key==="showLabel"){this._toggleClass("ui-button-icon-only",null,!value);this._updateTooltip();}if(key==="label"){if(this.isInput){this.element.val(value);}else {// If there is an icon, append it, else nothing then append the value
	// this avoids removal of the icon when setting label text
	this.element.html(value);if(this.icon){this._attachIcon(this.options.iconPosition);this._attachIconSpace(this.options.iconPosition);}}}this._super(key,value);if(key==="disabled"){this._toggleClass(null,"ui-state-disabled",value);this.element[0].disabled=value;if(value){this.element.trigger("blur");}}},refresh:function(){// Make sure to only check disabled if its an element that supports this otherwise
	// check for the disabled class to determine state
	var isDisabled=this.element.is("input, button")?this.element[0].disabled:this.element.hasClass("ui-button-disabled");if(isDisabled!==this.options.disabled){this._setOptions({disabled:isDisabled});}this._updateTooltip();}});// DEPRECATED
	if($.uiBackCompat===true){// Text and Icons options
	$.widget("ui.button",$.ui.button,{options:{text:true,icons:{primary:null,secondary:null}},_create:function(){if(this.options.showLabel&&!this.options.text){this.options.showLabel=this.options.text;}if(!this.options.showLabel&&this.options.text){this.options.text=this.options.showLabel;}if(!this.options.icon&&(this.options.icons.primary||this.options.icons.secondary)){if(this.options.icons.primary){this.options.icon=this.options.icons.primary;}else {this.options.icon=this.options.icons.secondary;this.options.iconPosition="end";}}else if(this.options.icon){this.options.icons.primary=this.options.icon;}this._super();},_setOption:function(key,value){if(key==="text"){this._super("showLabel",value);return;}if(key==="showLabel"){this.options.text=value;}if(key==="icon"){this.options.icons.primary=value;}if(key==="icons"){if(value.primary){this._super("icon",value.primary);this._super("iconPosition","beginning");}else if(value.secondary){this._super("icon",value.secondary);this._super("iconPosition","end");}}this._superApply(arguments);}});$.fn.button=function(orig){return function(options){var isMethodCall=typeof options==="string";var args=Array.prototype.slice.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 type=$(this).attr("type");var name=type!=="checkbox"&&type!=="radio"?"button":"checkboxradio";var instance=$.data(this,"ui-"+name);if(options==="instance"){returnValue=instance;return false;}if(!instance){return $.error("cannot call methods on button"+" prior to initialization; "+"attempted to call method '"+options+"'");}if(typeof instance[options]!=="function"||options.charAt(0)==="_"){return $.error("no such method '"+options+"' for button"+" 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 type=$(this).attr("type");var name=type!=="checkbox"&&type!=="radio"?"button":"checkboxradio";var instance=$.data(this,"ui-"+name);if(instance){instance.option(options||{});if(instance._init){instance._init();}}else {if(name==="button"){orig.call($(this),options);return;}$(this).checkboxradio($.extend({icon:false},options));}});}return returnValue;};}($.fn.button);$.fn.buttonset=function(){if(!$.ui.controlgroup){$.error("Controlgroup widget missing");}if(arguments[0]==="option"&&arguments[1]==="items"&&arguments[2]){return this.controlgroup.apply(this,[arguments[0],"items.button",arguments[2]]);}if(arguments[0]==="option"&&arguments[1]==="items"){return this.controlgroup.apply(this,[arguments[0],"items.button"]);}if(typeof arguments[0]==="object"&&arguments[0].items){arguments[0].items={button:arguments[0].items};}return this.controlgroup.apply(this,arguments);};}$.ui.button;/* eslint-disable max-len *//*!
		 * jQuery UI Datepicker 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Datepicker
	//>>group: Widgets
	//>>description: Displays a calendar from an input or inline for selecting dates.
	//>>docs: https://api.jqueryui.com/datepicker/
	//>>demos: https://jqueryui.com/datepicker/
	//>>css.structure: ../../themes/base/core.css
	//>>css.structure: ../../themes/base/datepicker.css
	//>>css.theme: ../../themes/base/theme.css
	$.extend($.ui,{datepicker:{version:"1.14.2"}});var datepicker_instActive;function datepicker_getZindex(elem){var position,value;while(elem.length&&elem[0]!==document){// Ignore z-index if position is set to a value where z-index is ignored by the browser
	// This makes behavior of this function consistent across browsers
	// WebKit always returns auto if the element is positioned
	position=elem.css("position");if(position==="absolute"||position==="relative"||position==="fixed"){// IE returns 0 when zIndex is not specified
	// other browsers return a string
	// we ignore the case of nested elements with an explicit value of 0
	// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
	value=parseInt(elem.css("zIndex"),10);if(!isNaN(value)&&value!==0){return value;}}elem=elem.parent();}return 0;}/* Date picker manager.
		   Use the singleton instance of this class, $.datepicker, to interact with the date picker.
		   Settings for (groups of) date pickers are maintained in an instance object,
		   allowing multiple different settings on the same page. */function Datepicker(){this._curInst=null;// The current instance in use
	this._keyEvent=false;// If the last event was a key event
	this._disabledInputs=[];// List of date picker inputs that have been disabled
	this._datepickerShowing=false;// True if the popup picker is showing , false if not
	this._inDialog=false;// True if showing within a "dialog", false if not
	this._mainDivId="ui-datepicker-div";// The ID of the main datepicker division
	this._inlineClass="ui-datepicker-inline";// The name of the inline marker class
	this._appendClass="ui-datepicker-append";// The name of the append marker class
	this._triggerClass="ui-datepicker-trigger";// The name of the trigger marker class
	this._dialogClass="ui-datepicker-dialog";// The name of the dialog marker class
	this._disableClass="ui-datepicker-disabled";// The name of the disabled covering marker class
	this._unselectableClass="ui-datepicker-unselectable";// The name of the unselectable cell marker class
	this._currentClass="ui-datepicker-current-day";// The name of the current day marker class
	this._dayOverClass="ui-datepicker-days-cell-over";// The name of the day hover marker class
	this.regional=[];// Available regional settings, indexed by language code
	this.regional[""]={// Default regional settings
	closeText:"Done",// Display text for close link
	prevText:"Prev",// Display text for previous month link
	nextText:"Next",// Display text for next month link
	currentText:"Today",// Display text for current month link
	monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],// Names of months for drop-down and formatting
	monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],// For formatting
	dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],// For formatting
	dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],// For formatting
	dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],// Column headings for days starting at Sunday
	weekHeader:"Wk",// Column header for week of the year
	dateFormat:"mm/dd/yy",// See format options on parseDate
	firstDay:0,// The first day of the week, Sun = 0, Mon = 1, ...
	isRTL:false,// True if right-to-left language, false if left-to-right
	showMonthAfterYear:false,// True if the year select precedes month, false for month then year
	yearSuffix:"",// Additional text to append to the year in the month headers,
	selectMonthLabel:"Select month",// Invisible label for month selector
	selectYearLabel:"Select year"// Invisible label for year selector
	};this._defaults={// Global defaults for all the date picker instances
	showOn:"focus",// "focus" for popup on focus,
	// "button" for trigger button, or "both" for either
	showAnim:"fadeIn",// Name of jQuery animation for popup
	showOptions:{},// Options for enhanced animations
	defaultDate:null,// Used when field is blank: actual date,
	// +/-number for offset from today, null for today
	appendText:"",// Display text following the input box, e.g. showing the format
	buttonText:"...",// Text for trigger button
	buttonImage:"",// URL for trigger button image
	buttonImageOnly:false,// True if the image appears alone, false if it appears on a button
	hideIfNoPrevNext:false,// True to hide next/previous month links
	// if not applicable, false to just disable them
	navigationAsDateFormat:false,// True if date formatting applied to prev/today/next links
	gotoCurrent:false,// True if today link goes back to current selection instead
	changeMonth:false,// True if month can be selected directly, false if only prev/next
	changeYear:false,// True if year can be selected directly, false if only prev/next
	yearRange:"c-10:c+10",// Range of years to display in drop-down,
	// either relative to today's year (-nn:+nn), relative to currently displayed year
	// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
	showOtherMonths:false,// True to show dates in other months, false to leave blank
	selectOtherMonths:false,// True to allow selection of dates in other months, false for unselectable
	showWeek:false,// True to show week of the year, false to not show it
	calculateWeek:this.iso8601Week,// How to calculate the week of the year,
	// takes a Date and returns the number of the week for it
	shortYearCutoff:"+10",// Short year values < this are in the current century,
	// > this are in the previous century,
	// string value starting with "+" for current year + value
	minDate:null,// The earliest selectable date, or null for no limit
	maxDate:null,// The latest selectable date, or null for no limit
	duration:"fast",// Duration of display/closure
	beforeShowDay:null,// Function that takes a date and returns an array with
	// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
	// [2] = cell title (optional), e.g. $.datepicker.noWeekends
	beforeShow:null,// Function that takes an input field and
	// returns a set of custom settings for the date picker
	onSelect:null,// Define a callback function when a date is selected
	onChangeMonthYear:null,// Define a callback function when the month or year is changed
	onClose:null,// Define a callback function when the datepicker is closed
	onUpdateDatepicker:null,// Define a callback function when the datepicker is updated
	numberOfMonths:1,// Number of months to show at a time
	showCurrentAtPos:0,// The position in multipe months at which to show the current month (starting at 0)
	stepMonths:1,// Number of months to step back/forward
	stepBigMonths:12,// Number of months to step back/forward for the big links
	altField:"",// Selector for an alternate field to store selected dates into
	altFormat:"",// The date format to use for the alternate field
	constrainInput:true,// The input is constrained by the current date format
	showButtonPanel:false,// True to show button panel, false to not show it
	autoSize:false,// True to size the input for the date format, false to leave as is
	disabled:false// The initial disabled state
	};$.extend(this._defaults,this.regional[""]);this.regional.en=$.extend(true,{},this.regional[""]);this.regional["en-US"]=$.extend(true,{},this.regional.en);this.dpDiv=datepicker_bindHover($("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"));}$.extend(Datepicker.prototype,{/* Class name added to elements to indicate already configured with a date picker. */markerClassName:"hasDatepicker",//Keep track of the maximum number of rows displayed (see #7043)
	maxRows:4,// TODO rename to "widget" when switching to widget factory
	_widgetDatepicker:function(){return this.dpDiv;},/* Override the default settings for all instances of the date picker.
			 * @param  settings  object - the new settings to use as defaults (anonymous object)
			 * @return the manager object
			 */setDefaults:function(settings){datepicker_extendRemove(this._defaults,settings||{});return this;},/* Attach the date picker to a jQuery selection.
			 * @param  target	element - the target input field or division or span
			 * @param  settings  object - the new settings to use for this date picker instance (anonymous)
			 */_attachDatepicker:function(target,settings){var nodeName,inline,inst;nodeName=target.nodeName.toLowerCase();inline=nodeName==="div"||nodeName==="span";if(!target.id){this.uuid+=1;target.id="dp"+this.uuid;}inst=this._newInst($(target),inline);inst.settings=$.extend({},settings||{});if(nodeName==="input"){this._connectDatepicker(target,inst);}else if(inline){this._inlineDatepicker(target,inst);}},/* Create a new instance object. */_newInst:function(target,inline){var id=target[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1");// escape jQuery meta chars
	return {id:id,input:target,// associated target
	selectedDay:0,selectedMonth:0,selectedYear:0,// current selection
	drawMonth:0,drawYear:0,// month being drawn
	inline:inline,// is datepicker inline or not
	dpDiv:!inline?this.dpDiv:// presentation div
	datepicker_bindHover($("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))};},/* Attach the date picker to an input field. */_connectDatepicker:function(target,inst){var input=$(target);inst.append=$([]);inst.trigger=$([]);if(input.hasClass(this.markerClassName)){return;}this._attachments(input,inst);input.addClass(this.markerClassName).on("keydown",this._doKeyDown).on("keypress",this._doKeyPress).on("keyup",this._doKeyUp);this._autoSize(inst);$.data(target,"datepicker",inst);//If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
	if(inst.settings.disabled){this._disableDatepicker(target);}},/* Make attachments based on settings. */_attachments:function(input,inst){var showOn,buttonText,buttonImage,appendText=this._get(inst,"appendText"),isRTL=this._get(inst,"isRTL");if(inst.append){inst.append.remove();}if(appendText){inst.append=$("<span>").addClass(this._appendClass).text(appendText);input[isRTL?"before":"after"](inst.append);}input.off("focus",this._showDatepicker);if(inst.trigger){inst.trigger.remove();}showOn=this._get(inst,"showOn");if(showOn==="focus"||showOn==="both"){// pop-up date picker when in the marked field
	input.on("focus",this._showDatepicker);}if(showOn==="button"||showOn==="both"){// pop-up date picker when button clicked
	buttonText=this._get(inst,"buttonText");buttonImage=this._get(inst,"buttonImage");if(this._get(inst,"buttonImageOnly")){inst.trigger=$("<img>").addClass(this._triggerClass).attr({src:buttonImage,alt:buttonText,title:buttonText});}else {inst.trigger=$("<button type='button'>").addClass(this._triggerClass);if(buttonImage){inst.trigger.html($("<img>").attr({src:buttonImage,alt:buttonText,title:buttonText}));}else {inst.trigger.text(buttonText);}}input[isRTL?"before":"after"](inst.trigger);inst.trigger.on("click",function(){if($.datepicker._datepickerShowing&&$.datepicker._lastInput===input[0]){$.datepicker._hideDatepicker();}else if($.datepicker._datepickerShowing&&$.datepicker._lastInput!==input[0]){$.datepicker._hideDatepicker();$.datepicker._showDatepicker(input[0]);}else {$.datepicker._showDatepicker(input[0]);}return false;});}},/* Apply the maximum length for the date format. */_autoSize:function(inst){if(this._get(inst,"autoSize")&&!inst.inline){var findMax,max,maxI,i,date=new Date(2009,12-1,20),// Ensure double digits
	dateFormat=this._get(inst,"dateFormat");if(dateFormat.match(/[DM]/)){findMax=function(names){max=0;maxI=0;for(i=0;i<names.length;i++){if(names[i].length>max){max=names[i].length;maxI=i;}}return maxI;};date.setMonth(findMax(this._get(inst,dateFormat.match(/MM/)?"monthNames":"monthNamesShort")));date.setDate(findMax(this._get(inst,dateFormat.match(/DD/)?"dayNames":"dayNamesShort"))+20-date.getDay());}inst.input.attr("size",this._formatDate(inst,date).length);}},/* Attach an inline date picker to a div. */_inlineDatepicker:function(target,inst){var divSpan=$(target);if(divSpan.hasClass(this.markerClassName)){return;}divSpan.addClass(this.markerClassName).append(inst.dpDiv);$.data(target,"datepicker",inst);this._setDate(inst,this._getDefaultDate(inst),true);this._updateDatepicker(inst);this._updateAlternate(inst);//If disabled option is true, disable the datepicker before showing it (see ticket #5665)
	if(inst.settings.disabled){this._disableDatepicker(target);}// Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
	// https://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
	inst.dpDiv.css("display","block");},/* Pop-up the date picker in a "dialog" box.
			 * @param  input element - ignored
			 * @param  date	string or Date - the initial date to display
			 * @param  onSelect  function - the function to call when a date is selected
			 * @param  settings  object - update the dialog date picker instance's settings (anonymous object)
			 * @param  pos int[2] - coordinates for the dialog's position within the screen or
			 *					event - with x/y coordinates or
			 *					leave empty for default (screen centre)
			 * @return the manager object
			 */_dialogDatepicker:function(input,date,onSelect,settings,pos){var id,browserWidth,browserHeight,scrollX,scrollY,inst=this._dialogInst;// internal instance
	if(!inst){this.uuid+=1;id="dp"+this.uuid;this._dialogInput=$("<input type='text' id='"+id+"' style='position: absolute; top: -100px; width: 0px;'/>");this._dialogInput.on("keydown",this._doKeyDown);$("body").append(this._dialogInput);inst=this._dialogInst=this._newInst(this._dialogInput,false);inst.settings={};$.data(this._dialogInput[0],"datepicker",inst);}datepicker_extendRemove(inst.settings,settings||{});date=date&&date.constructor===Date?this._formatDate(inst,date):date;this._dialogInput.val(date);this._pos=pos?pos.length?pos:[pos.pageX,pos.pageY]:null;if(!this._pos){browserWidth=document.documentElement.clientWidth;browserHeight=document.documentElement.clientHeight;scrollX=document.documentElement.scrollLeft||document.body.scrollLeft;scrollY=document.documentElement.scrollTop||document.body.scrollTop;this._pos=// should use actual width/height below
	[browserWidth/2-100+scrollX,browserHeight/2-150+scrollY];}// Move input on screen for focus, but hidden behind dialog
	this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px");inst.settings.onSelect=onSelect;this._inDialog=true;this.dpDiv.addClass(this._dialogClass);this._showDatepicker(this._dialogInput[0]);if($.blockUI){$.blockUI(this.dpDiv);}$.data(this._dialogInput[0],"datepicker",inst);return this;},/* Detach a datepicker from its control.
			 * @param  target	element - the target input field or division or span
			 */_destroyDatepicker:function(target){var nodeName,$target=$(target),inst=$.data(target,"datepicker");if(!$target.hasClass(this.markerClassName)){return;}nodeName=target.nodeName.toLowerCase();$.removeData(target,"datepicker");if(nodeName==="input"){inst.append.remove();inst.trigger.remove();$target.removeClass(this.markerClassName).off("focus",this._showDatepicker).off("keydown",this._doKeyDown).off("keypress",this._doKeyPress).off("keyup",this._doKeyUp);}else if(nodeName==="div"||nodeName==="span"){$target.removeClass(this.markerClassName).empty();}$.datepicker._hideDatepicker();if(datepicker_instActive===inst){datepicker_instActive=null;this._curInst=null;}},/* Enable the date picker to a jQuery selection.
			 * @param  target	element - the target input field or division or span
			 */_enableDatepicker:function(target){var nodeName,inline,$target=$(target),inst=$.data(target,"datepicker");if(!$target.hasClass(this.markerClassName)){return;}nodeName=target.nodeName.toLowerCase();if(nodeName==="input"){target.disabled=false;inst.trigger.filter("button").each(function(){this.disabled=false;}).end().filter("img").css({opacity:"1.0",cursor:""});}else if(nodeName==="div"||nodeName==="span"){inline=$target.children("."+this._inlineClass);inline.children().removeClass("ui-state-disabled");inline.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",false);}this._disabledInputs=$.map(this._disabledInputs,// Delete entry
	function(value){return value===target?null:value;});},/* Disable the date picker to a jQuery selection.
			 * @param  target	element - the target input field or division or span
			 */_disableDatepicker:function(target){var nodeName,inline,$target=$(target),inst=$.data(target,"datepicker");if(!$target.hasClass(this.markerClassName)){return;}nodeName=target.nodeName.toLowerCase();if(nodeName==="input"){target.disabled=true;inst.trigger.filter("button").each(function(){this.disabled=true;}).end().filter("img").css({opacity:"0.5",cursor:"default"});}else if(nodeName==="div"||nodeName==="span"){inline=$target.children("."+this._inlineClass);inline.children().addClass("ui-state-disabled");inline.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",true);}this._disabledInputs=$.map(this._disabledInputs,// Delete entry
	function(value){return value===target?null:value;});this._disabledInputs[this._disabledInputs.length]=target;},/* Is the first field in a jQuery collection disabled as a datepicker?
			 * @param  target	element - the target input field or division or span
			 * @return boolean - true if disabled, false if enabled
			 */_isDisabledDatepicker:function(target){if(!target){return false;}for(var i=0;i<this._disabledInputs.length;i++){if(this._disabledInputs[i]===target){return true;}}return false;},/* Retrieve the instance data for the target control.
			 * @param  target  element - the target input field or division or span
			 * @return  object - the associated instance data
			 * @throws  error if a jQuery problem getting data
			 */_getInst:function(target){try{return $.data(target,"datepicker");}catch(_err){throw "Missing instance data for this datepicker";}},/* Update or retrieve the settings for a date picker attached to an input field or division.
			 * @param  target  element - the target input field or division or span
			 * @param  name	object - the new settings to update or
			 *				string - the name of the setting to change or retrieve,
			 *				when retrieving also "all" for all instance settings or
			 *				"defaults" for all global defaults
			 * @param  value   any - the new value for the setting
			 *				(omit if above is an object or to retrieve a value)
			 */_optionDatepicker:function(target,name,value){var settings,date,minDate,maxDate,inst=this._getInst(target);if(arguments.length===2&&typeof name==="string"){return name==="defaults"?$.extend({},$.datepicker._defaults):inst?name==="all"?$.extend({},inst.settings):this._get(inst,name):null;}settings=name||{};if(typeof name==="string"){settings={};settings[name]=value;}if(inst){if(this._curInst===inst){this._hideDatepicker();}date=this._getDateDatepicker(target,true);minDate=this._getMinMaxDate(inst,"min");maxDate=this._getMinMaxDate(inst,"max");datepicker_extendRemove(inst.settings,settings);// reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
	if(minDate!==null&&settings.dateFormat!==undefined&&settings.minDate===undefined){inst.settings.minDate=this._formatDate(inst,minDate);}if(maxDate!==null&&settings.dateFormat!==undefined&&settings.maxDate===undefined){inst.settings.maxDate=this._formatDate(inst,maxDate);}if("disabled"in settings){if(settings.disabled){this._disableDatepicker(target);}else {this._enableDatepicker(target);}}this._attachments($(target),inst);this._autoSize(inst);this._setDate(inst,date);this._updateAlternate(inst);this._updateDatepicker(inst);}},// Change method deprecated
	_changeDatepicker:function(target,name,value){this._optionDatepicker(target,name,value);},/* Redraw the date picker attached to an input field or division.
			 * @param  target  element - the target input field or division or span
			 */_refreshDatepicker:function(target){var inst=this._getInst(target);if(inst){this._updateDatepicker(inst);}},/* Set the dates for a jQuery selection.
			 * @param  target element - the target input field or division or span
			 * @param  date	Date - the new date
			 */_setDateDatepicker:function(target,date){var inst=this._getInst(target);if(inst){this._setDate(inst,date);this._updateDatepicker(inst);this._updateAlternate(inst);}},/* Get the date(s) for the first entry in a jQuery selection.
			 * @param  target element - the target input field or division or span
			 * @param  noDefault boolean - true if no default date is to be used
			 * @return Date - the current date
			 */_getDateDatepicker:function(target,noDefault){var inst=this._getInst(target);if(inst&&!inst.inline){this._setDateFromField(inst,noDefault);}return inst?this._getDate(inst):null;},/* Handle keystrokes. */_doKeyDown:function(event){var onSelect,dateStr,sel,inst=$.datepicker._getInst(event.target),handled=true,isRTL=inst.dpDiv.is(".ui-datepicker-rtl");inst._keyEvent=true;if($.datepicker._datepickerShowing){switch(event.keyCode){case 9:$.datepicker._hideDatepicker();handled=false;break;// hide on tab out
	case 13:sel=$("td."+$.datepicker._dayOverClass+":not(."+$.datepicker._currentClass+")",inst.dpDiv);if(sel[0]){$.datepicker._selectDay(event.target,inst.selectedMonth,inst.selectedYear,sel[0]);}onSelect=$.datepicker._get(inst,"onSelect");if(onSelect){dateStr=$.datepicker._formatDate(inst);// Trigger custom callback
	onSelect.apply(inst.input?inst.input[0]:null,[dateStr,inst]);}else {$.datepicker._hideDatepicker();}return false;// don't submit the form
	case 27:$.datepicker._hideDatepicker();break;// hide on escape
	case 33:$.datepicker._adjustDate(event.target,event.ctrlKey?-$.datepicker._get(inst,"stepBigMonths"):-$.datepicker._get(inst,"stepMonths"),"M");break;// previous month/year on page up/+ ctrl
	case 34:$.datepicker._adjustDate(event.target,event.ctrlKey?+$.datepicker._get(inst,"stepBigMonths"):+$.datepicker._get(inst,"stepMonths"),"M");break;// next month/year on page down/+ ctrl
	case 35:if(event.ctrlKey||event.metaKey){$.datepicker._clearDate(event.target);}handled=event.ctrlKey||event.metaKey;break;// clear on ctrl or command +end
	case 36:if(event.ctrlKey||event.metaKey){$.datepicker._gotoToday(event.target);}handled=event.ctrlKey||event.metaKey;break;// current on ctrl or command +home
	case 37:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,isRTL?1:-1,"D");}handled=event.ctrlKey||event.metaKey;// -1 day on ctrl or command +left
	if(event.originalEvent.altKey){$.datepicker._adjustDate(event.target,event.ctrlKey?-$.datepicker._get(inst,"stepBigMonths"):-$.datepicker._get(inst,"stepMonths"),"M");}// next month/year on alt +left on Mac
	break;case 38:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,-7,"D");}handled=event.ctrlKey||event.metaKey;break;// -1 week on ctrl or command +up
	case 39:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,isRTL?-1:1,"D");}handled=event.ctrlKey||event.metaKey;// +1 day on ctrl or command +right
	if(event.originalEvent.altKey){$.datepicker._adjustDate(event.target,event.ctrlKey?+$.datepicker._get(inst,"stepBigMonths"):+$.datepicker._get(inst,"stepMonths"),"M");}// next month/year on alt +right
	break;case 40:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,7,"D");}handled=event.ctrlKey||event.metaKey;break;// +1 week on ctrl or command +down
	default:handled=false;}}else if(event.keyCode===36&&event.ctrlKey){// display the date picker on ctrl+home
	$.datepicker._showDatepicker(this);}else {handled=false;}if(handled){event.preventDefault();event.stopPropagation();}},/* Filter entered characters - based on date format. */_doKeyPress:function(event){var chars,chr,inst=$.datepicker._getInst(event.target);if($.datepicker._get(inst,"constrainInput")){chars=$.datepicker._possibleChars($.datepicker._get(inst,"dateFormat"));chr=String.fromCharCode(event.charCode==null?event.keyCode:event.charCode);return event.ctrlKey||event.metaKey||chr<" "||!chars||chars.indexOf(chr)>-1;}},/* Synchronise manual entry and field/alternate field. */_doKeyUp:function(event){var date,inst=$.datepicker._getInst(event.target);if(inst.input.val()!==inst.lastVal){try{date=$.datepicker.parseDate($.datepicker._get(inst,"dateFormat"),inst.input?inst.input.val():null,$.datepicker._getFormatConfig(inst));if(date){// only if valid
	$.datepicker._setDateFromField(inst);$.datepicker._updateAlternate(inst);$.datepicker._updateDatepicker(inst);}}catch(_err){}}return true;},/* Pop-up the date picker for a given input field.
			 * If false returned from beforeShow event handler do not show.
			 * @param  input  element - the input field attached to the date picker or
			 *					event - if triggered by focus
			 */_showDatepicker:function(input){input=input.target||input;if(input.nodeName.toLowerCase()!=="input"){// find from button/image trigger
	input=$("input",input.parentNode)[0];}if($.datepicker._isDisabledDatepicker(input)||$.datepicker._lastInput===input){// already here
	return;}var inst,beforeShow,beforeShowSettings,isFixed,offset,showAnim,duration;inst=$.datepicker._getInst(input);if($.datepicker._curInst&&$.datepicker._curInst!==inst){$.datepicker._curInst.dpDiv.stop(true,true);if(inst&&$.datepicker._datepickerShowing){$.datepicker._hideDatepicker($.datepicker._curInst.input[0]);}}beforeShow=$.datepicker._get(inst,"beforeShow");beforeShowSettings=beforeShow?beforeShow.apply(input,[input,inst]):{};if(beforeShowSettings===false){return;}datepicker_extendRemove(inst.settings,beforeShowSettings);inst.lastVal=null;$.datepicker._lastInput=input;$.datepicker._setDateFromField(inst);if($.datepicker._inDialog){// hide cursor
	input.value="";}if(!$.datepicker._pos){// position below input
	$.datepicker._pos=$.datepicker._findPos(input);$.datepicker._pos[1]+=input.offsetHeight;// add the height
	}isFixed=false;$(input).parents().each(function(){isFixed|=$(this).css("position")==="fixed";return !isFixed;});offset={left:$.datepicker._pos[0],top:$.datepicker._pos[1]};$.datepicker._pos=null;//to avoid flashes on Firefox
	inst.dpDiv.empty();// determine sizing offscreen
	inst.dpDiv.css({position:"absolute",display:"block",top:"-1000px"});$.datepicker._updateDatepicker(inst);// fix width for dynamic number of date pickers
	// and adjust position before showing
	offset=$.datepicker._checkOffset(inst,offset,isFixed);inst.dpDiv.css({position:$.datepicker._inDialog&&$.blockUI?"static":isFixed?"fixed":"absolute",display:"none",left:offset.left+"px",top:offset.top+"px"});if(!inst.inline){showAnim=$.datepicker._get(inst,"showAnim");duration=$.datepicker._get(inst,"duration");inst.dpDiv.css("z-index",datepicker_getZindex($(input))+1);$.datepicker._datepickerShowing=true;if($.effects&&$.effects.effect[showAnim]){inst.dpDiv.show(showAnim,$.datepicker._get(inst,"showOptions"),duration);}else {inst.dpDiv[showAnim||"show"](showAnim?duration:null);}if($.datepicker._shouldFocusInput(inst)){inst.input.trigger("focus");}$.datepicker._curInst=inst;}},/* Generate the date picker content. */_updateDatepicker:function(inst){this.maxRows=4;//Reset the max number of rows being displayed (see #7043)
	datepicker_instActive=inst;// for delegate hover events
	inst.dpDiv.empty().append(this._generateHTML(inst));this._attachHandlers(inst);var origyearshtml,numMonths=this._getNumberOfMonths(inst),cols=numMonths[1],width=17,activeCell=inst.dpDiv.find("."+this._dayOverClass+" a"),onUpdateDatepicker=$.datepicker._get(inst,"onUpdateDatepicker");if(activeCell.length>0){datepicker_handleMouseover.apply(activeCell.get(0));}inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");if(cols>1){inst.dpDiv.addClass("ui-datepicker-multi-"+cols).css("width",width*cols+"em");}inst.dpDiv[(numMonths[0]!==1||numMonths[1]!==1?"add":"remove")+"Class"]("ui-datepicker-multi");inst.dpDiv[(this._get(inst,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl");if(inst===$.datepicker._curInst&&$.datepicker._datepickerShowing&&$.datepicker._shouldFocusInput(inst)){inst.input.trigger("focus");}// Deffered render of the years select (to avoid flashes on Firefox)
	if(inst.yearshtml){origyearshtml=inst.yearshtml;setTimeout(function(){//assure that inst.yearshtml didn't change.
	if(origyearshtml===inst.yearshtml&&inst.yearshtml){inst.dpDiv.find("select.ui-datepicker-year").first().replaceWith(inst.yearshtml);}origyearshtml=inst.yearshtml=null;},0);}if(onUpdateDatepicker){onUpdateDatepicker.apply(inst.input?inst.input[0]:null,[inst]);}},_shouldFocusInput:function(inst){return inst.input&&inst.input.is(":visible")&&!inst.input.is(":disabled");},/* Check positioning to remain on screen. */_checkOffset:function(inst,offset,isFixed){var dpWidth=inst.dpDiv.outerWidth(),dpHeight=inst.dpDiv.outerHeight(),inputWidth=inst.input?inst.input.outerWidth():0,inputHeight=inst.input?inst.input.outerHeight():0,viewWidth=document.documentElement.clientWidth+(isFixed?0:$(document).scrollLeft()),viewHeight=document.documentElement.clientHeight+(isFixed?0:$(document).scrollTop());offset.left-=this._get(inst,"isRTL")?dpWidth-inputWidth:0;offset.left-=isFixed&&offset.left===inst.input.offset().left?$(document).scrollLeft():0;offset.top-=isFixed&&offset.top===inst.input.offset().top+inputHeight?$(document).scrollTop():0;// Now check if datepicker is showing outside window viewport - move to a better place if so.
	offset.left-=Math.min(offset.left,offset.left+dpWidth>viewWidth&&viewWidth>dpWidth?Math.abs(offset.left+dpWidth-viewWidth):0);offset.top-=Math.min(offset.top,offset.top+dpHeight>viewHeight&&viewHeight>dpHeight?Math.abs(dpHeight+inputHeight):0);return offset;},/* Find an object's position on the screen. */_findPos:function(obj){var position,inst=this._getInst(obj),isRTL=this._get(inst,"isRTL");while(obj&&(obj.type==="hidden"||obj.nodeType!==1||$.expr.pseudos.hidden(obj))){obj=obj[isRTL?"previousSibling":"nextSibling"];}position=$(obj).offset();return [position.left,position.top];},/* Hide the date picker from view.
			 * @param  input  element - the input field attached to the date picker
			 */_hideDatepicker:function(input){var showAnim,duration,postProcess,onClose,inst=this._curInst;if(!inst||input&&inst!==$.data(input,"datepicker")){return;}if(this._datepickerShowing){showAnim=this._get(inst,"showAnim");duration=this._get(inst,"duration");postProcess=function(){$.datepicker._tidyDialog(inst);};if($.effects&&$.effects.effect[showAnim]){inst.dpDiv.hide(showAnim,$.datepicker._get(inst,"showOptions"),duration,postProcess);}else {inst.dpDiv[showAnim==="slideDown"?"slideUp":showAnim==="fadeIn"?"fadeOut":"hide"](showAnim?duration:null,postProcess);}if(!showAnim){postProcess();}this._datepickerShowing=false;onClose=this._get(inst,"onClose");if(onClose){onClose.apply(inst.input?inst.input[0]:null,[inst.input?inst.input.val():"",inst]);}this._lastInput=null;if(this._inDialog){this._dialogInput.css({position:"absolute",left:"0",top:"-100px"});if($.blockUI){$.unblockUI();$("body").append(this.dpDiv);}}this._inDialog=false;}},/* Tidy up after a dialog display. */_tidyDialog:function(inst){inst.dpDiv.removeClass(this._dialogClass).off(".ui-datepicker-calendar");},/* Close date picker if clicked elsewhere. */_checkExternalClick:function(event){if(!$.datepicker._curInst){return;}var $target=$(event.target),inst=$.datepicker._getInst($target[0]);if($target[0].id!==$.datepicker._mainDivId&&$target.parents("#"+$.datepicker._mainDivId).length===0&&!$target.hasClass($.datepicker.markerClassName)&&!$target.closest("."+$.datepicker._triggerClass).length&&$.datepicker._datepickerShowing&&!($.datepicker._inDialog&&$.blockUI)||$target.hasClass($.datepicker.markerClassName)&&$.datepicker._curInst!==inst){$.datepicker._hideDatepicker();}},/* Adjust one of the date sub-fields. */_adjustDate:function(id,offset,period){var target=$(id),inst=this._getInst(target[0]);if(this._isDisabledDatepicker(target[0])){return;}this._adjustInstDate(inst,offset,period);this._updateDatepicker(inst);},/* Action for current link. */_gotoToday:function(id){var date,target=$(id),inst=this._getInst(target[0]);if(this._get(inst,"gotoCurrent")&&inst.currentDay){inst.selectedDay=inst.currentDay;inst.drawMonth=inst.selectedMonth=inst.currentMonth;inst.drawYear=inst.selectedYear=inst.currentYear;}else {date=new Date();inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear();}this._notifyChange(inst);this._adjustDate(target);},/* Action for selecting a new month/year. */_selectMonthYear:function(id,select,period){var target=$(id),inst=this._getInst(target[0]);inst["selected"+(period==="M"?"Month":"Year")]=inst["draw"+(period==="M"?"Month":"Year")]=parseInt(select.options[select.selectedIndex].value,10);this._notifyChange(inst);this._adjustDate(target);},/* Action for selecting a day. */_selectDay:function(id,month,year,td){var inst,target=$(id);if($(td).hasClass(this._unselectableClass)||this._isDisabledDatepicker(target[0])){return;}inst=this._getInst(target[0]);inst.selectedDay=inst.currentDay=parseInt($("a",td).attr("data-date"));inst.selectedMonth=inst.currentMonth=month;inst.selectedYear=inst.currentYear=year;this._selectDate(id,this._formatDate(inst,inst.currentDay,inst.currentMonth,inst.currentYear));},/* Erase the input field and hide the date picker. */_clearDate:function(id){var target=$(id);this._selectDate(target,"");},/* Update the input field with the selected date. */_selectDate:function(id,dateStr){var onSelect,target=$(id),inst=this._getInst(target[0]);dateStr=dateStr!=null?dateStr:this._formatDate(inst);if(inst.input){inst.input.val(dateStr);}this._updateAlternate(inst);onSelect=this._get(inst,"onSelect");if(onSelect){onSelect.apply(inst.input?inst.input[0]:null,[dateStr,inst]);// trigger custom callback
	}else if(inst.input){inst.input.trigger("change");// fire the change event
	}if(inst.inline){this._updateDatepicker(inst);}else {this._hideDatepicker();this._lastInput=inst.input[0];if(typeof inst.input[0]!=="object"){inst.input.trigger("focus");// restore focus
	}this._lastInput=null;}},/* Update any alternate field to synchronise with the main field. */_updateAlternate:function(inst){var altFormat,date,dateStr,altField=this._get(inst,"altField");if(altField){// update alternate field too
	altFormat=this._get(inst,"altFormat")||this._get(inst,"dateFormat");date=this._getDate(inst);dateStr=this.formatDate(altFormat,date,this._getFormatConfig(inst));$(document).find(altField).val(dateStr);}},/* Set as beforeShowDay function to prevent selection of weekends.
			 * @param  date  Date - the date to customise
			 * @return [boolean, string] - is this date selectable?, what is its CSS class?
			 */noWeekends:function(date){var day=date.getDay();return [day>0&&day<6,""];},/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
			 * @param  date  Date - the date to get the week for
			 * @return  number - the number of the week within the year that contains this date
			 */iso8601Week:function(date){var time,checkDate=new Date(date.getTime());// Find Thursday of this week starting on Monday
	checkDate.setDate(checkDate.getDate()+4-(checkDate.getDay()||7));time=checkDate.getTime();checkDate.setMonth(0);// Compare with Jan 1
	checkDate.setDate(1);return Math.floor(Math.round((time-checkDate)/86400000)/7)+1;},/* Parse a string value into a date object.
			 * See formatDate below for the possible formats.
			 *
			 * @param  format string - the expected format of the date
			 * @param  value string - the date in the above format
			 * @param  settings Object - attributes include:
			 *					shortYearCutoff  number - the cutoff year for determining the century (optional)
			 *					dayNamesShort	string[7] - abbreviated names of the days from Sunday (optional)
			 *					dayNames		string[7] - names of the days from Sunday (optional)
			 *					monthNamesShort string[12] - abbreviated names of the months (optional)
			 *					monthNames		string[12] - names of the months (optional)
			 * @return  Date - the extracted date value or null if value is blank
			 */parseDate:function(format,value,settings){if(format==null||value==null){throw "Invalid arguments";}value=typeof value==="object"?value.toString():value+"";if(value===""){return null;}var iFormat,dim,extra,iValue=0,shortYearCutoffTemp=(settings?settings.shortYearCutoff:null)||this._defaults.shortYearCutoff,shortYearCutoff=typeof shortYearCutoffTemp!=="string"?shortYearCutoffTemp:new Date().getFullYear()%100+parseInt(shortYearCutoffTemp,10),dayNamesShort=(settings?settings.dayNamesShort:null)||this._defaults.dayNamesShort,dayNames=(settings?settings.dayNames:null)||this._defaults.dayNames,monthNamesShort=(settings?settings.monthNamesShort:null)||this._defaults.monthNamesShort,monthNames=(settings?settings.monthNames:null)||this._defaults.monthNames,year=-1,month=-1,day=-1,doy=-1,literal=false,date,// Check whether a format character is doubled
	lookAhead=function(match){var matches=iFormat+1<format.length&&format.charAt(iFormat+1)===match;if(matches){iFormat++;}return matches;},// Extract a number from the string value
	getNumber=function(match){var isDoubled=lookAhead(match),size=match==="@"?14:match==="!"?20:match==="y"&&isDoubled?4:match==="o"?3:2,minSize=match==="y"?size:1,digits=new RegExp("^\\d{"+minSize+","+size+"}"),num=value.substring(iValue).match(digits);if(!num){throw "Missing number at position "+iValue;}iValue+=num[0].length;return parseInt(num[0],10);},// Extract a name from the string value and convert to an index
	getName=function(match,shortNames,longNames){var index=-1,names=$.map(lookAhead(match)?longNames:shortNames,function(v,k){return [[k,v]];}).sort(function(a,b){return -(a[1].length-b[1].length);});$.each(names,function(i,pair){var name=pair[1];if(value.substr(iValue,name.length).toLowerCase()===name.toLowerCase()){index=pair[0];iValue+=name.length;return false;}});if(index!==-1){return index+1;}else {throw "Unknown name at position "+iValue;}},// Confirm that a literal character matches the string value
	checkLiteral=function(){if(value.charAt(iValue)!==format.charAt(iFormat)){throw "Unexpected literal at position "+iValue;}iValue++;};for(iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)==="'"&&!lookAhead("'")){literal=false;}else {checkLiteral();}}else {switch(format.charAt(iFormat)){case "d":day=getNumber("d");break;case "D":getName("D",dayNamesShort,dayNames);break;case "o":doy=getNumber("o");break;case "m":month=getNumber("m");break;case "M":month=getName("M",monthNamesShort,monthNames);break;case "y":year=getNumber("y");break;case "@":date=new Date(getNumber("@"));year=date.getFullYear();month=date.getMonth()+1;day=date.getDate();break;case "!":date=new Date((getNumber("!")-this._ticksTo1970)/10000);year=date.getFullYear();month=date.getMonth()+1;day=date.getDate();break;case "'":if(lookAhead("'")){checkLiteral();}else {literal=true;}break;default:checkLiteral();}}}if(iValue<value.length){extra=value.substr(iValue);if(!/^\s+/.test(extra)){throw "Extra/unparsed characters found in date: "+extra;}}if(year===-1){year=new Date().getFullYear();}else if(year<100){year+=new Date().getFullYear()-new Date().getFullYear()%100+(year<=shortYearCutoff?0:-100);}if(doy>-1){month=1;day=doy;do{dim=this._getDaysInMonth(year,month-1);if(day<=dim){break;}month++;day-=dim;}while(true);}date=this._daylightSavingAdjust(new Date(year,month-1,day));if(date.getFullYear()!==year||date.getMonth()+1!==month||date.getDate()!==day){throw "Invalid date";// E.g. 31/02/00
	}return date;},/* Standard date formats. */ATOM:"yy-mm-dd",// RFC 3339 (ISO 8601)
	COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",// RFC 822
	TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",// ISO 8601
	_ticksTo1970:((1970-1)*365+Math.floor(1970/4)-Math.floor(1970/100)+Math.floor(1970/400))*24*60*60*10000000,/* Format a date object into a string value.
			 * The format can be combinations of the following:
			 * d  - day of month (no leading zero)
			 * dd - day of month (two digit)
			 * o  - day of year (no leading zeros)
			 * oo - day of year (three digit)
			 * D  - day name short
			 * DD - day name long
			 * m  - month of year (no leading zero)
			 * mm - month of year (two digit)
			 * M  - month name short
			 * MM - month name long
			 * y  - year (two digit)
			 * yy - year (four digit)
			 * @ - Unix timestamp (ms since 01/01/1970)
			 * ! - Windows ticks (100ns since 01/01/0001)
			 * "..." - literal text
			 * '' - single quote
			 *
			 * @param  format string - the desired format of the date
			 * @param  date Date - the date value to format
			 * @param  settings Object - attributes include:
			 *					dayNamesShort	string[7] - abbreviated names of the days from Sunday (optional)
			 *					dayNames		string[7] - names of the days from Sunday (optional)
			 *					monthNamesShort string[12] - abbreviated names of the months (optional)
			 *					monthNames		string[12] - names of the months (optional)
			 * @return  string - the date in the above format
			 */formatDate:function(format,date,settings){if(!date){return "";}var iFormat,dayNamesShort=(settings?settings.dayNamesShort:null)||this._defaults.dayNamesShort,dayNames=(settings?settings.dayNames:null)||this._defaults.dayNames,monthNamesShort=(settings?settings.monthNamesShort:null)||this._defaults.monthNamesShort,monthNames=(settings?settings.monthNames:null)||this._defaults.monthNames,// Check whether a format character is doubled
	lookAhead=function(match){var matches=iFormat+1<format.length&&format.charAt(iFormat+1)===match;if(matches){iFormat++;}return matches;},// Format a number, with leading zero if necessary
	formatNumber=function(match,value,len){var num=""+value;if(lookAhead(match)){while(num.length<len){num="0"+num;}}return num;},// Format a name, short or long as requested
	formatName=function(match,value,shortNames,longNames){return lookAhead(match)?longNames[value]:shortNames[value];},output="",literal=false;if(date){for(iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)==="'"&&!lookAhead("'")){literal=false;}else {output+=format.charAt(iFormat);}}else {switch(format.charAt(iFormat)){case "d":output+=formatNumber("d",date.getDate(),2);break;case "D":output+=formatName("D",date.getDay(),dayNamesShort,dayNames);break;case "o":output+=formatNumber("o",Math.round((new Date(date.getFullYear(),date.getMonth(),date.getDate()).getTime()-new Date(date.getFullYear(),0,0).getTime())/86400000),3);break;case "m":output+=formatNumber("m",date.getMonth()+1,2);break;case "M":output+=formatName("M",date.getMonth(),monthNamesShort,monthNames);break;case "y":output+=lookAhead("y")?date.getFullYear():(date.getFullYear()%100<10?"0":"")+date.getFullYear()%100;break;case "@":output+=date.getTime();break;case "!":output+=date.getTime()*10000+this._ticksTo1970;break;case "'":if(lookAhead("'")){output+="'";}else {literal=true;}break;default:output+=format.charAt(iFormat);}}}}return output;},/* Extract all possible characters from the date format. */_possibleChars:function(format){var iFormat,chars="",literal=false,// Check whether a format character is doubled
	lookAhead=function(match){var matches=iFormat+1<format.length&&format.charAt(iFormat+1)===match;if(matches){iFormat++;}return matches;};for(iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)==="'"&&!lookAhead("'")){literal=false;}else {chars+=format.charAt(iFormat);}}else {switch(format.charAt(iFormat)){case "d":case "m":case "y":case "@":chars+="0123456789";break;case "D":case "M":return null;// Accept anything
	case "'":if(lookAhead("'")){chars+="'";}else {literal=true;}break;default:chars+=format.charAt(iFormat);}}}return chars;},/* Get a setting value, defaulting if necessary. */_get:function(inst,name){return inst.settings[name]!==undefined?inst.settings[name]:this._defaults[name];},/* Parse existing date and initialise date picker. */_setDateFromField:function(inst,noDefault){if(inst.input.val()===inst.lastVal){return;}var dateFormat=this._get(inst,"dateFormat"),dates=inst.lastVal=inst.input?inst.input.val():null,defaultDate=this._getDefaultDate(inst),date=defaultDate,settings=this._getFormatConfig(inst);try{date=this.parseDate(dateFormat,dates,settings)||defaultDate;}catch(_err){dates=noDefault?"":dates;}inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear();inst.currentDay=dates?date.getDate():0;inst.currentMonth=dates?date.getMonth():0;inst.currentYear=dates?date.getFullYear():0;this._adjustInstDate(inst);},/* Retrieve the default date shown on opening. */_getDefaultDate:function(inst){return this._restrictMinMax(inst,this._determineDate(inst,this._get(inst,"defaultDate"),new Date()));},/* A date may be specified as an exact value or a relative one. */_determineDate:function(inst,date,defaultDate){var offsetNumeric=function(offset){var date=new Date();date.setDate(date.getDate()+offset);return date;},offsetString=function(offset){try{return $.datepicker.parseDate($.datepicker._get(inst,"dateFormat"),offset,$.datepicker._getFormatConfig(inst));}catch(_e){// Ignore
	}var date=(offset.toLowerCase().match(/^c/)?$.datepicker._getDate(inst):null)||new Date(),year=date.getFullYear(),month=date.getMonth(),day=date.getDate(),pattern=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,matches=pattern.exec(offset);while(matches){switch(matches[2]||"d"){case "d":case "D":day+=parseInt(matches[1],10);break;case "w":case "W":day+=parseInt(matches[1],10)*7;break;case "m":case "M":month+=parseInt(matches[1],10);day=Math.min(day,$.datepicker._getDaysInMonth(year,month));break;case "y":case "Y":year+=parseInt(matches[1],10);day=Math.min(day,$.datepicker._getDaysInMonth(year,month));break;}matches=pattern.exec(offset);}return new Date(year,month,day);},newDate=date==null||date===""?defaultDate:typeof date==="string"?offsetString(date):typeof date==="number"?isNaN(date)?defaultDate:offsetNumeric(date):new Date(date.getTime());newDate=newDate&&newDate.toString()==="Invalid Date"?defaultDate:newDate;if(newDate){newDate.setHours(0);newDate.setMinutes(0);newDate.setSeconds(0);newDate.setMilliseconds(0);}return this._daylightSavingAdjust(newDate);},/* Handle switch to/from daylight saving.
			 * Hours may be non-zero on daylight saving cut-over:
			 * > 12 when midnight changeover, but then cannot generate
			 * midnight datetime, so jump to 1AM, otherwise reset.
			 * @param  date  (Date) the date to check
			 * @return  (Date) the corrected date
			 */_daylightSavingAdjust:function(date){if(!date){return null;}date.setHours(date.getHours()>12?date.getHours()+2:0);return date;},/* Set the date(s) directly. */_setDate:function(inst,date,noChange){var clear=!date,origMonth=inst.selectedMonth,origYear=inst.selectedYear,newDate=this._restrictMinMax(inst,this._determineDate(inst,date,new Date()));inst.selectedDay=inst.currentDay=newDate.getDate();inst.drawMonth=inst.selectedMonth=inst.currentMonth=newDate.getMonth();inst.drawYear=inst.selectedYear=inst.currentYear=newDate.getFullYear();if((origMonth!==inst.selectedMonth||origYear!==inst.selectedYear)&&!noChange){this._notifyChange(inst);}this._adjustInstDate(inst);if(inst.input){inst.input.val(clear?"":this._formatDate(inst));}},/* Retrieve the date(s) directly. */_getDate:function(inst){var startDate=!inst.currentYear||inst.input&&inst.input.val()===""?null:this._daylightSavingAdjust(new Date(inst.currentYear,inst.currentMonth,inst.currentDay));return startDate;},/* Attach the onxxx handlers.  These are declared statically so
			 * they work with static code transformers like Caja.
			 */_attachHandlers:function(inst){var stepMonths=this._get(inst,"stepMonths"),id="#"+inst.id.replace(/\\\\/g,"\\");inst.dpDiv.find("[data-handler]").map(function(){var handler={prev:function(){$.datepicker._adjustDate(id,-stepMonths,"M");},next:function(){$.datepicker._adjustDate(id,+stepMonths,"M");},hide:function(){$.datepicker._hideDatepicker();},today:function(){$.datepicker._gotoToday(id);},selectDay:function(){$.datepicker._selectDay(id,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this);return false;},selectMonth:function(){$.datepicker._selectMonthYear(id,this,"M");return false;},selectYear:function(){$.datepicker._selectMonthYear(id,this,"Y");return false;}};$(this).on(this.getAttribute("data-event"),handler[this.getAttribute("data-handler")]);});},/* Generate the HTML for the current state of the date picker. */_generateHTML:function(inst){var maxDraw,prevText,prev,nextText,next,currentText,gotoDate,controls,buttonPanel,firstDay,showWeek,dayNames,dayNamesMin,monthNames,monthNamesShort,beforeShowDay,showOtherMonths,selectOtherMonths,defaultDate,html,dow,row,group,col,selectedDate,cornerClass,calender,thead,day,daysInMonth,leadDays,curRows,numRows,printDate,dRow,tbody,daySettings,otherMonth,unselectable,tempDate=new Date(),today=this._daylightSavingAdjust(new Date(tempDate.getFullYear(),tempDate.getMonth(),tempDate.getDate())),// clear time
	isRTL=this._get(inst,"isRTL"),showButtonPanel=this._get(inst,"showButtonPanel"),hideIfNoPrevNext=this._get(inst,"hideIfNoPrevNext"),navigationAsDateFormat=this._get(inst,"navigationAsDateFormat"),numMonths=this._getNumberOfMonths(inst),showCurrentAtPos=this._get(inst,"showCurrentAtPos"),stepMonths=this._get(inst,"stepMonths"),isMultiMonth=numMonths[0]!==1||numMonths[1]!==1,currentDate=this._daylightSavingAdjust(!inst.currentDay?new Date(9999,9,9):new Date(inst.currentYear,inst.currentMonth,inst.currentDay)),minDate=this._getMinMaxDate(inst,"min"),maxDate=this._getMinMaxDate(inst,"max"),drawMonth=inst.drawMonth-showCurrentAtPos,drawYear=inst.drawYear;if(drawMonth<0){drawMonth+=12;drawYear--;}if(maxDate){maxDraw=this._daylightSavingAdjust(new Date(maxDate.getFullYear(),maxDate.getMonth()-numMonths[0]*numMonths[1]+1,maxDate.getDate()));maxDraw=minDate&&maxDraw<minDate?minDate:maxDraw;while(this._daylightSavingAdjust(new Date(drawYear,drawMonth,1))>maxDraw){drawMonth--;if(drawMonth<0){drawMonth=11;drawYear--;}}}inst.drawMonth=drawMonth;inst.drawYear=drawYear;prevText=this._get(inst,"prevText");prevText=!navigationAsDateFormat?prevText:this.formatDate(prevText,this._daylightSavingAdjust(new Date(drawYear,drawMonth-stepMonths,1)),this._getFormatConfig(inst));if(this._canAdjustMonth(inst,-1,drawYear,drawMonth)){prev=$("<a>").attr({"class":"ui-datepicker-prev ui-corner-all","data-handler":"prev","data-event":"click",title:prevText}).append($("<span>").addClass("ui-icon ui-icon-circle-triangle-"+(isRTL?"e":"w")).text(prevText))[0].outerHTML;}else if(hideIfNoPrevNext){prev="";}else {prev=$("<a>").attr({"class":"ui-datepicker-prev ui-corner-all ui-state-disabled",title:prevText}).append($("<span>").addClass("ui-icon ui-icon-circle-triangle-"+(isRTL?"e":"w")).text(prevText))[0].outerHTML;}nextText=this._get(inst,"nextText");nextText=!navigationAsDateFormat?nextText:this.formatDate(nextText,this._daylightSavingAdjust(new Date(drawYear,drawMonth+stepMonths,1)),this._getFormatConfig(inst));if(this._canAdjustMonth(inst,1,drawYear,drawMonth)){next=$("<a>").attr({"class":"ui-datepicker-next ui-corner-all","data-handler":"next","data-event":"click",title:nextText}).append($("<span>").addClass("ui-icon ui-icon-circle-triangle-"+(isRTL?"w":"e")).text(nextText))[0].outerHTML;}else if(hideIfNoPrevNext){next="";}else {next=$("<a>").attr({"class":"ui-datepicker-next ui-corner-all ui-state-disabled",title:nextText}).append($("<span>").attr("class","ui-icon ui-icon-circle-triangle-"+(isRTL?"w":"e")).text(nextText))[0].outerHTML;}currentText=this._get(inst,"currentText");gotoDate=this._get(inst,"gotoCurrent")&&inst.currentDay?currentDate:today;currentText=!navigationAsDateFormat?currentText:this.formatDate(currentText,gotoDate,this._getFormatConfig(inst));controls="";if(!inst.inline){controls=$("<button>").attr({type:"button","class":"ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all","data-handler":"hide","data-event":"click"}).text(this._get(inst,"closeText"))[0].outerHTML;}buttonPanel="";if(showButtonPanel){buttonPanel=$("<div class='ui-datepicker-buttonpane ui-widget-content'>").append(isRTL?controls:"").append(this._isInRange(inst,gotoDate)?$("<button>").attr({type:"button","class":"ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all","data-handler":"today","data-event":"click"}).text(currentText):"").append(isRTL?"":controls)[0].outerHTML;}firstDay=parseInt(this._get(inst,"firstDay"),10);firstDay=isNaN(firstDay)?0:firstDay;showWeek=this._get(inst,"showWeek");dayNames=this._get(inst,"dayNames");dayNamesMin=this._get(inst,"dayNamesMin");monthNames=this._get(inst,"monthNames");monthNamesShort=this._get(inst,"monthNamesShort");beforeShowDay=this._get(inst,"beforeShowDay");showOtherMonths=this._get(inst,"showOtherMonths");selectOtherMonths=this._get(inst,"selectOtherMonths");defaultDate=this._getDefaultDate(inst);html="";for(row=0;row<numMonths[0];row++){group="";this.maxRows=4;for(col=0;col<numMonths[1];col++){selectedDate=this._daylightSavingAdjust(new Date(drawYear,drawMonth,inst.selectedDay));cornerClass=" ui-corner-all";calender="";if(isMultiMonth){calender+="<div class='ui-datepicker-group";if(numMonths[1]>1){switch(col){case 0:calender+=" ui-datepicker-group-first";cornerClass=" ui-corner-"+(isRTL?"right":"left");break;case numMonths[1]-1:calender+=" ui-datepicker-group-last";cornerClass=" ui-corner-"+(isRTL?"left":"right");break;default:calender+=" ui-datepicker-group-middle";cornerClass="";break;}}calender+="'>";}calender+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+cornerClass+"'>"+(/all|left/.test(cornerClass)&&row===0?isRTL?next:prev:"")+(/all|right/.test(cornerClass)&&row===0?isRTL?prev:next:"")+this._generateMonthYearHeader(inst,drawMonth,drawYear,minDate,maxDate,row>0||col>0,monthNames,monthNamesShort)+// draw month headers
	"</div><table class='ui-datepicker-calendar'><thead>"+"<tr>";thead=showWeek?"<th class='ui-datepicker-week-col'>"+this._get(inst,"weekHeader")+"</th>":"";for(dow=0;dow<7;dow++){// days of the week
	day=(dow+firstDay)%7;thead+="<th scope='col'"+((dow+firstDay+6)%7>=5?" class='ui-datepicker-week-end'":"")+">"+"<span title='"+dayNames[day]+"'>"+dayNamesMin[day]+"</span></th>";}calender+=thead+"</tr></thead><tbody>";daysInMonth=this._getDaysInMonth(drawYear,drawMonth);if(drawYear===inst.selectedYear&&drawMonth===inst.selectedMonth){inst.selectedDay=Math.min(inst.selectedDay,daysInMonth);}leadDays=(this._getFirstDayOfMonth(drawYear,drawMonth)-firstDay+7)%7;curRows=Math.ceil((leadDays+daysInMonth)/7);// calculate the number of rows to generate
	numRows=isMultiMonth?this.maxRows>curRows?this.maxRows:curRows:curRows;//If multiple months, use the higher number of rows (see #7043)
	this.maxRows=numRows;printDate=this._daylightSavingAdjust(new Date(drawYear,drawMonth,1-leadDays));for(dRow=0;dRow<numRows;dRow++){// create date picker rows
	calender+="<tr>";tbody=!showWeek?"":"<td class='ui-datepicker-week-col'>"+this._get(inst,"calculateWeek")(printDate)+"</td>";for(dow=0;dow<7;dow++){// create date picker days
	daySettings=beforeShowDay?beforeShowDay.apply(inst.input?inst.input[0]:null,[printDate]):[true,""];otherMonth=printDate.getMonth()!==drawMonth;unselectable=otherMonth&&!selectOtherMonths||!daySettings[0]||minDate&&printDate<minDate||maxDate&&printDate>maxDate;tbody+="<td class='"+((dow+firstDay+6)%7>=5?" ui-datepicker-week-end":"")+(// highlight weekends
	otherMonth?" ui-datepicker-other-month":"")+(// highlight days from other months
	printDate.getTime()===selectedDate.getTime()&&drawMonth===inst.selectedMonth&&inst._keyEvent||// user pressed key
	defaultDate.getTime()===printDate.getTime()&&defaultDate.getTime()===selectedDate.getTime()?// or defaultDate is current printedDate and defaultDate is selectedDate
	" "+this._dayOverClass:"")+(// highlight selected day
	unselectable?" "+this._unselectableClass+" ui-state-disabled":"")+(// highlight unselectable days
	otherMonth&&!showOtherMonths?"":" "+daySettings[1]+(// highlight custom dates
	printDate.getTime()===currentDate.getTime()?" "+this._currentClass:"")+(// highlight selected day
	printDate.getTime()===today.getTime()?" ui-datepicker-today":""))+"'"+(// highlight today (if different)
	(!otherMonth||showOtherMonths)&&daySettings[2]?" title='"+daySettings[2].replace(/'/g,"&#39;")+"'":"")+(// cell title
	unselectable?"":" data-handler='selectDay' data-event='click' data-month='"+printDate.getMonth()+"' data-year='"+printDate.getFullYear()+"'")+">"+(// actions
	otherMonth&&!showOtherMonths?"&#xa0;":// display for other months
	unselectable?"<span class='ui-state-default'>"+printDate.getDate()+"</span>":"<a class='ui-state-default"+(printDate.getTime()===today.getTime()?" ui-state-highlight":"")+(printDate.getTime()===currentDate.getTime()?" ui-state-active":"")+(// highlight selected day
	otherMonth?" ui-priority-secondary":"")+// distinguish dates from other months
	"' href='#' aria-current='"+(printDate.getTime()===currentDate.getTime()?"true":"false")+// mark date as selected for screen reader
	"' data-date='"+printDate.getDate()+// store date as data
	"'>"+printDate.getDate()+"</a>")+"</td>";// display selectable date
	printDate.setDate(printDate.getDate()+1);printDate=this._daylightSavingAdjust(printDate);}calender+=tbody+"</tr>";}drawMonth++;if(drawMonth>11){drawMonth=0;drawYear++;}calender+="</tbody></table>"+(isMultiMonth?"</div>"+(numMonths[0]>0&&col===numMonths[1]-1?"<div class='ui-datepicker-row-break'></div>":""):"");group+=calender;}html+=group;}html+=buttonPanel;inst._keyEvent=false;return html;},/* Generate the month and year header. */_generateMonthYearHeader:function(inst,drawMonth,drawYear,minDate,maxDate,secondary,monthNames,monthNamesShort){var inMinYear,inMaxYear,month,years,thisYear,determineYear,year,endYear,changeMonth=this._get(inst,"changeMonth"),changeYear=this._get(inst,"changeYear"),showMonthAfterYear=this._get(inst,"showMonthAfterYear"),selectMonthLabel=this._get(inst,"selectMonthLabel"),selectYearLabel=this._get(inst,"selectYearLabel"),html="<div class='ui-datepicker-title'>",monthHtml="";// Month selection
	if(secondary||!changeMonth){monthHtml+="<span class='ui-datepicker-month'>"+monthNames[drawMonth]+"</span>";}else {inMinYear=minDate&&minDate.getFullYear()===drawYear;inMaxYear=maxDate&&maxDate.getFullYear()===drawYear;monthHtml+="<select class='ui-datepicker-month' aria-label='"+selectMonthLabel+"' data-handler='selectMonth' data-event='change'>";for(month=0;month<12;month++){if((!inMinYear||month>=minDate.getMonth())&&(!inMaxYear||month<=maxDate.getMonth())){monthHtml+="<option value='"+month+"'"+(month===drawMonth?" selected='selected'":"")+">"+monthNamesShort[month]+"</option>";}}monthHtml+="</select>";}if(!showMonthAfterYear){html+=monthHtml+(secondary||!(changeMonth&&changeYear)?"&#xa0;":"");}// Year selection
	if(!inst.yearshtml){inst.yearshtml="";if(secondary||!changeYear){html+="<span class='ui-datepicker-year'>"+drawYear+"</span>";}else {// determine range of years to display
	years=this._get(inst,"yearRange").split(":");thisYear=new Date().getFullYear();determineYear=function(value){var year=value.match(/c[+\-].*/)?drawYear+parseInt(value.substring(1),10):value.match(/[+\-].*/)?thisYear+parseInt(value,10):parseInt(value,10);return isNaN(year)?thisYear:year;};year=determineYear(years[0]);endYear=Math.max(year,determineYear(years[1]||""));year=minDate?Math.max(year,minDate.getFullYear()):year;endYear=maxDate?Math.min(endYear,maxDate.getFullYear()):endYear;inst.yearshtml+="<select class='ui-datepicker-year' aria-label='"+selectYearLabel+"' data-handler='selectYear' data-event='change'>";for(;year<=endYear;year++){inst.yearshtml+="<option value='"+year+"'"+(year===drawYear?" selected='selected'":"")+">"+year+"</option>";}inst.yearshtml+="</select>";html+=inst.yearshtml;inst.yearshtml=null;}}html+=this._get(inst,"yearSuffix");if(showMonthAfterYear){html+=(secondary||!(changeMonth&&changeYear)?"&#xa0;":"")+monthHtml;}html+="</div>";// Close datepicker_header
	return html;},/* Adjust one of the date sub-fields. */_adjustInstDate:function(inst,offset,period){var year=inst.selectedYear+(period==="Y"?offset:0),month=inst.selectedMonth+(period==="M"?offset:0),day=Math.min(inst.selectedDay,this._getDaysInMonth(year,month))+(period==="D"?offset:0),date=this._restrictMinMax(inst,this._daylightSavingAdjust(new Date(year,month,day)));inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear();if(period==="M"||period==="Y"){this._notifyChange(inst);}},/* Ensure a date is within any min/max bounds. */_restrictMinMax:function(inst,date){var minDate=this._getMinMaxDate(inst,"min"),maxDate=this._getMinMaxDate(inst,"max"),newDate=minDate&&date<minDate?minDate:date;return maxDate&&newDate>maxDate?maxDate:newDate;},/* Notify change of month/year. */_notifyChange:function(inst){var onChange=this._get(inst,"onChangeMonthYear");if(onChange){onChange.apply(inst.input?inst.input[0]:null,[inst.selectedYear,inst.selectedMonth+1,inst]);}},/* Determine the number of months to show. */_getNumberOfMonths:function(inst){var numMonths=this._get(inst,"numberOfMonths");return numMonths==null?[1,1]:typeof numMonths==="number"?[1,numMonths]:numMonths;},/* Determine the current maximum date - ensure no time components are set. */_getMinMaxDate:function(inst,minMax){return this._determineDate(inst,this._get(inst,minMax+"Date"),null);},/* Find the number of days in a given month. */_getDaysInMonth:function(year,month){return 32-this._daylightSavingAdjust(new Date(year,month,32)).getDate();},/* Find the day of the week of the first of a month. */_getFirstDayOfMonth:function(year,month){return new Date(year,month,1).getDay();},/* Determines if we should allow a "next/prev" month display change. */_canAdjustMonth:function(inst,offset,curYear,curMonth){var numMonths=this._getNumberOfMonths(inst),date=this._daylightSavingAdjust(new Date(curYear,curMonth+(offset<0?offset:numMonths[0]*numMonths[1]),1));if(offset<0){date.setDate(this._getDaysInMonth(date.getFullYear(),date.getMonth()));}return this._isInRange(inst,date);},/* Is the given date in the accepted range? */_isInRange:function(inst,date){var yearSplit,currentYear,minDate=this._getMinMaxDate(inst,"min"),maxDate=this._getMinMaxDate(inst,"max"),minYear=null,maxYear=null,years=this._get(inst,"yearRange");if(years){yearSplit=years.split(":");currentYear=new Date().getFullYear();minYear=parseInt(yearSplit[0],10);maxYear=parseInt(yearSplit[1],10);if(yearSplit[0].match(/[+\-].*/)){minYear+=currentYear;}if(yearSplit[1].match(/[+\-].*/)){maxYear+=currentYear;}}return (!minDate||date.getTime()>=minDate.getTime())&&(!maxDate||date.getTime()<=maxDate.getTime())&&(!minYear||date.getFullYear()>=minYear)&&(!maxYear||date.getFullYear()<=maxYear);},/* Provide the configuration settings for formatting/parsing. */_getFormatConfig:function(inst){var shortYearCutoff=this._get(inst,"shortYearCutoff");shortYearCutoff=typeof shortYearCutoff!=="string"?shortYearCutoff:new Date().getFullYear()%100+parseInt(shortYearCutoff,10);return {shortYearCutoff:shortYearCutoff,dayNamesShort:this._get(inst,"dayNamesShort"),dayNames:this._get(inst,"dayNames"),monthNamesShort:this._get(inst,"monthNamesShort"),monthNames:this._get(inst,"monthNames")};},/* Format the given date for display. */_formatDate:function(inst,day,month,year){if(!day){inst.currentDay=inst.selectedDay;inst.currentMonth=inst.selectedMonth;inst.currentYear=inst.selectedYear;}var date=day?typeof day==="object"?day:this._daylightSavingAdjust(new Date(year,month,day)):this._daylightSavingAdjust(new Date(inst.currentYear,inst.currentMonth,inst.currentDay));return this.formatDate(this._get(inst,"dateFormat"),date,this._getFormatConfig(inst));}});/*
		 * Bind hover events for datepicker elements.
		 * Done via delegate so the binding only occurs once in the lifetime of the parent div.
		 * Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
		 */function datepicker_bindHover(dpDiv){var selector="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return dpDiv.on("mouseout",selector,function(){$(this).removeClass("ui-state-hover");if(this.className.indexOf("ui-datepicker-prev")!==-1){$(this).removeClass("ui-datepicker-prev-hover");}if(this.className.indexOf("ui-datepicker-next")!==-1){$(this).removeClass("ui-datepicker-next-hover");}}).on("mouseover",selector,datepicker_handleMouseover);}function datepicker_handleMouseover(){if(!$.datepicker._isDisabledDatepicker(datepicker_instActive.inline?datepicker_instActive.dpDiv.parent()[0]:datepicker_instActive.input[0])){$(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");$(this).addClass("ui-state-hover");if(this.className.indexOf("ui-datepicker-prev")!==-1){$(this).addClass("ui-datepicker-prev-hover");}if(this.className.indexOf("ui-datepicker-next")!==-1){$(this).addClass("ui-datepicker-next-hover");}}}/* jQuery extend now ignores nulls! */function datepicker_extendRemove(target,props){$.extend(target,props);for(var name in props){if(props[name]==null){target[name]=props[name];}}return target;}/* Invoke the datepicker functionality.
		   @param  options  string - a command, optionally followed by additional parameters or
							Object - settings for attaching new datepicker functionality
		   @return  jQuery object */$.fn.datepicker=function(options){/* Verify an empty collection wasn't passed - Fixes #6976 */if(!this.length){return this;}/* Initialise the date picker. */if(!$.datepicker.initialized){$(document).on("mousedown",$.datepicker._checkExternalClick);$.datepicker.initialized=true;}/* Append datepicker main container to body if not exist. */if($("#"+$.datepicker._mainDivId).length===0){$("body").append($.datepicker.dpDiv);}var otherArgs=Array.prototype.slice.call(arguments,1);if(typeof options==="string"&&(options==="isDisabled"||options==="getDate"||options==="widget")){return $.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this[0]].concat(otherArgs));}if(options==="option"&&arguments.length===2&&typeof arguments[1]==="string"){return $.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this[0]].concat(otherArgs));}return this.each(function(){if(typeof options==="string"){$.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this].concat(otherArgs));}else {$.datepicker._attachDatepicker(this,options);}});};$.datepicker=new Datepicker();// singleton instance
	$.datepicker.initialized=false;$.datepicker.uuid=new Date().getTime();$.datepicker.version="1.14.2";$.datepicker;/*!
		 * jQuery UI Mouse 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Mouse
	//>>group: Widgets
	//>>description: Abstracts mouse-based interactions to assist in creating certain widgets.
	//>>docs: https://api.jqueryui.com/mouse/
	var mouseHandled=false;$(document).on("mouseup",function(){mouseHandled=false;});$.widget("ui.mouse",{version:"1.14.2",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)
	if(this._mouseStarted){this._mouseUp(event);}this._mouseDownEvent=event;var that=this,btnIsLeft=event.which===1,elIsCancel=typeof this.options.cancel==="string"?$(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.
	if(this._mouseMoved&&!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;if(this._mouseStarted){this._mouseDrag(event);}else {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;}});// $.ui.plugin is deprecated. Use $.widget() extensions instead.
	$.ui.plugin={add:function(module,option,set){var i,proto=$.ui[module].prototype;for(i in set){proto.plugins[i]=proto.plugins[i]||[];proto.plugins[i].push([option,set[i]]);}},call:function(instance,name,args,allowDisconnected){var i,set=instance.plugins[name];if(!set){return;}if(!allowDisconnected&&(!instance.element[0].parentNode||instance.element[0].parentNode.nodeType===11)){return;}for(i=0;i<set.length;i++){if(instance.options[set[i][0]]){set[i][1].apply(instance.element,args);}}}};/*!
		 * jQuery UI Draggable 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Draggable
	//>>group: Interactions
	//>>description: Enables dragging functionality for any element.
	//>>docs: https://api.jqueryui.com/draggable/
	//>>demos: https://jqueryui.com/draggable/
	//>>css.structure: ../../themes/base/draggable.css
	$.widget("ui.draggable",$.ui.mouse,{version:"1.14.2",widgetEventPrefix:"drag",options:{addClasses:true,appendTo:"parent",axis:false,connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false,// Callbacks
	drag:null,start:null,stop:null},_create:function(){if(this.options.helper==="original"){this._setPositionRelative();}if(this.options.addClasses){this._addClass("ui-draggable");}this._setHandleClassName();this._mouseInit();},_setOption:function(key,value){this._super(key,value);if(key==="handle"){this._removeHandleClassName();this._setHandleClassName();}},_destroy:function(){if((this.helper||this.element).is(".ui-draggable-dragging")){this.destroyOnClear=true;return;}this._removeHandleClassName();this._mouseDestroy();},_mouseCapture:function(event){var o=this.options;// Among others, prevent a drag on a resizable-handle
	if(this.helper||o.disabled||$(event.target).closest(".ui-resizable-handle").length>0){return false;}//Quit if we're not on a valid handle
	this.handle=this._getHandle(event);if(!this.handle){return false;}this._blurActiveElement(event);this._blockFrames(o.iframeFix===true?"iframe":o.iframeFix);return true;},_blockFrames:function(selector){this.iframeBlocks=this.document.find(selector).map(function(){var iframe=$(this);return $("<div>").css("position","absolute").appendTo(iframe.parent()).outerWidth(iframe.outerWidth()).outerHeight(iframe.outerHeight()).offset(iframe.offset())[0];});},_unblockFrames:function(){if(this.iframeBlocks){this.iframeBlocks.remove();delete this.iframeBlocks;}},_blurActiveElement:function(event){var activeElement=this.document[0].activeElement,target=$(event.target);// Don't blur if the event occurred on an element that is within
	// the currently focused element
	// See #10527, #12472
	if(target.closest(activeElement).length){return;}// Blur any element that currently has focus, see #4261
	$(activeElement).trigger("blur");},_mouseStart:function(event){var o=this.options;//Create and append the visible helper
	this.helper=this._createHelper(event);this._addClass(this.helper,"ui-draggable-dragging");//Cache the helper size
	this._cacheHelperProportions();//If ddmanager is used for droppables, set the global draggable
	if($.ui.ddmanager){$.ui.ddmanager.current=this;}/*
				 * - Position generation -
				 * This block generates everything position related - it's the core of draggables.
				 *///Cache the margins of the original element
	this._cacheMargins();//Store the helper's css position
	this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent(true);this.offsetParent=this.helper.offsetParent();this.hasFixedAncestor=this.helper.parents().filter(function(){return $(this).css("position")==="fixed";}).length>0;//The element's absolute position on the page minus margins
	this.positionAbs=this.element.offset();this._refreshOffsets(event);//Generate the original position
	this.originalPosition=this.position=this._generatePosition(event,false);this.originalPageX=event.pageX;this.originalPageY=event.pageY;//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
	if(o.cursorAt){this._adjustOffsetFromHelper(o.cursorAt);}//Set a containment if given in the options
	this._setContainment();//Trigger event + callbacks
	if(this._trigger("start",event)===false){this._clear();return false;}//Recache the helper size
	this._cacheHelperProportions();//Prepare the droppable offsets
	if($.ui.ddmanager&&!o.dropBehaviour){$.ui.ddmanager.prepareOffsets(this,event);}// Execute the drag once - this causes the helper not to be visible before getting its
	// correct position
	this._mouseDrag(event,true);// If the ddmanager is used for droppables, inform the manager that dragging has started
	// (see #5003)
	if($.ui.ddmanager){$.ui.ddmanager.dragStart(this,event);}return true;},_refreshOffsets:function(event){this.offset={top:this.positionAbs.top-this.margins.top,left:this.positionAbs.left-this.margins.left,scroll:false,parent:this._getParentOffset(),relative:this._getRelativeOffset()};this.offset.click={left:event.pageX-this.offset.left,top:event.pageY-this.offset.top};},_mouseDrag:function(event,noPropagation){// reset any necessary cached properties (see #5009)
	if(this.hasFixedAncestor){this.offset.parent=this._getParentOffset();}//Compute the helpers position
	this.position=this._generatePosition(event,true);this.positionAbs=this._convertPositionTo("absolute");//Call plugins and callbacks and use the resulting position if something is returned
	if(!noPropagation){var ui=this._uiHash();if(this._trigger("drag",event,ui)===false){this._mouseUp(new $.Event("mouseup",event));return false;}this.position=ui.position;}this.helper[0].style.left=this.position.left+"px";this.helper[0].style.top=this.position.top+"px";if($.ui.ddmanager){$.ui.ddmanager.drag(this,event);}return false;},_mouseStop:function(event){//If we are using droppables, inform the manager about the drop
	var that=this,dropped=false;if($.ui.ddmanager&&!this.options.dropBehaviour){dropped=$.ui.ddmanager.drop(this,event);}//if a drop comes from outside (a sortable)
	if(this.dropped){dropped=this.dropped;this.dropped=false;}if(this.options.revert==="invalid"&&!dropped||this.options.revert==="valid"&&dropped||this.options.revert===true||typeof this.options.revert==="function"&&this.options.revert.call(this.element,dropped)){$(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){if(that._trigger("stop",event)!==false){that._clear();}});}else {if(this._trigger("stop",event)!==false){this._clear();}}return false;},_mouseUp:function(event){this._unblockFrames();// If the ddmanager is used for droppables, inform the manager that dragging has stopped
	// (see #5003)
	if($.ui.ddmanager){$.ui.ddmanager.dragStop(this,event);}// Only need to focus if the event occurred on the draggable itself, see #10527
	if(this.handleElement.is(event.target)){// The interaction is over; whether or not the click resulted in a drag,
	// focus the element
	this.element.trigger("focus");}return $.ui.mouse.prototype._mouseUp.call(this,event);},cancel:function(){if(this.helper.is(".ui-draggable-dragging")){this._mouseUp(new $.Event("mouseup",{target:this.element[0]}));}else {this._clear();}return this;},_getHandle:function(event){return this.options.handle?!!$(event.target).closest(this.element.find(this.options.handle)).length:true;},_setHandleClassName:function(){this.handleElement=this.options.handle?this.element.find(this.options.handle):this.element;this._addClass(this.handleElement,"ui-draggable-handle");},_removeHandleClassName:function(){this._removeClass(this.handleElement,"ui-draggable-handle");},_createHelper:function(event){var o=this.options,helperIsFunction=typeof o.helper==="function",helper=helperIsFunction?$(o.helper.apply(this.element[0],[event])):o.helper==="clone"?this.element.clone().removeAttr("id"):this.element;if(!helper.parents("body").length){helper.appendTo(o.appendTo==="parent"?this.element[0].parentNode:o.appendTo);}// https://bugs.jqueryui.com/ticket/9446
	// a helper function can return the original element
	// which wouldn't have been set to relative in _create
	if(helperIsFunction&&helper[0]===this.element[0]){this._setPositionRelative();}if(helper[0]!==this.element[0]&&!/(fixed|absolute)/.test(helper.css("position"))){helper.css("position","absolute");}return helper;},_setPositionRelative:function(){if(!/^(?:r|a|f)/.test(this.element.css("position"))){this.element[0].style.position="relative";}},_adjustOffsetFromHelper:function(obj){if(typeof obj==="string"){obj=obj.split(" ");}if(Array.isArray(obj)){obj={left:+obj[0],top:+obj[1]||0};}if("left"in obj){this.offset.click.left=obj.left+this.margins.left;}if("right"in obj){this.offset.click.left=this.helperProportions.width-obj.right+this.margins.left;}if("top"in obj){this.offset.click.top=obj.top+this.margins.top;}if("bottom"in obj){this.offset.click.top=this.helperProportions.height-obj.bottom+this.margins.top;}},_isRootNode:function(element){return /(html|body)/i.test(element.tagName)||element===this.document[0];},_getParentOffset:function(){//Get the offsetParent and cache its position
	var po=this.offsetParent.offset(),document=this.document[0];// This is a special case where we need to modify a offset calculated on start, since the
	// following happened:
	// 1. The position of the helper is absolute, so it's position is calculated based on the
	// next positioned parent
	// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't
	// the document, which means that the scroll is included in the initial calculation of the
	// offset of the parent, and never recalculated upon drag
	if(this.cssPosition==="absolute"&&this.scrollParent[0]!==document&&$.contains(this.scrollParent[0],this.offsetParent[0])){po.left+=this.scrollParent.scrollLeft();po.top+=this.scrollParent.scrollTop();}if(this._isRootNode(this.offsetParent[0])){po={top:0,left:0};}return {top:po.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:po.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)};},_getRelativeOffset:function(){if(this.cssPosition!=="relative"){return {top:0,left:0};}var p=this.element.position(),scrollIsRootNode=this._isRootNode(this.scrollParent[0]);return {top:p.top-(parseInt(this.helper.css("top"),10)||0)+(!scrollIsRootNode?this.scrollParent.scrollTop():0),left:p.left-(parseInt(this.helper.css("left"),10)||0)+(!scrollIsRootNode?this.scrollParent.scrollLeft():0)};},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0};},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()};},_setContainment:function(){var isUserScrollable,c,ce,o=this.options,document=this.document[0];this.relativeContainer=null;if(!o.containment){this.containment=null;return;}if(o.containment==="window"){this.containment=[$(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,$(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,$(window).scrollLeft()+$(window).width()-this.helperProportions.width-this.margins.left,$(window).scrollTop()+($(window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];return;}if(o.containment==="document"){this.containment=[0,0,$(document).width()-this.helperProportions.width-this.margins.left,($(document).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];return;}if(o.containment.constructor===Array){this.containment=o.containment;return;}if(o.containment==="parent"){o.containment=this.helper[0].parentNode;}c=$(o.containment);ce=c[0];if(!ce){return;}isUserScrollable=/(scroll|auto)/.test(c.css("overflow"));this.containment=[(parseInt(c.css("borderLeftWidth"),10)||0)+(parseInt(c.css("paddingLeft"),10)||0),(parseInt(c.css("borderTopWidth"),10)||0)+(parseInt(c.css("paddingTop"),10)||0),(isUserScrollable?Math.max(ce.scrollWidth,ce.offsetWidth):ce.offsetWidth)-(parseInt(c.css("borderRightWidth"),10)||0)-(parseInt(c.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(isUserScrollable?Math.max(ce.scrollHeight,ce.offsetHeight):ce.offsetHeight)-(parseInt(c.css("borderBottomWidth"),10)||0)-(parseInt(c.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom];this.relativeContainer=c;},_convertPositionTo:function(d,pos){if(!pos){pos=this.position;}var mod=d==="absolute"?1:-1,scrollIsRootNode=this._isRootNode(this.scrollParent[0]);return {top:// The absolute mouse position
	pos.top+// Only for relative positioned nodes: Relative offset from element to offset parent
	this.offset.relative.top*mod+// The offsetParent's offset without borders (offset + border)
	this.offset.parent.top*mod-(this.cssPosition==="fixed"?-this.offset.scroll.top:scrollIsRootNode?0:this.offset.scroll.top)*mod,left:// The absolute mouse position
	pos.left+// Only for relative positioned nodes: Relative offset from element to offset parent
	this.offset.relative.left*mod+// The offsetParent's offset without borders (offset + border)
	this.offset.parent.left*mod-(this.cssPosition==="fixed"?-this.offset.scroll.left:scrollIsRootNode?0:this.offset.scroll.left)*mod};},_generatePosition:function(event,constrainPosition){var containment,co,top,left,o=this.options,scrollIsRootNode=this._isRootNode(this.scrollParent[0]),pageX=event.pageX,pageY=event.pageY;// Cache the scroll
	if(!scrollIsRootNode||!this.offset.scroll){this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()};}/*
				 * - Position constraining -
				 * Constrain the position to a mix of grid, containment.
				 */// If we are not dragging yet, we won't check for options
	if(constrainPosition){if(this.containment){if(this.relativeContainer){co=this.relativeContainer.offset();containment=[this.containment[0]+co.left,this.containment[1]+co.top,this.containment[2]+co.left,this.containment[3]+co.top];}else {containment=this.containment;}if(event.pageX-this.offset.click.left<containment[0]){pageX=containment[0]+this.offset.click.left;}if(event.pageY-this.offset.click.top<containment[1]){pageY=containment[1]+this.offset.click.top;}if(event.pageX-this.offset.click.left>containment[2]){pageX=containment[2]+this.offset.click.left;}if(event.pageY-this.offset.click.top>containment[3]){pageY=containment[3]+this.offset.click.top;}}if(o.grid){//Check for grid elements set to 0 to prevent divide by 0 error causing invalid
	// argument errors in IE (see ticket #6950)
	top=o.grid[1]?this.originalPageY+Math.round((pageY-this.originalPageY)/o.grid[1])*o.grid[1]:this.originalPageY;pageY=containment?top-this.offset.click.top>=containment[1]||top-this.offset.click.top>containment[3]?top:top-this.offset.click.top>=containment[1]?top-o.grid[1]:top+o.grid[1]:top;left=o.grid[0]?this.originalPageX+Math.round((pageX-this.originalPageX)/o.grid[0])*o.grid[0]:this.originalPageX;pageX=containment?left-this.offset.click.left>=containment[0]||left-this.offset.click.left>containment[2]?left:left-this.offset.click.left>=containment[0]?left-o.grid[0]:left+o.grid[0]:left;}if(o.axis==="y"){pageX=this.originalPageX;}if(o.axis==="x"){pageY=this.originalPageY;}}return {top:// The absolute mouse position
	pageY-// Click offset (relative to the element)
	this.offset.click.top-// Only for relative positioned nodes: Relative offset from element to offset parent
	this.offset.relative.top-// The offsetParent's offset without borders (offset + border)
	this.offset.parent.top+(this.cssPosition==="fixed"?-this.offset.scroll.top:scrollIsRootNode?0:this.offset.scroll.top),left:// The absolute mouse position
	pageX-// Click offset (relative to the element)
	this.offset.click.left-// Only for relative positioned nodes: Relative offset from element to offset parent
	this.offset.relative.left-// The offsetParent's offset without borders (offset + border)
	this.offset.parent.left+(this.cssPosition==="fixed"?-this.offset.scroll.left:scrollIsRootNode?0:this.offset.scroll.left)};},_clear:function(){this._removeClass(this.helper,"ui-draggable-dragging");if(this.helper[0]!==this.element[0]&&!this.cancelHelperRemoval){this.helper.remove();}this.helper=null;this.cancelHelperRemoval=false;if(this.destroyOnClear){this.destroy();}},// From now on bulk stuff - mainly helpers
	_trigger:function(type,event,ui){ui=ui||this._uiHash();$.ui.plugin.call(this,type,[event,ui,this],true);// Absolute position and offset (see #6884 ) have to be recalculated after plugins
	if(/^(drag|start|stop)/.test(type)){this.positionAbs=this._convertPositionTo("absolute");ui.offset=this.positionAbs;}return $.Widget.prototype._trigger.call(this,type,event,ui);},plugins:{},_uiHash:function(){return {helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs};}});$.ui.plugin.add("draggable","connectToSortable",{start:function(event,ui,draggable){var uiSortable=$.extend({},ui,{item:draggable.element});draggable.sortables=[];$(draggable.options.connectToSortable).each(function(){var sortable=$(this).sortable("instance");if(sortable&&!sortable.options.disabled){draggable.sortables.push(sortable);// RefreshPositions is called at drag start to refresh the containerCache
	// which is used in drag. This ensures it's initialized and synchronized
	// with any changes that might have happened on the page since initialization.
	sortable.refreshPositions();sortable._trigger("activate",event,uiSortable);}});},stop:function(event,ui,draggable){var uiSortable=$.extend({},ui,{item:draggable.element});draggable.cancelHelperRemoval=false;$.each(draggable.sortables,function(){var sortable=this;if(sortable.isOver){sortable.isOver=0;// Allow this sortable to handle removing the helper
	draggable.cancelHelperRemoval=true;sortable.cancelHelperRemoval=false;// Use _storedCSS To restore properties in the sortable,
	// as this also handles revert (#9675) since the draggable
	// may have modified them in unexpected ways (#8809)
	sortable._storedCSS={position:sortable.placeholder.css("position"),top:sortable.placeholder.css("top"),left:sortable.placeholder.css("left")};sortable._mouseStop(event);// Once drag has ended, the sortable should return to using
	// its original helper, not the shared helper from draggable
	sortable.options.helper=sortable.options._helper;}else {// Prevent this Sortable from removing the helper.
	// However, don't set the draggable to remove the helper
	// either as another connected Sortable may yet handle the removal.
	sortable.cancelHelperRemoval=true;sortable._trigger("deactivate",event,uiSortable);}});},drag:function(event,ui,draggable){$.each(draggable.sortables,function(){var innermostIntersecting=false,sortable=this;// Copy over variables that sortable's _intersectsWith uses
	sortable.positionAbs=draggable.positionAbs;sortable.helperProportions=draggable.helperProportions;sortable.offset.click=draggable.offset.click;if(sortable._intersectsWith(sortable.containerCache)){innermostIntersecting=true;$.each(draggable.sortables,function(){// Copy over variables that sortable's _intersectsWith uses
	this.positionAbs=draggable.positionAbs;this.helperProportions=draggable.helperProportions;this.offset.click=draggable.offset.click;if(this!==sortable&&this._intersectsWith(this.containerCache)&&$.contains(sortable.element[0],this.element[0])){innermostIntersecting=false;}return innermostIntersecting;});}if(innermostIntersecting){// If it intersects, we use a little isOver variable and set it once,
	// so that the move-in stuff gets fired only once.
	if(!sortable.isOver){sortable.isOver=1;// Store draggable's parent in case we need to reappend to it later.
	draggable._parent=ui.helper.parent();sortable.currentItem=ui.helper.appendTo(sortable.element).data("ui-sortable-item",true);// Store helper option to later restore it
	sortable.options._helper=sortable.options.helper;sortable.options.helper=function(){return ui.helper[0];};// Fire the start events of the sortable with our passed browser event,
	// and our own helper (so it doesn't create a new one)
	event.target=sortable.currentItem[0];sortable._mouseCapture(event,true);sortable._mouseStart(event,true,true);// Because the browser event is way off the new appended portlet,
	// modify necessary variables to reflect the changes
	sortable.offset.click.top=draggable.offset.click.top;sortable.offset.click.left=draggable.offset.click.left;sortable.offset.parent.left-=draggable.offset.parent.left-sortable.offset.parent.left;sortable.offset.parent.top-=draggable.offset.parent.top-sortable.offset.parent.top;draggable._trigger("toSortable",event);// Inform draggable that the helper is in a valid drop zone,
	// used solely in the revert option to handle "valid/invalid".
	draggable.dropped=sortable.element;// Need to refreshPositions of all sortables in the case that
	// adding to one sortable changes the location of the other sortables (#9675)
	$.each(draggable.sortables,function(){this.refreshPositions();});// Hack so receive/update callbacks work (mostly)
	draggable.currentItem=draggable.element;sortable.fromOutside=draggable;}if(sortable.currentItem){sortable._mouseDrag(event);// Copy the sortable's position because the draggable's can potentially reflect
	// a relative position, while sortable is always absolute, which the dragged
	// element has now become. (#8809)
	ui.position=sortable.position;}}else {// If it doesn't intersect with the sortable, and it intersected before,
	// we fake the drag stop of the sortable, but make sure it doesn't remove
	// the helper by using cancelHelperRemoval.
	if(sortable.isOver){sortable.isOver=0;sortable.cancelHelperRemoval=true;// Calling sortable's mouseStop would trigger a revert,
	// so revert must be temporarily false until after mouseStop is called.
	sortable.options._revert=sortable.options.revert;sortable.options.revert=false;sortable._trigger("out",event,sortable._uiHash(sortable));sortable._mouseStop(event,true);// Restore sortable behaviors that were modfied
	// when the draggable entered the sortable area (#9481)
	sortable.options.revert=sortable.options._revert;sortable.options.helper=sortable.options._helper;if(sortable.placeholder){sortable.placeholder.remove();}// Restore and recalculate the draggable's offset considering the sortable
	// may have modified them in unexpected ways. (#8809, #10669)
	ui.helper.appendTo(draggable._parent);draggable._refreshOffsets(event);ui.position=draggable._generatePosition(event,true);draggable._trigger("fromSortable",event);// Inform draggable that the helper is no longer in a valid drop zone
	draggable.dropped=false;// Need to refreshPositions of all sortables just in case removing
	// from one sortable changes the location of other sortables (#9675)
	$.each(draggable.sortables,function(){this.refreshPositions();});}}});}});$.ui.plugin.add("draggable","cursor",{start:function(event,ui,instance){var t=$("body"),o=instance.options;if(t.css("cursor")){o._cursor=t.css("cursor");}t.css("cursor",o.cursor);},stop:function(event,ui,instance){var o=instance.options;if(o._cursor){$("body").css("cursor",o._cursor);}}});$.ui.plugin.add("draggable","opacity",{start:function(event,ui,instance){var t=$(ui.helper),o=instance.options;if(t.css("opacity")){o._opacity=t.css("opacity");}t.css("opacity",o.opacity);},stop:function(event,ui,instance){var o=instance.options;if(o._opacity){$(ui.helper).css("opacity",o._opacity);}}});$.ui.plugin.add("draggable","scroll",{start:function(event,ui,i){if(!i.scrollParentNotHidden){i.scrollParentNotHidden=i.helper.scrollParent(false);}if(i.scrollParentNotHidden[0]!==i.document[0]&&i.scrollParentNotHidden[0].tagName!=="HTML"){i.overflowOffset=i.scrollParentNotHidden.offset();}},drag:function(event,ui,i){var o=i.options,scrolled=false,scrollParent=i.scrollParentNotHidden[0],document=i.document[0];if(scrollParent!==document&&scrollParent.tagName!=="HTML"){if(!o.axis||o.axis!=="x"){if(i.overflowOffset.top+scrollParent.offsetHeight-event.pageY<o.scrollSensitivity){scrollParent.scrollTop=scrolled=scrollParent.scrollTop+o.scrollSpeed;}else if(event.pageY-i.overflowOffset.top<o.scrollSensitivity){scrollParent.scrollTop=scrolled=scrollParent.scrollTop-o.scrollSpeed;}}if(!o.axis||o.axis!=="y"){if(i.overflowOffset.left+scrollParent.offsetWidth-event.pageX<o.scrollSensitivity){scrollParent.scrollLeft=scrolled=scrollParent.scrollLeft+o.scrollSpeed;}else if(event.pageX-i.overflowOffset.left<o.scrollSensitivity){scrollParent.scrollLeft=scrolled=scrollParent.scrollLeft-o.scrollSpeed;}}}else {if(!o.axis||o.axis!=="x"){if(event.pageY-$(document).scrollTop()<o.scrollSensitivity){scrolled=$(document).scrollTop($(document).scrollTop()-o.scrollSpeed);}else if($(window).height()-(event.pageY-$(document).scrollTop())<o.scrollSensitivity){scrolled=$(document).scrollTop($(document).scrollTop()+o.scrollSpeed);}}if(!o.axis||o.axis!=="y"){if(event.pageX-$(document).scrollLeft()<o.scrollSensitivity){scrolled=$(document).scrollLeft($(document).scrollLeft()-o.scrollSpeed);}else if($(window).width()-(event.pageX-$(document).scrollLeft())<o.scrollSensitivity){scrolled=$(document).scrollLeft($(document).scrollLeft()+o.scrollSpeed);}}}if(scrolled!==false&&$.ui.ddmanager&&!o.dropBehaviour){$.ui.ddmanager.prepareOffsets(i,event);}}});$.ui.plugin.add("draggable","snap",{start:function(event,ui,i){var o=i.options;i.snapElements=[];$(o.snap.constructor!==String?o.snap.items||":data(ui-draggable)":o.snap).each(function(){var $t=$(this),$o=$t.offset();if(this!==i.element[0]){i.snapElements.push({item:this,width:$t.outerWidth(),height:$t.outerHeight(),top:$o.top,left:$o.left});}});},drag:function(event,ui,inst){var ts,bs,ls,rs,l,r,t,b,i,first,o=inst.options,d=o.snapTolerance,x1=ui.offset.left,x2=x1+inst.helperProportions.width,y1=ui.offset.top,y2=y1+inst.helperProportions.height;for(i=inst.snapElements.length-1;i>=0;i--){l=inst.snapElements[i].left-inst.margins.left;r=l+inst.snapElements[i].width;t=inst.snapElements[i].top-inst.margins.top;b=t+inst.snapElements[i].height;if(x2<l-d||x1>r+d||y2<t-d||y1>b+d||!$.contains(inst.snapElements[i].item.ownerDocument,inst.snapElements[i].item)){if(inst.snapElements[i].snapping){if(inst.options.snap.release){inst.options.snap.release.call(inst.element,event,$.extend(inst._uiHash(),{snapItem:inst.snapElements[i].item}));}}inst.snapElements[i].snapping=false;continue;}if(o.snapMode!=="inner"){ts=Math.abs(t-y2)<=d;bs=Math.abs(b-y1)<=d;ls=Math.abs(l-x2)<=d;rs=Math.abs(r-x1)<=d;if(ts){ui.position.top=inst._convertPositionTo("relative",{top:t-inst.helperProportions.height,left:0}).top;}if(bs){ui.position.top=inst._convertPositionTo("relative",{top:b,left:0}).top;}if(ls){ui.position.left=inst._convertPositionTo("relative",{top:0,left:l-inst.helperProportions.width}).left;}if(rs){ui.position.left=inst._convertPositionTo("relative",{top:0,left:r}).left;}}first=ts||bs||ls||rs;if(o.snapMode!=="outer"){ts=Math.abs(t-y1)<=d;bs=Math.abs(b-y2)<=d;ls=Math.abs(l-x1)<=d;rs=Math.abs(r-x2)<=d;if(ts){ui.position.top=inst._convertPositionTo("relative",{top:t,left:0}).top;}if(bs){ui.position.top=inst._convertPositionTo("relative",{top:b-inst.helperProportions.height,left:0}).top;}if(ls){ui.position.left=inst._convertPositionTo("relative",{top:0,left:l}).left;}if(rs){ui.position.left=inst._convertPositionTo("relative",{top:0,left:r-inst.helperProportions.width}).left;}}if(!inst.snapElements[i].snapping&&(ts||bs||ls||rs||first)){if(inst.options.snap.snap){inst.options.snap.snap.call(inst.element,event,$.extend(inst._uiHash(),{snapItem:inst.snapElements[i].item}));}}inst.snapElements[i].snapping=ts||bs||ls||rs||first;}}});$.ui.plugin.add("draggable","stack",{start:function(event,ui,instance){var min,o=instance.options,group=$.makeArray($(o.stack)).sort(function(a,b){return (parseInt($(a).css("zIndex"),10)||0)-(parseInt($(b).css("zIndex"),10)||0);});if(!group.length){return;}min=parseInt($(group[0]).css("zIndex"),10)||0;$(group).each(function(i){$(this).css("zIndex",min+i);});this.css("zIndex",min+group.length);}});$.ui.plugin.add("draggable","zIndex",{start:function(event,ui,instance){var t=$(ui.helper),o=instance.options;if(t.css("zIndex")){o._zIndex=t.css("zIndex");}t.css("zIndex",o.zIndex);},stop:function(event,ui,instance){var o=instance.options;if(o._zIndex){$(ui.helper).css("zIndex",o._zIndex);}}});$.ui.draggable;/*!
		 * jQuery UI Resizable 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Resizable
	//>>group: Interactions
	//>>description: Enables resize functionality for any element.
	//>>docs: https://api.jqueryui.com/resizable/
	//>>demos: https://jqueryui.com/resizable/
	//>>css.structure: ../../themes/base/core.css
	//>>css.structure: ../../themes/base/resizable.css
	//>>css.theme: ../../themes/base/theme.css
	$.widget("ui.resizable",$.ui.mouse,{version:"1.14.2",widgetEventPrefix:"resize",options:{alsoResize:false,animate:false,animateDuration:"slow",animateEasing:"swing",aspectRatio:false,autoHide:false,classes:{"ui-resizable-se":"ui-icon ui-icon-gripsmall-diagonal-se"},containment:false,ghost:false,grid:false,handles:"e,s,se",helper:false,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,// See #7960
	zIndex:90,// Callbacks
	resize:null,start:null,stop:null},_num:function(value){return parseFloat(value)||0;},_isNumber:function(value){return !isNaN(parseFloat(value));},_hasScroll:function(el,a){var scroll,has=false,overflow=$(el).css("overflow");if(overflow==="hidden"){return false;}if(overflow==="scroll"){return true;}scroll=a&&a==="left"?"scrollLeft":"scrollTop";if(el[scroll]>0){return true;}// TODO: determine which cases actually cause this to happen
	// if the element doesn't have the scroll set, see if it's possible to
	// set the scroll
	try{el[scroll]=1;has=el[scroll]>0;el[scroll]=0;}catch(_e){// `el` might be a string, then setting `scroll` will throw
	// an error in strict mode; ignore it.
	}return has;},_create:function(){var margins,o=this.options,that=this;this._addClass("ui-resizable");$.extend(this,{_aspectRatio:!!o.aspectRatio,aspectRatio:o.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:o.helper||o.ghost||o.animate?o.helper||"ui-resizable-helper":null});// Wrap the element if it cannot hold child nodes
	if(this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)){this.element.wrap($("<div class='ui-wrapper'></div>").css({overflow:"hidden",position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")}));this.element=this.element.parent().data("ui-resizable",this.element.resizable("instance"));this.elementIsWrapper=true;margins={marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom"),marginLeft:this.originalElement.css("marginLeft")};this.element.css(margins);// Support: Safari
	// Prevent Safari textarea resize
	this.originalResizeStyle=this.originalElement.css("resize");this.originalElement.css("resize","none");this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"}));this._proportionallyResize();}this._setupHandles();if(o.autoHide){$(this.element).on("mouseenter",function(){if(o.disabled){return;}that._removeClass("ui-resizable-autohide");that._handles.show();}).on("mouseleave",function(){if(o.disabled){return;}if(!that.resizing){that._addClass("ui-resizable-autohide");that._handles.hide();}});}this._mouseInit();},_destroy:function(){this._mouseDestroy();this._addedHandles.remove();var wrapper,_destroy=function(exp){$(exp).removeData("resizable").removeData("ui-resizable").off(".resizable");};// TODO: Unwrap at same DOM position
	if(this.elementIsWrapper){_destroy(this.element);wrapper=this.element;this.originalElement.css({position:wrapper.css("position"),width:wrapper.outerWidth(),height:wrapper.outerHeight(),top:wrapper.css("top"),left:wrapper.css("left")}).insertAfter(wrapper);wrapper.remove();}this.originalElement.css("resize",this.originalResizeStyle);_destroy(this.originalElement);return this;},_setOption:function(key,value){this._super(key,value);switch(key){case "handles":this._removeHandles();this._setupHandles();break;case "aspectRatio":this._aspectRatio=!!value;break;}},_setupHandles:function(){var o=this.options,handle,i,n,hname,axis,that=this;this.handles=o.handles||(!$(".ui-resizable-handle",this.element).length?"e,s,se":{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"});this._handles=$();this._addedHandles=$();if(this.handles.constructor===String){if(this.handles==="all"){this.handles="n,e,s,w,se,sw,ne,nw";}n=this.handles.split(",");this.handles={};for(i=0;i<n.length;i++){handle=String.prototype.trim.call(n[i]);hname="ui-resizable-"+handle;axis=$("<div>");this._addClass(axis,"ui-resizable-handle "+hname);axis.css({zIndex:o.zIndex});this.handles[handle]=".ui-resizable-"+handle;if(!this.element.children(this.handles[handle]).length){this.element.append(axis);this._addedHandles=this._addedHandles.add(axis);}}}this._renderAxis=function(target){var i,axis,padPos,padWrapper;target=target||this.element;for(i in this.handles){if(this.handles[i].constructor===String){this.handles[i]=this.element.children(this.handles[i]).first().show();}else if(this.handles[i].jquery||this.handles[i].nodeType){this.handles[i]=$(this.handles[i]);this._on(this.handles[i],{"mousedown":that._mouseDown});}if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)){axis=$(this.handles[i],this.element);padWrapper=/sw|ne|nw|se|n|s/.test(i)?axis.outerHeight():axis.outerWidth();padPos=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join("");target.css(padPos,padWrapper);this._proportionallyResize();}this._handles=this._handles.add(this.handles[i]);}};// TODO: make renderAxis a prototype function
	this._renderAxis(this.element);this._handles=this._handles.add(this.element.find(".ui-resizable-handle"));this._handles.disableSelection();this._handles.on("mouseover",function(){if(!that.resizing){if(this.className){axis=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);}that.axis=axis&&axis[1]?axis[1]:"se";}});if(o.autoHide){this._handles.hide();this._addClass("ui-resizable-autohide");}},_removeHandles:function(){this._addedHandles.remove();},_mouseCapture:function(event){var i,handle,capture=false;for(i in this.handles){handle=$(this.handles[i])[0];if(handle===event.target||$.contains(handle,event.target)){capture=true;}}return !this.options.disabled&&capture;},_mouseStart:function(event){var curleft,curtop,cursor,calculatedSize,o=this.options,el=this.element;this.resizing=true;this._renderProxy();curleft=this._num(this.helper.css("left"));curtop=this._num(this.helper.css("top"));if(o.containment){curleft+=$(o.containment).scrollLeft()||0;curtop+=$(o.containment).scrollTop()||0;}this.offset=this.helper.offset();this.position={left:curleft,top:curtop};if(!this._helper){calculatedSize=this._calculateAdjustedElementDimensions(el);}this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:calculatedSize.width,height:calculatedSize.height};this.originalSize=this._helper?{width:el.outerWidth(),height:el.outerHeight()}:{width:calculatedSize.width,height:calculatedSize.height};this.sizeDiff={width:el.outerWidth()-el.width(),height:el.outerHeight()-el.height()};this.originalPosition={left:curleft,top:curtop};this.originalMousePosition={left:event.pageX,top:event.pageY};this.aspectRatio=typeof o.aspectRatio==="number"?o.aspectRatio:this.originalSize.width/this.originalSize.height||1;cursor=$(".ui-resizable-"+this.axis).css("cursor");$("body").css("cursor",cursor==="auto"?this.axis+"-resize":cursor);this._addClass("ui-resizable-resizing");this._propagate("start",event);return true;},_mouseDrag:function(event){var data,props,smp=this.originalMousePosition,a=this.axis,dx=event.pageX-smp.left||0,dy=event.pageY-smp.top||0,trigger=this._change[a];this._updatePrevProperties();if(!trigger){return false;}data=trigger.apply(this,[event,dx,dy]);this._updateVirtualBoundaries(event.shiftKey);if(this._aspectRatio||event.shiftKey){data=this._updateRatio(data,event);}data=this._respectSize(data,event);this._updateCache(data);this._propagate("resize",event);props=this._applyChanges();if(!this._helper&&this._proportionallyResizeElements.length){this._proportionallyResize();}if(!$.isEmptyObject(props)){this._updatePrevProperties();this._trigger("resize",event,this.ui());this._applyChanges();}return false;},_mouseStop:function(event){this.resizing=false;var pr,ista,soffseth,soffsetw,s,left,top,o=this.options,that=this;if(this._helper){pr=this._proportionallyResizeElements;ista=pr.length&&/textarea/i.test(pr[0].nodeName);soffseth=ista&&this._hasScroll(pr[0],"left")?0:that.sizeDiff.height;soffsetw=ista?0:that.sizeDiff.width;s={width:that.helper.width()-soffsetw,height:that.helper.height()-soffseth};left=parseFloat(that.element.css("left"))+(that.position.left-that.originalPosition.left)||null;top=parseFloat(that.element.css("top"))+(that.position.top-that.originalPosition.top)||null;if(!o.animate){this.element.css($.extend(s,{top:top,left:left}));}that.helper.height(that.size.height);that.helper.width(that.size.width);if(this._helper&&!o.animate){this._proportionallyResize();}}$("body").css("cursor","auto");this._removeClass("ui-resizable-resizing");this._propagate("stop",event);if(this._helper){this.helper.remove();}return false;},_updatePrevProperties:function(){this.prevPosition={top:this.position.top,left:this.position.left};this.prevSize={width:this.size.width,height:this.size.height};},_applyChanges:function(){var props={};if(this.position.top!==this.prevPosition.top){props.top=this.position.top+"px";}if(this.position.left!==this.prevPosition.left){props.left=this.position.left+"px";}this.helper.css(props);if(this.size.width!==this.prevSize.width){props.width=this.size.width+"px";this.helper.width(props.width);}if(this.size.height!==this.prevSize.height){props.height=this.size.height+"px";this.helper.height(props.height);}return props;},_updateVirtualBoundaries:function(forceAspectRatio){var pMinWidth,pMaxWidth,pMinHeight,pMaxHeight,b,o=this.options;b={minWidth:this._isNumber(o.minWidth)?o.minWidth:0,maxWidth:this._isNumber(o.maxWidth)?o.maxWidth:Infinity,minHeight:this._isNumber(o.minHeight)?o.minHeight:0,maxHeight:this._isNumber(o.maxHeight)?o.maxHeight:Infinity};if(this._aspectRatio||forceAspectRatio){pMinWidth=b.minHeight*this.aspectRatio;pMinHeight=b.minWidth/this.aspectRatio;pMaxWidth=b.maxHeight*this.aspectRatio;pMaxHeight=b.maxWidth/this.aspectRatio;if(pMinWidth>b.minWidth){b.minWidth=pMinWidth;}if(pMinHeight>b.minHeight){b.minHeight=pMinHeight;}if(pMaxWidth<b.maxWidth){b.maxWidth=pMaxWidth;}if(pMaxHeight<b.maxHeight){b.maxHeight=pMaxHeight;}}this._vBoundaries=b;},_updateCache:function(data){this.offset=this.helper.offset();if(this._isNumber(data.left)){this.position.left=data.left;}if(this._isNumber(data.top)){this.position.top=data.top;}if(this._isNumber(data.height)){this.size.height=data.height;}if(this._isNumber(data.width)){this.size.width=data.width;}},_updateRatio:function(data){var cpos=this.position,csize=this.size,a=this.axis;if(this._isNumber(data.height)){data.width=data.height*this.aspectRatio;}else if(this._isNumber(data.width)){data.height=data.width/this.aspectRatio;}if(a==="sw"){data.left=cpos.left+(csize.width-data.width);data.top=null;}if(a==="nw"){data.top=cpos.top+(csize.height-data.height);data.left=cpos.left+(csize.width-data.width);}return data;},_respectSize:function(data){var o=this._vBoundaries,a=this.axis,ismaxw=this._isNumber(data.width)&&o.maxWidth&&o.maxWidth<data.width,ismaxh=this._isNumber(data.height)&&o.maxHeight&&o.maxHeight<data.height,isminw=this._isNumber(data.width)&&o.minWidth&&o.minWidth>data.width,isminh=this._isNumber(data.height)&&o.minHeight&&o.minHeight>data.height,dw=this.originalPosition.left+this.originalSize.width,dh=this.originalPosition.top+this.originalSize.height,cw=/sw|nw|w/.test(a),ch=/nw|ne|n/.test(a);if(isminw){data.width=o.minWidth;}if(isminh){data.height=o.minHeight;}if(ismaxw){data.width=o.maxWidth;}if(ismaxh){data.height=o.maxHeight;}if(isminw&&cw){data.left=dw-o.minWidth;}if(ismaxw&&cw){data.left=dw-o.maxWidth;}if(isminh&&ch){data.top=dh-o.minHeight;}if(ismaxh&&ch){data.top=dh-o.maxHeight;}// Fixing jump error on top/left - bug #2330
	if(!data.width&&!data.height&&!data.left&&data.top){data.top=null;}else if(!data.width&&!data.height&&!data.top&&data.left){data.left=null;}return data;},_getPaddingPlusBorderDimensions:function(element){var i=0,widths=[],borders=[element.css("borderTopWidth"),element.css("borderRightWidth"),element.css("borderBottomWidth"),element.css("borderLeftWidth")],paddings=[element.css("paddingTop"),element.css("paddingRight"),element.css("paddingBottom"),element.css("paddingLeft")];for(;i<4;i++){widths[i]=parseFloat(borders[i])||0;widths[i]+=parseFloat(paddings[i])||0;}return {height:widths[0]+widths[2],width:widths[1]+widths[3]};},_calculateAdjustedElementDimensions:function(element){var elWidth,elHeight,paddingBorder,ce=element.get(0);if(element.css("box-sizing")!=="content-box"||!this._hasScroll(ce)&&!this._hasScroll(ce,"left")){return {height:parseFloat(element.css("height")),width:parseFloat(element.css("width"))};}// Check if CSS inline styles are set and use those (usually from previous resizes)
	elWidth=parseFloat(ce.style.width);elHeight=parseFloat(ce.style.height);paddingBorder=this._getPaddingPlusBorderDimensions(element);elWidth=isNaN(elWidth)?this._getElementTheoreticalSize(element,paddingBorder,"width"):elWidth;elHeight=isNaN(elHeight)?this._getElementTheoreticalSize(element,paddingBorder,"height"):elHeight;return {height:elHeight,width:elWidth};},_getElementTheoreticalSize:function(element,extraSize,dimension){// offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border
	var size=Math.max(0,Math.ceil(element.get(0)["offset"+dimension[0].toUpperCase()+dimension.slice(1)]-extraSize[dimension]-0.5// If offsetWidth/offsetHeight is unknown, then we can't determine theoretical size.
	// Use an explicit zero to avoid NaN.
	// See https://github.com/jquery/jquery/issues/3964
	))||0;return size;},_proportionallyResize:function(){if(!this._proportionallyResizeElements.length){return;}var prel,i=0,element=this.helper||this.element;for(;i<this._proportionallyResizeElements.length;i++){prel=this._proportionallyResizeElements[i];// TODO: Seems like a bug to cache this.outerDimensions
	// considering that we are in a loop.
	if(!this.outerDimensions){this.outerDimensions=this._getPaddingPlusBorderDimensions(prel);}prel.css({height:element.height()-this.outerDimensions.height||0,width:element.width()-this.outerDimensions.width||0});}},_renderProxy:function(){var el=this.element,o=this.options;this.elementOffset=el.offset();if(this._helper){this.helper=this.helper||$("<div></div>").css({overflow:"hidden"});this._addClass(this.helper,this._helper);this.helper.css({width:this.element.outerWidth(),height:this.element.outerHeight(),position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++o.zIndex//TODO: Don't modify option
	});this.helper.appendTo("body").disableSelection();}else {this.helper=this.element;}},_change:{e:function(event,dx){return {width:this.originalSize.width+dx};},w:function(event,dx){var cs=this.originalSize,sp=this.originalPosition;return {left:sp.left+dx,width:cs.width-dx};},n:function(event,dx,dy){var cs=this.originalSize,sp=this.originalPosition;return {top:sp.top+dy,height:cs.height-dy};},s:function(event,dx,dy){return {height:this.originalSize.height+dy};},se:function(event,dx,dy){return $.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[event,dx,dy]));},sw:function(event,dx,dy){return $.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[event,dx,dy]));},ne:function(event,dx,dy){return $.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[event,dx,dy]));},nw:function(event,dx,dy){return $.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[event,dx,dy]));}},_propagate:function(n,event){$.ui.plugin.call(this,n,[event,this.ui()]);if(n!=="resize"){this._trigger(n,event,this.ui());}},plugins:{},ui:function(){return {originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition};}});/*
		 * Resizable Extensions
		 */$.ui.plugin.add("resizable","animate",{stop:function(event){var that=$(this).resizable("instance"),o=that.options,pr=that._proportionallyResizeElements,ista=pr.length&&/textarea/i.test(pr[0].nodeName),soffseth=ista&&that._hasScroll(pr[0],"left")?0:that.sizeDiff.height,soffsetw=ista?0:that.sizeDiff.width,style={width:that.size.width-soffsetw,height:that.size.height-soffseth},left=parseFloat(that.element.css("left"))+(that.position.left-that.originalPosition.left)||null,top=parseFloat(that.element.css("top"))+(that.position.top-that.originalPosition.top)||null;that.element.animate($.extend(style,top&&left?{top:top,left:left}:{}),{duration:o.animateDuration,easing:o.animateEasing,step:function(){var data={width:parseFloat(that.element.css("width")),height:parseFloat(that.element.css("height")),top:parseFloat(that.element.css("top")),left:parseFloat(that.element.css("left"))};if(pr&&pr.length){$(pr[0]).css({width:data.width,height:data.height});}// Propagating resize, and updating values for each animation step
	that._updateCache(data);that._propagate("resize",event);}});}});$.ui.plugin.add("resizable","containment",{start:function(){var element,p,co,ch,cw,width,height,that=$(this).resizable("instance"),o=that.options,el=that.element,oc=o.containment,ce=oc instanceof $?oc.get(0):/parent/.test(oc)?el.parent().get(0):oc;if(!ce){return;}that.containerElement=$(ce);if(/document/.test(oc)||oc===document){that.containerOffset={left:0,top:0};that.containerPosition={left:0,top:0};that.parentData={element:$(document),left:0,top:0,width:$(document).width(),height:$(document).height()||document.body.parentNode.scrollHeight};}else {element=$(ce);p=[];$(["Top","Right","Left","Bottom"]).each(function(i,name){p[i]=that._num(element.css("padding"+name));});that.containerOffset=element.offset();that.containerPosition=element.position();that.containerSize={height:element.innerHeight()-p[3],width:element.innerWidth()-p[1]};co=that.containerOffset;ch=that.containerSize.height;cw=that.containerSize.width;width=that._hasScroll(ce,"left")?ce.scrollWidth:cw;height=that._hasScroll(ce)?ce.scrollHeight:ch;that.parentData={element:ce,left:co.left,top:co.top,width:width,height:height};}},resize:function(event){var woset,hoset,isParent,isOffsetRelative,that=$(this).resizable("instance"),o=that.options,co=that.containerOffset,cp=that.position,pRatio=that._aspectRatio||event.shiftKey,cop={top:0,left:0},ce=that.containerElement,continueResize=true;if(ce[0]!==document&&/static/.test(ce.css("position"))){cop=co;}if(cp.left<(that._helper?co.left:0)){that.size.width=that.size.width+(that._helper?that.position.left-co.left:that.position.left-cop.left);if(pRatio){that.size.height=that.size.width/that.aspectRatio;continueResize=false;}that.position.left=o.helper?co.left:0;}if(cp.top<(that._helper?co.top:0)){that.size.height=that.size.height+(that._helper?that.position.top-co.top:that.position.top);if(pRatio){that.size.width=that.size.height*that.aspectRatio;continueResize=false;}that.position.top=that._helper?co.top:0;}isParent=that.containerElement.get(0)===that.element.parent().get(0);isOffsetRelative=/relative|absolute/.test(that.containerElement.css("position"));if(isParent&&isOffsetRelative){that.offset.left=that.parentData.left+that.position.left;that.offset.top=that.parentData.top+that.position.top;}else {that.offset.left=that.element.offset().left;that.offset.top=that.element.offset().top;}woset=Math.abs(that.sizeDiff.width+(that._helper?that.offset.left-cop.left:that.offset.left-co.left));hoset=Math.abs(that.sizeDiff.height+(that._helper?that.offset.top-cop.top:that.offset.top-co.top));if(woset+that.size.width>=that.parentData.width){that.size.width=that.parentData.width-woset;if(pRatio){that.size.height=that.size.width/that.aspectRatio;continueResize=false;}}if(hoset+that.size.height>=that.parentData.height){that.size.height=that.parentData.height-hoset;if(pRatio){that.size.width=that.size.height*that.aspectRatio;continueResize=false;}}if(!continueResize){that.position.left=that.prevPosition.left;that.position.top=that.prevPosition.top;that.size.width=that.prevSize.width;that.size.height=that.prevSize.height;}},stop:function(){var that=$(this).resizable("instance"),o=that.options,co=that.containerOffset,cop=that.containerPosition,ce=that.containerElement,helper=$(that.helper),ho=helper.offset(),w=helper.outerWidth()-that.sizeDiff.width,h=helper.outerHeight()-that.sizeDiff.height;if(that._helper&&!o.animate&&/relative/.test(ce.css("position"))){$(this).css({left:ho.left-cop.left-co.left,width:w,height:h});}if(that._helper&&!o.animate&&/static/.test(ce.css("position"))){$(this).css({left:ho.left-cop.left-co.left,width:w,height:h});}}});$.ui.plugin.add("resizable","alsoResize",{start:function(){var that=$(this).resizable("instance"),o=that.options;$(o.alsoResize).each(function(){var el=$(this),elSize=that._calculateAdjustedElementDimensions(el);el.data("ui-resizable-alsoresize",{width:elSize.width,height:elSize.height,left:parseFloat(el.css("left")),top:parseFloat(el.css("top"))});});},resize:function(event,ui){var that=$(this).resizable("instance"),o=that.options,os=that.originalSize,op=that.originalPosition,delta={height:that.size.height-os.height||0,width:that.size.width-os.width||0,top:that.position.top-op.top||0,left:that.position.left-op.left||0};$(o.alsoResize).each(function(){var el=$(this),start=$(this).data("ui-resizable-alsoresize"),style={},css=el.parents(ui.originalElement[0]).length?["width","height"]:["width","height","top","left"];$.each(css,function(i,prop){var sum=(start[prop]||0)+(delta[prop]||0);if(sum&&sum>=0){style[prop]=sum||null;}});el.css(style);});},stop:function(){$(this).removeData("ui-resizable-alsoresize");}});$.ui.plugin.add("resizable","ghost",{start:function(){var that=$(this).resizable("instance"),cs=that.size;that.ghost=that.originalElement.clone();that.ghost.css({opacity:0.25,display:"block",position:"relative",height:cs.height,width:cs.width,margin:0,left:0,top:0});that._addClass(that.ghost,"ui-resizable-ghost");// DEPRECATED
	// TODO: remove after 1.12
	if($.uiBackCompat===true&&typeof that.options.ghost==="string"){// Ghost option
	that.ghost.addClass(this.options.ghost);}that.ghost.appendTo(that.helper);},resize:function(){var that=$(this).resizable("instance");if(that.ghost){that.ghost.css({position:"relative",height:that.size.height,width:that.size.width});}},stop:function(){var that=$(this).resizable("instance");if(that.ghost&&that.helper){that.helper.get(0).removeChild(that.ghost.get(0));}}});$.ui.plugin.add("resizable","grid",{resize:function(){var outerDimensions,that=$(this).resizable("instance"),o=that.options,cs=that.size,os=that.originalSize,op=that.originalPosition,a=that.axis,grid=typeof o.grid==="number"?[o.grid,o.grid]:o.grid,gridX=grid[0]||1,gridY=grid[1]||1,ox=Math.round((cs.width-os.width)/gridX)*gridX,oy=Math.round((cs.height-os.height)/gridY)*gridY,newWidth=os.width+ox,newHeight=os.height+oy,isMaxWidth=o.maxWidth&&o.maxWidth<newWidth,isMaxHeight=o.maxHeight&&o.maxHeight<newHeight,isMinWidth=o.minWidth&&o.minWidth>newWidth,isMinHeight=o.minHeight&&o.minHeight>newHeight;o.grid=grid;if(isMinWidth){newWidth+=gridX;}if(isMinHeight){newHeight+=gridY;}if(isMaxWidth){newWidth-=gridX;}if(isMaxHeight){newHeight-=gridY;}if(/^(se|s|e)$/.test(a)){that.size.width=newWidth;that.size.height=newHeight;}else if(/^(ne)$/.test(a)){that.size.width=newWidth;that.size.height=newHeight;that.position.top=op.top-oy;}else if(/^(sw)$/.test(a)){that.size.width=newWidth;that.size.height=newHeight;that.position.left=op.left-ox;}else {if(newHeight-gridY<=0||newWidth-gridX<=0){outerDimensions=that._getPaddingPlusBorderDimensions(this);}if(newHeight-gridY>0){that.size.height=newHeight;that.position.top=op.top-oy;}else {newHeight=gridY-outerDimensions.height;that.size.height=newHeight;that.position.top=op.top+os.height-newHeight;}if(newWidth-gridX>0){that.size.width=newWidth;that.position.left=op.left-ox;}else {newWidth=gridX-outerDimensions.width;that.size.width=newWidth;that.position.left=op.left+os.width-newWidth;}}}});$.ui.resizable;/*!
		 * jQuery UI Dialog 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Dialog
	//>>group: Widgets
	//>>description: Displays customizable dialog windows.
	//>>docs: https://api.jqueryui.com/dialog/
	//>>demos: https://jqueryui.com/dialog/
	//>>css.structure: ../../themes/base/core.css
	//>>css.structure: ../../themes/base/dialog.css
	//>>css.theme: ../../themes/base/theme.css
	$.widget("ui.dialog",{version:"1.14.2",options:{appendTo:"body",autoOpen:true,buttons:[],classes:{"ui-dialog":"ui-corner-all","ui-dialog-titlebar":"ui-corner-all"},closeOnEscape:true,closeText:"Close",draggable:true,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:false,position:{my:"center",at:"center",of:window,collision:"fit",// Ensure the titlebar is always visible
	using:function(pos){var topOffset=$(this).css(pos).offset().top;if(topOffset<0){$(this).css("top",pos.top-topOffset);}}},resizable:true,show:null,title:null,uiDialogTitleHeadingLevel:0,width:300,// Callbacks
	beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},sizeRelatedOptions:{buttons:true,height:true,maxHeight:true,maxWidth:true,minHeight:true,minWidth:true,width:true},resizableRelatedOptions:{maxHeight:true,maxWidth:true,minHeight:true,minWidth:true},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height};this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)};this.originalTitle=this.element.attr("title");if(this.options.title==null&&this.originalTitle!=null){this.options.title=this.originalTitle;}// Dialogs can't be disabled
	if(this.options.disabled){this.options.disabled=false;}this._createWrapper();this.element.show().removeAttr("title").appendTo(this.uiDialog);this._addClass("ui-dialog-content","ui-widget-content");this._createTitlebar();this._createButtonPane();if(this.options.draggable&&$.fn.draggable){this._makeDraggable();}if(this.options.resizable&&$.fn.resizable){this._makeResizable();}this._isOpen=false;this._trackFocus();},_init:function(){if(this.options.autoOpen){this.open();}},_appendTo:function(){var element=this.options.appendTo;if(element&&(element.jquery||element.nodeType)){return $(element);}return this.document.find(element||"body").eq(0);},_destroy:function(){var next,originalPosition=this.originalPosition;this._untrackInstance();this._destroyOverlay();this.element.removeUniqueId().css(this.originalCss)// Without detaching first, the following becomes really slow
	.detach();this.uiDialog.remove();if(this.originalTitle){this.element.attr("title",this.originalTitle);}next=originalPosition.parent.children().eq(originalPosition.index);// Don't try to place the dialog next to itself (#8613)
	if(next.length&&next[0]!==this.element[0]){next.before(this.element);}else {originalPosition.parent.append(this.element);}},widget:function(){return this.uiDialog;},disable:$.noop,enable:$.noop,close:function(event){var that=this;if(!this._isOpen||this._trigger("beforeClose",event)===false){return;}this._isOpen=false;this._focusedElement=null;this._destroyOverlay();this._untrackInstance();if(!this.opener.filter(":focusable").trigger("focus").length){// Hiding a focused element doesn't trigger blur in WebKit
	// so in case we have nothing to focus on, explicitly blur the active element
	// https://bugs.webkit.org/show_bug.cgi?id=47182
	$(this.document[0].activeElement).trigger("blur");}this._hide(this.uiDialog,this.options.hide,function(){that._trigger("close",event);});},isOpen:function(){return this._isOpen;},moveToTop:function(){this._moveToTop();},_moveToTop:function(event,silent){var moved=false,zIndices=this.uiDialog.siblings(".ui-front:visible").map(function(){return +$(this).css("z-index");}).get(),zIndexMax=Math.max.apply(null,zIndices);if(zIndexMax>=+this.uiDialog.css("z-index")){this.uiDialog.css("z-index",zIndexMax+1);moved=true;}if(moved&&!silent){this._trigger("focus",event);}return moved;},open:function(){var that=this;if(this._isOpen){if(this._moveToTop()){this._focusTabbable();}return;}this._isOpen=true;this.opener=$(this.document[0].activeElement);this._size();this._position();this._createOverlay();this._moveToTop(null,true);// Ensure the overlay is moved to the top with the dialog, but only when
	// opening. The overlay shouldn't move after the dialog is open so that
	// modeless dialogs opened after the modal dialog stack properly.
	if(this.overlay){this.overlay.css("z-index",this.uiDialog.css("z-index")-1);}this._show(this.uiDialog,this.options.show,function(){that._focusTabbable();that._trigger("focus");});// Track the dialog immediately upon opening in case a focus event
	// somehow occurs outside of the dialog before an element inside the
	// dialog is focused (#10152)
	this._makeFocusTarget();this._trigger("open");},_focusTabbable:function(){// Set focus to the first match:
	// 1. An element that was focused previously
	// 2. First element inside the dialog matching [autofocus]
	// 3. Tabbable element inside the content element
	// 4. Tabbable element inside the buttonpane
	// 5. The close button
	// 6. The dialog itself
	var hasFocus=this._focusedElement;if(!hasFocus){hasFocus=this.element.find("[autofocus]");}if(!hasFocus.length){hasFocus=this.element.find(":tabbable");}if(!hasFocus.length){hasFocus=this.uiDialogButtonPane.find(":tabbable");}if(!hasFocus.length){hasFocus=this.uiDialogTitlebarClose.filter(":tabbable");}if(!hasFocus.length){hasFocus=this.uiDialog;}hasFocus.eq(0).trigger("focus");},_restoreTabbableFocus:function(){var activeElement=this.document[0].activeElement,isActive=this.uiDialog[0]===activeElement||$.contains(this.uiDialog[0],activeElement);if(!isActive){this._focusTabbable();}},_keepFocus:function(event){event.preventDefault();this._restoreTabbableFocus();},_createWrapper:function(){this.uiDialog=$("<div>").hide().attr({// Setting tabIndex makes the div focusable
	tabIndex:-1,role:"dialog","aria-modal":this.options.modal?"true":null}).appendTo(this._appendTo());this._addClass(this.uiDialog,"ui-dialog","ui-widget ui-widget-content ui-front");this._on(this.uiDialog,{keydown:function(event){if(this.options.closeOnEscape&&!event.isDefaultPrevented()&&event.keyCode&&event.keyCode===$.ui.keyCode.ESCAPE){event.preventDefault();this.close(event);return;}// Prevent tabbing out of dialogs
	if(event.keyCode!==$.ui.keyCode.TAB||event.isDefaultPrevented()){return;}var tabbables=this.uiDialog.find(":tabbable"),first=tabbables.first(),last=tabbables.last();if((event.target===last[0]||event.target===this.uiDialog[0])&&!event.shiftKey){this._delay(function(){first.trigger("focus");});event.preventDefault();}else if((event.target===first[0]||event.target===this.uiDialog[0])&&event.shiftKey){this._delay(function(){last.trigger("focus");});event.preventDefault();}},mousedown:function(event){if(this._moveToTop(event)){this._focusTabbable();}}});// We assume that any existing aria-describedby attribute means
	// that the dialog content is marked up properly
	// otherwise we brute force the content as the description
	if(!this.element.find("[aria-describedby]").length){this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")});}},_createTitlebar:function(){var uiDialogTitle;this.uiDialogTitlebar=$("<div>");this._addClass(this.uiDialogTitlebar,"ui-dialog-titlebar","ui-widget-header ui-helper-clearfix");this._on(this.uiDialogTitlebar,{mousedown:function(event){// Don't prevent click on close button (#8838)
	// Focusing a dialog that is partially scrolled out of view
	// causes the browser to scroll it into view, preventing the click event
	if(!$(event.target).closest(".ui-dialog-titlebar-close")){// Dialog isn't getting focus when dragging (#8063)
	this.uiDialog.trigger("focus");}}});this.uiDialogTitlebarClose=$("<button type='button'></button>").button({label:$("<a>").text(this.options.closeText).html(),icon:"ui-icon-closethick",showLabel:false}).appendTo(this.uiDialogTitlebar);this._addClass(this.uiDialogTitlebarClose,"ui-dialog-titlebar-close");this._on(this.uiDialogTitlebarClose,{click:function(event){event.preventDefault();this.close(event);}});var uiDialogHeadingLevel=Number.isInteger(this.options.uiDialogTitleHeadingLevel)&&this.options.uiDialogTitleHeadingLevel>0&&this.options.uiDialogTitleHeadingLevel<=6?"h"+this.options.uiDialogTitleHeadingLevel:"span";uiDialogTitle=$("<"+uiDialogHeadingLevel+">").uniqueId().prependTo(this.uiDialogTitlebar);this._addClass(uiDialogTitle,"ui-dialog-title");this._title(uiDialogTitle);this.uiDialogTitlebar.prependTo(this.uiDialog);this.uiDialog.attr({"aria-labelledby":uiDialogTitle.attr("id")});},_title:function(title){if(this.options.title){title.text(this.options.title);}else {title.html("&#160;");}},_createButtonPane:function(){this.uiDialogButtonPane=$("<div>");this._addClass(this.uiDialogButtonPane,"ui-dialog-buttonpane","ui-widget-content ui-helper-clearfix");this.uiButtonSet=$("<div>").appendTo(this.uiDialogButtonPane);this._addClass(this.uiButtonSet,"ui-dialog-buttonset");this._createButtons();},_createButtons:function(){var that=this,buttons=this.options.buttons;// If we already have a button pane, remove it
	this.uiDialogButtonPane.remove();this.uiButtonSet.empty();if($.isEmptyObject(buttons)||Array.isArray(buttons)&&!buttons.length){this._removeClass(this.uiDialog,"ui-dialog-buttons");return;}$.each(buttons,function(name,props){var click,buttonOptions;props=typeof props==="function"?{click:props,text:name}:props;// Default to a non-submitting button
	props=$.extend({type:"button"},props);// Change the context for the click callback to be the main element
	click=props.click;buttonOptions={icon:props.icon,iconPosition:props.iconPosition,showLabel:props.showLabel,// Deprecated options
	icons:props.icons,text:props.text};delete props.click;delete props.icon;delete props.iconPosition;delete props.showLabel;// Deprecated options
	delete props.icons;if(typeof props.text==="boolean"){delete props.text;}$("<button></button>",props).button(buttonOptions).appendTo(that.uiButtonSet).on("click",function(){click.apply(that.element[0],arguments);});});this._addClass(this.uiDialog,"ui-dialog-buttons");this.uiDialogButtonPane.appendTo(this.uiDialog);},_makeDraggable:function(){var that=this,options=this.options;function filteredUi(ui){return {position:ui.position,offset:ui.offset};}this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(event,ui){that._addClass($(this),"ui-dialog-dragging");that._blockFrames();that._trigger("dragStart",event,filteredUi(ui));},drag:function(event,ui){that._trigger("drag",event,filteredUi(ui));},stop:function(event,ui){var left=ui.offset.left-that.document.scrollLeft(),top=ui.offset.top-that.document.scrollTop();options.position={my:"left top",at:"left"+(left>=0?"+":"")+left+" "+"top"+(top>=0?"+":"")+top,of:that.window};that._removeClass($(this),"ui-dialog-dragging");that._unblockFrames();that._trigger("dragStop",event,filteredUi(ui));}});},_makeResizable:function(){var that=this,options=this.options,handles=options.resizable,// .ui-resizable has position: relative defined in the stylesheet
	// but dialogs have to use absolute or fixed positioning
	position=this.uiDialog.css("position"),resizeHandles=typeof handles==="string"?handles:"n,e,s,w,se,sw,ne,nw";function filteredUi(ui){return {originalPosition:ui.originalPosition,originalSize:ui.originalSize,position:ui.position,size:ui.size};}this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:options.maxWidth,maxHeight:options.maxHeight,minWidth:options.minWidth,minHeight:this._minHeight(),handles:resizeHandles,start:function(event,ui){that._addClass($(this),"ui-dialog-resizing");that._blockFrames();that._trigger("resizeStart",event,filteredUi(ui));},resize:function(event,ui){that._trigger("resize",event,filteredUi(ui));},stop:function(event,ui){var offset=that.uiDialog.offset(),left=offset.left-that.document.scrollLeft(),top=offset.top-that.document.scrollTop();options.height=that.uiDialog.height();options.width=that.uiDialog.width();options.position={my:"left top",at:"left"+(left>=0?"+":"")+left+" "+"top"+(top>=0?"+":"")+top,of:that.window};that._removeClass($(this),"ui-dialog-resizing");that._unblockFrames();that._trigger("resizeStop",event,filteredUi(ui));}}).css("position",position);},_trackFocus:function(){this._on(this.widget(),{focusin:function(event){this._makeFocusTarget();this._focusedElement=$(event.target);}});},_makeFocusTarget:function(){this._untrackInstance();this._trackingInstances().unshift(this);},_untrackInstance:function(){var instances=this._trackingInstances(),exists=$.inArray(this,instances);if(exists!==-1){instances.splice(exists,1);}},_trackingInstances:function(){var instances=this.document.data("ui-dialog-instances");if(!instances){instances=[];this.document.data("ui-dialog-instances",instances);}return instances;},_minHeight:function(){var options=this.options;return options.height==="auto"?options.minHeight:Math.min(options.minHeight,options.height);},_position:function(){// Need to show the dialog to get the actual offset in the position plugin
	var isVisible=this.uiDialog.is(":visible");if(!isVisible){this.uiDialog.show();}this.uiDialog.position(this.options.position);if(!isVisible){this.uiDialog.hide();}},_setOptions:function(options){var that=this,resize=false,resizableOptions={};$.each(options,function(key,value){that._setOption(key,value);if(key in that.sizeRelatedOptions){resize=true;}if(key in that.resizableRelatedOptions){resizableOptions[key]=value;}});if(resize){this._size();this._position();}if(this.uiDialog.is(":data(ui-resizable)")){this.uiDialog.resizable("option",resizableOptions);}},_setOption:function(key,value){var isDraggable,isResizable,uiDialog=this.uiDialog;if(key==="disabled"){return;}this._super(key,value);if(key==="appendTo"){this.uiDialog.appendTo(this._appendTo());}if(key==="buttons"){this._createButtons();}if(key==="closeText"){this.uiDialogTitlebarClose.button({// Ensure that we always pass a string
	label:$("<a>").text(""+this.options.closeText).html()});}if(key==="draggable"){isDraggable=uiDialog.is(":data(ui-draggable)");if(isDraggable&&!value){uiDialog.draggable("destroy");}if(!isDraggable&&value){this._makeDraggable();}}if(key==="position"){this._position();}if(key==="resizable"){// currently resizable, becoming non-resizable
	isResizable=uiDialog.is(":data(ui-resizable)");if(isResizable&&!value){uiDialog.resizable("destroy");}// Currently resizable, changing handles
	if(isResizable&&typeof value==="string"){uiDialog.resizable("option","handles",value);}// Currently non-resizable, becoming resizable
	if(!isResizable&&value!==false){this._makeResizable();}}if(key==="title"){this._title(this.uiDialogTitlebar.find(".ui-dialog-title"));}if(key==="modal"){uiDialog.attr("aria-modal",value?"true":null);}},_size:function(){// If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
	// divs will both have width and height set, so we need to reset them
	var nonContentHeight,minContentHeight,maxContentHeight,options=this.options;// Reset content sizing
	this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0});if(options.minWidth>options.width){options.width=options.minWidth;}// Reset wrapper sizing
	// determine the height of all the non-content elements
	nonContentHeight=this.uiDialog.css({height:"auto",width:options.width}).outerHeight();minContentHeight=Math.max(0,options.minHeight-nonContentHeight);maxContentHeight=typeof options.maxHeight==="number"?Math.max(0,options.maxHeight-nonContentHeight):"none";if(options.height==="auto"){this.element.css({minHeight:minContentHeight,maxHeight:maxContentHeight,height:"auto"});}else {this.element.height(Math.max(0,options.height-nonContentHeight));}if(this.uiDialog.is(":data(ui-resizable)")){this.uiDialog.resizable("option","minHeight",this._minHeight());}},_blockFrames:function(){this.iframeBlocks=this.document.find("iframe").map(function(){var iframe=$(this);return $("<div>").css({position:"absolute",width:iframe.outerWidth(),height:iframe.outerHeight()}).appendTo(iframe.parent()).offset(iframe.offset())[0];});},_unblockFrames:function(){if(this.iframeBlocks){this.iframeBlocks.remove();delete this.iframeBlocks;}},_allowInteraction:function(event){if($(event.target).closest(".ui-dialog").length){return true;}// TODO: Remove hack when datepicker implements
	// the .ui-front logic (#8989)
	return !!$(event.target).closest(".ui-datepicker").length;},_createOverlay:function(){if(!this.options.modal){return;}// We use a delay in case the overlay is created from an
	// event that we're going to be cancelling (#2804)
	var isOpening=true;this._delay(function(){isOpening=false;});if(!this.document.data("ui-dialog-overlays")){// Prevent use of anchors and inputs
	// This doesn't use `_on()` because it is a shared event handler
	// across all open modal dialogs.
	this.document.on("focusin.ui-dialog",function(event){if(isOpening){return;}var instance=this._trackingInstances()[0];if(!instance._allowInteraction(event)){event.preventDefault();instance._focusTabbable();}}.bind(this));}this.overlay=$("<div>").appendTo(this._appendTo());this._addClass(this.overlay,null,"ui-widget-overlay ui-front");this._on(this.overlay,{mousedown:"_keepFocus"});this.document.data("ui-dialog-overlays",(this.document.data("ui-dialog-overlays")||0)+1);},_destroyOverlay:function(){if(!this.options.modal){return;}if(this.overlay){var overlays=this.document.data("ui-dialog-overlays")-1;if(!overlays){this.document.off("focusin.ui-dialog");this.document.removeData("ui-dialog-overlays");}else {this.document.data("ui-dialog-overlays",overlays);}this.overlay.remove();this.overlay=null;}}});// DEPRECATED
	// TODO: switch return back to widget declaration at top of file when this is removed
	if($.uiBackCompat===true){// Backcompat for dialogClass option
	$.widget("ui.dialog",$.ui.dialog,{options:{dialogClass:""},_createWrapper:function(){this._super();this.uiDialog.addClass(this.options.dialogClass);},_setOption:function(key,value){if(key==="dialogClass"){this.uiDialog.removeClass(this.options.dialogClass).addClass(value);}this._superApply(arguments);}});}$.ui.dialog;/*!
		 * jQuery UI Droppable 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Droppable
	//>>group: Interactions
	//>>description: Enables drop targets for draggable elements.
	//>>docs: https://api.jqueryui.com/droppable/
	//>>demos: https://jqueryui.com/droppable/
	$.widget("ui.droppable",{version:"1.14.2",widgetEventPrefix:"drop",options:{accept:"*",addClasses:true,greedy:false,scope:"default",tolerance:"intersect",// Callbacks
	activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var proportions,o=this.options,accept=o.accept;this.isover=false;this.isout=true;this.accept=typeof accept==="function"?accept:function(d){return d.is(accept);};this.proportions=function/* valueToWrite */(){if(arguments.length){// Store the droppable's proportions
	proportions=arguments[0];}else {// Retrieve or derive the droppable's proportions
	return proportions?proportions:proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight};}};this._addToManager(o.scope);if(o.addClasses){this._addClass("ui-droppable");}},_addToManager:function(scope){// Add the reference and positions to the manager
	$.ui.ddmanager.droppables[scope]=$.ui.ddmanager.droppables[scope]||[];$.ui.ddmanager.droppables[scope].push(this);},_splice:function(drop){var i=0;for(;i<drop.length;i++){if(drop[i]===this){drop.splice(i,1);}}},_destroy:function(){var drop=$.ui.ddmanager.droppables[this.options.scope];this._splice(drop);},_setOption:function(key,value){if(key==="accept"){this.accept=typeof value==="function"?value:function(d){return d.is(value);};}else if(key==="scope"){var drop=$.ui.ddmanager.droppables[this.options.scope];this._splice(drop);this._addToManager(value);}this._super(key,value);},_activate:function(event){var draggable=$.ui.ddmanager.current;this._addActiveClass();if(draggable){this._trigger("activate",event,this.ui(draggable));}},_deactivate:function(event){var draggable=$.ui.ddmanager.current;this._removeActiveClass();if(draggable){this._trigger("deactivate",event,this.ui(draggable));}},_over:function(event){var draggable=$.ui.ddmanager.current;// Bail if draggable and droppable are same element
	if(!draggable||(draggable.currentItem||draggable.element)[0]===this.element[0]){return;}if(this.accept.call(this.element[0],draggable.currentItem||draggable.element)){this._addHoverClass();this._trigger("over",event,this.ui(draggable));}},_out:function(event){var draggable=$.ui.ddmanager.current;// Bail if draggable and droppable are same element
	if(!draggable||(draggable.currentItem||draggable.element)[0]===this.element[0]){return;}if(this.accept.call(this.element[0],draggable.currentItem||draggable.element)){this._removeHoverClass();this._trigger("out",event,this.ui(draggable));}},_drop:function(event,custom){var draggable=custom||$.ui.ddmanager.current,childrenIntersection=false;// Bail if draggable and droppable are same element
	if(!draggable||(draggable.currentItem||draggable.element)[0]===this.element[0]){return false;}this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var inst=$(this).droppable("instance");if(inst.options.greedy&&!inst.options.disabled&&inst.options.scope===draggable.options.scope&&inst.accept.call(inst.element[0],draggable.currentItem||draggable.element)&&$.ui.intersect(draggable,$.extend(inst,{offset:inst.element.offset()}),inst.options.tolerance,event)){childrenIntersection=true;return false;}});if(childrenIntersection){return false;}if(this.accept.call(this.element[0],draggable.currentItem||draggable.element)){this._removeActiveClass();this._removeHoverClass();this._trigger("drop",event,this.ui(draggable));return this.element;}return false;},ui:function(c){return {draggable:c.currentItem||c.element,helper:c.helper,position:c.position,offset:c.positionAbs};},// Extension points just to make backcompat sane and avoid duplicating logic
	// TODO: Remove in 1.14 along with call to it below
	_addHoverClass:function(){this._addClass("ui-droppable-hover");},_removeHoverClass:function(){this._removeClass("ui-droppable-hover");},_addActiveClass:function(){this._addClass("ui-droppable-active");},_removeActiveClass:function(){this._removeClass("ui-droppable-active");}});$.ui.intersect=function(){function isOverAxis(x,reference,size){return x>=reference&&x<reference+size;}return function(draggable,droppable,toleranceMode,event){if(!droppable.offset){return false;}var x1=(draggable.positionAbs||draggable.position.absolute).left+draggable.margins.left,y1=(draggable.positionAbs||draggable.position.absolute).top+draggable.margins.top,x2=x1+draggable.helperProportions.width,y2=y1+draggable.helperProportions.height,l=droppable.offset.left,t=droppable.offset.top,r=l+droppable.proportions().width,b=t+droppable.proportions().height;switch(toleranceMode){case "fit":return l<=x1&&x2<=r&&t<=y1&&y2<=b;case "intersect":return l<x1+draggable.helperProportions.width/2&&// Right Half
	x2-draggable.helperProportions.width/2<r&&// Left Half
	t<y1+draggable.helperProportions.height/2&&// Bottom Half
	y2-draggable.helperProportions.height/2<b;// Top Half
	case "pointer":return isOverAxis(event.pageY,t,droppable.proportions().height)&&isOverAxis(event.pageX,l,droppable.proportions().width);case "touch":return (y1>=t&&y1<=b||// Top edge touching
	y2>=t&&y2<=b||// Bottom edge touching
	y1<t&&y2>b// Surrounded vertically
	)&&(x1>=l&&x1<=r||// Left edge touching
	x2>=l&&x2<=r||// Right edge touching
	x1<l&&x2>r// Surrounded horizontally
	);default:return false;}};}();/*
			This manager tracks offsets of draggables and droppables
		*/$.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(t,event){var i,j,m=$.ui.ddmanager.droppables[t.options.scope]||[],type=event?event.type:null,// workaround for #2317
	list=(t.currentItem||t.element).find(":data(ui-droppable)").addBack();droppablesLoop:for(i=0;i<m.length;i++){// No disabled and non-accepted
	if(m[i].options.disabled||t&&!m[i].accept.call(m[i].element[0],t.currentItem||t.element)){continue;}// Filter out elements in the current dragged item
	for(j=0;j<list.length;j++){if(list[j]===m[i].element[0]){m[i].proportions().height=0;continue droppablesLoop;}}m[i].visible=m[i].element.css("display")!=="none";if(!m[i].visible){continue;}// Activate the droppable if used directly from draggables
	if(type==="mousedown"){m[i]._activate.call(m[i],event);}m[i].offset=m[i].element.offset();m[i].proportions({width:m[i].element[0].offsetWidth,height:m[i].element[0].offsetHeight});}},drop:function(draggable,event){var dropped=false;// Create a copy of the droppables in case the list changes during the drop (#9116)
	$.each(($.ui.ddmanager.droppables[draggable.options.scope]||[]).slice(),function(){if(!this.options){return;}if(!this.options.disabled&&this.visible&&$.ui.intersect(draggable,this,this.options.tolerance,event)){dropped=this._drop.call(this,event)||dropped;}if(!this.options.disabled&&this.visible&&this.accept.call(this.element[0],draggable.currentItem||draggable.element)){this.isout=true;this.isover=false;this._deactivate.call(this,event);}});return dropped;},dragStart:function(draggable,event){// Listen for scrolling so that if the dragging causes scrolling the position of the
	// droppables can be recalculated (see #5003)
	draggable.element.parentsUntil("body").on("scroll.droppable",function(){if(!draggable.options.refreshPositions){$.ui.ddmanager.prepareOffsets(draggable,event);}});},drag:function(draggable,event){// If you have a highly dynamic page, you might try this option. It renders positions
	// every time you move the mouse.
	if(draggable.options.refreshPositions){$.ui.ddmanager.prepareOffsets(draggable,event);}// Run through all droppables and check their positions based on specific tolerance options
	$.each($.ui.ddmanager.droppables[draggable.options.scope]||[],function(){if(this.options.disabled||this.greedyChild||!this.visible){return;}var parentInstance,scope,parent,intersects=$.ui.intersect(draggable,this,this.options.tolerance,event),c=!intersects&&this.isover?"isout":intersects&&!this.isover?"isover":null;if(!c){return;}if(this.options.greedy){// find droppable parents with same scope
	scope=this.options.scope;parent=this.element.parents(":data(ui-droppable)").filter(function(){return $(this).droppable("instance").options.scope===scope;});if(parent.length){parentInstance=$(parent[0]).droppable("instance");parentInstance.greedyChild=c==="isover";}}// We just moved into a greedy child
	if(parentInstance&&c==="isover"){parentInstance.isover=false;parentInstance.isout=true;parentInstance._out.call(parentInstance,event);}this[c]=true;this[c==="isout"?"isover":"isout"]=false;this[c==="isover"?"_over":"_out"].call(this,event);// We just moved out of a greedy child
	if(parentInstance&&c==="isout"){parentInstance.isout=false;parentInstance.isover=true;parentInstance._over.call(parentInstance,event);}});},dragStop:function(draggable,event){draggable.element.parentsUntil("body").off("scroll.droppable");// Call prepareOffsets one final time since IE does not fire return scroll events when
	// overflow was caused by drag (see #5003)
	if(!draggable.options.refreshPositions){$.ui.ddmanager.prepareOffsets(draggable,event);}}};// DEPRECATED
	// TODO: switch return back to widget declaration at top of file when this is removed
	if($.uiBackCompat===true){// Backcompat for activeClass and hoverClass options
	$.widget("ui.droppable",$.ui.droppable,{options:{hoverClass:false,activeClass:false},_addActiveClass:function(){this._super();if(this.options.activeClass){this.element.addClass(this.options.activeClass);}},_removeActiveClass:function(){this._super();if(this.options.activeClass){this.element.removeClass(this.options.activeClass);}},_addHoverClass:function(){this._super();if(this.options.hoverClass){this.element.addClass(this.options.hoverClass);}},_removeHoverClass:function(){this._super();if(this.options.hoverClass){this.element.removeClass(this.options.hoverClass);}}});}$.ui.droppable;/*!
		 * jQuery UI Progressbar 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Progressbar
	//>>group: Widgets
	//>>description: Displays a status indicator for loading state, standard percentage, and other progress indicators.
	//>>docs: https://api.jqueryui.com/progressbar/
	//>>demos: https://jqueryui.com/progressbar/
	//>>css.structure: ../../themes/base/core.css
	//>>css.structure: ../../themes/base/progressbar.css
	//>>css.theme: ../../themes/base/theme.css
	$.widget("ui.progressbar",{version:"1.14.2",options:{classes:{"ui-progressbar":"ui-corner-all","ui-progressbar-value":"ui-corner-left","ui-progressbar-complete":"ui-corner-right"},max:100,value:0,change:null,complete:null},min:0,_create:function(){// Constrain initial value
	this.oldValue=this.options.value=this._constrainedValue();this.element.attr({// Only set static values; aria-valuenow and aria-valuemax are
	// set inside _refreshValue()
	role:"progressbar","aria-valuemin":this.min});this._addClass("ui-progressbar","ui-widget ui-widget-content");this.valueDiv=$("<div>").appendTo(this.element);this._addClass(this.valueDiv,"ui-progressbar-value","ui-widget-header");this._refreshValue();},_destroy:function(){this.element.removeAttr("role aria-valuemin aria-valuemax aria-valuenow");this.valueDiv.remove();},value:function(newValue){if(newValue===undefined){return this.options.value;}this.options.value=this._constrainedValue(newValue);this._refreshValue();},_constrainedValue:function(newValue){if(newValue===undefined){newValue=this.options.value;}this.indeterminate=newValue===false;// Sanitize value
	if(typeof newValue!=="number"){newValue=0;}return this.indeterminate?false:Math.min(this.options.max,Math.max(this.min,newValue));},_setOptions:function(options){// Ensure "value" option is set after other values (like max)
	var value=options.value;delete options.value;this._super(options);this.options.value=this._constrainedValue(value);this._refreshValue();},_setOption:function(key,value){if(key==="max"){// Don't allow a max less than min
	value=Math.max(this.min,value);}this._super(key,value);},_setOptionDisabled:function(value){this._super(value);this.element.attr("aria-disabled",value);this._toggleClass(null,"ui-state-disabled",!!value);},_percentage:function(){return this.indeterminate?100:100*(this.options.value-this.min)/(this.options.max-this.min);},_refreshValue:function(){var value=this.options.value,percentage=this._percentage();this.valueDiv.toggle(this.indeterminate||value>this.min).width(percentage.toFixed(0)+"%");this._toggleClass(this.valueDiv,"ui-progressbar-complete",null,value===this.options.max)._toggleClass("ui-progressbar-indeterminate",null,this.indeterminate);if(this.indeterminate){this.element.removeAttr("aria-valuenow");if(!this.overlayDiv){this.overlayDiv=$("<div>").appendTo(this.valueDiv);this._addClass(this.overlayDiv,"ui-progressbar-overlay");}}else {this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":value});if(this.overlayDiv){this.overlayDiv.remove();this.overlayDiv=null;}}if(this.oldValue!==value){this.oldValue=value;this._trigger("change");}if(value===this.options.max){this._trigger("complete");}}});/*!
		 * jQuery UI Selectable 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Selectable
	//>>group: Interactions
	//>>description: Allows groups of elements to be selected with the mouse.
	//>>docs: https://api.jqueryui.com/selectable/
	//>>demos: https://jqueryui.com/selectable/
	//>>css.structure: ../../themes/base/selectable.css
	$.widget("ui.selectable",$.ui.mouse,{version:"1.14.2",options:{appendTo:"body",autoRefresh:true,distance:0,filter:"*",tolerance:"touch",// Callbacks
	selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var that=this;this._addClass("ui-selectable");this.dragged=false;// Cache selectee children based on filter
	this.refresh=function(){that.elementPos=$(that.element[0]).offset();that.selectees=$(that.options.filter,that.element[0]);that._addClass(that.selectees,"ui-selectee");that.selectees.each(function(){var $this=$(this),selecteeOffset=$this.offset(),pos={left:selecteeOffset.left-that.elementPos.left,top:selecteeOffset.top-that.elementPos.top};$.data(this,"selectable-item",{element:this,$element:$this,left:pos.left,top:pos.top,right:pos.left+$this.outerWidth(),bottom:pos.top+$this.outerHeight(),startselected:false,selected:$this.hasClass("ui-selected"),selecting:$this.hasClass("ui-selecting"),unselecting:$this.hasClass("ui-unselecting")});});};this.refresh();this._mouseInit();this.helper=$("<div>");this._addClass(this.helper,"ui-selectable-helper");},_destroy:function(){this.selectees.removeData("selectable-item");this._mouseDestroy();},_mouseStart:function(event){var that=this,options=this.options;this.opos=[event.pageX,event.pageY];this.elementPos=$(this.element[0]).offset();if(this.options.disabled){return;}this.selectees=$(options.filter,this.element[0]);this._trigger("start",event);$(options.appendTo).append(this.helper);// position helper (lasso)
	this.helper.css({"left":event.pageX,"top":event.pageY,"width":0,"height":0});if(options.autoRefresh){this.refresh();}this.selectees.filter(".ui-selected").each(function(){var selectee=$.data(this,"selectable-item");selectee.startselected=true;if(!event.metaKey&&!event.ctrlKey){that._removeClass(selectee.$element,"ui-selected");selectee.selected=false;that._addClass(selectee.$element,"ui-unselecting");selectee.unselecting=true;// selectable UNSELECTING callback
	that._trigger("unselecting",event,{unselecting:selectee.element});}});$(event.target).parents().addBack().each(function(){var doSelect,selectee=$.data(this,"selectable-item");if(selectee){doSelect=!event.metaKey&&!event.ctrlKey||!selectee.$element.hasClass("ui-selected");that._removeClass(selectee.$element,doSelect?"ui-unselecting":"ui-selected")._addClass(selectee.$element,doSelect?"ui-selecting":"ui-unselecting");selectee.unselecting=!doSelect;selectee.selecting=doSelect;selectee.selected=doSelect;// selectable (UN)SELECTING callback
	if(doSelect){that._trigger("selecting",event,{selecting:selectee.element});}else {that._trigger("unselecting",event,{unselecting:selectee.element});}return false;}});},_mouseDrag:function(event){this.dragged=true;if(this.options.disabled){return;}var tmp,that=this,options=this.options,x1=this.opos[0],y1=this.opos[1],x2=event.pageX,y2=event.pageY;if(x1>x2){tmp=x2;x2=x1;x1=tmp;}if(y1>y2){tmp=y2;y2=y1;y1=tmp;}this.helper.css({left:x1,top:y1,width:x2-x1,height:y2-y1});this.selectees.each(function(){var selectee=$.data(this,"selectable-item"),hit=false,offset={};//prevent helper from being selected if appendTo: selectable
	if(!selectee||selectee.element===that.element[0]){return;}offset.left=selectee.left+that.elementPos.left;offset.right=selectee.right+that.elementPos.left;offset.top=selectee.top+that.elementPos.top;offset.bottom=selectee.bottom+that.elementPos.top;if(options.tolerance==="touch"){hit=!(offset.left>x2||offset.right<x1||offset.top>y2||offset.bottom<y1);}else if(options.tolerance==="fit"){hit=offset.left>x1&&offset.right<x2&&offset.top>y1&&offset.bottom<y2;}if(hit){// SELECT
	if(selectee.selected){that._removeClass(selectee.$element,"ui-selected");selectee.selected=false;}if(selectee.unselecting){that._removeClass(selectee.$element,"ui-unselecting");selectee.unselecting=false;}if(!selectee.selecting){that._addClass(selectee.$element,"ui-selecting");selectee.selecting=true;// selectable SELECTING callback
	that._trigger("selecting",event,{selecting:selectee.element});}}else {// UNSELECT
	if(selectee.selecting){if((event.metaKey||event.ctrlKey)&&selectee.startselected){that._removeClass(selectee.$element,"ui-selecting");selectee.selecting=false;that._addClass(selectee.$element,"ui-selected");selectee.selected=true;}else {that._removeClass(selectee.$element,"ui-selecting");selectee.selecting=false;if(selectee.startselected){that._addClass(selectee.$element,"ui-unselecting");selectee.unselecting=true;}// selectable UNSELECTING callback
	that._trigger("unselecting",event,{unselecting:selectee.element});}}if(selectee.selected){if(!event.metaKey&&!event.ctrlKey&&!selectee.startselected){that._removeClass(selectee.$element,"ui-selected");selectee.selected=false;that._addClass(selectee.$element,"ui-unselecting");selectee.unselecting=true;// selectable UNSELECTING callback
	that._trigger("unselecting",event,{unselecting:selectee.element});}}}});return false;},_mouseStop:function(event){var that=this;this.dragged=false;$(".ui-unselecting",this.element[0]).each(function(){var selectee=$.data(this,"selectable-item");that._removeClass(selectee.$element,"ui-unselecting");selectee.unselecting=false;selectee.startselected=false;that._trigger("unselected",event,{unselected:selectee.element});});$(".ui-selecting",this.element[0]).each(function(){var selectee=$.data(this,"selectable-item");that._removeClass(selectee.$element,"ui-selecting")._addClass(selectee.$element,"ui-selected");selectee.selecting=false;selectee.selected=true;selectee.startselected=true;that._trigger("selected",event,{selected:selectee.element});});this._trigger("stop",event);this.helper.remove();return false;}});/*!
		 * jQuery UI Selectmenu 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Selectmenu
	//>>group: Widgets
	//>>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.
	//>>docs: https://api.jqueryui.com/selectmenu/
	//>>demos: https://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
	$.widget("ui.selectmenu",[$.ui.formResetMixin,{version:"1.14.2",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.trigger("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();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");}if(item.hidden){li.prop("hidden",true);}else {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;}selection=window.getSelection();selection.removeAllRanges();selection.addRange(this.range);},_documentClick:{mousedown:function(event){if(!this.isOpen){return;}if(!$(event.target).closest(".ui-selectmenu-menu, #"+CSS.escape(this.ids.button)).length){this.close(event);}}},_buttonEvents:{// Prevent text selection from being reset when interacting with the selectmenu (#10144)
	mousedown:function(){var selection=window.getSelection();if(selection.rangeCount){this.range=selection.getRangeAt(0);}},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(),this.menu.width("").outerWidth()));},_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(),hidden:optgroup.prop("hidden")||option.prop("hidden"),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.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Slider
	//>>group: Widgets
	//>>description: Displays a flexible slider with ranges and accessibility via keyboard.
	//>>docs: https://api.jqueryui.com/slider/
	//>>demos: https://jqueryui.com/slider/
	//>>css.structure: ../../themes/base/core.css
	//>>css.structure: ../../themes/base/slider.css
	//>>css.theme: ../../themes/base/theme.css
	$.widget("ui.slider",$.ui.mouse,{version:"1.14.2",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(Array.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(Array.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(Array.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 Sortable 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Sortable
	//>>group: Interactions
	//>>description: Enables items in a list to be sorted using the mouse.
	//>>docs: https://api.jqueryui.com/sortable/
	//>>demos: https://jqueryui.com/sortable/
	//>>css.structure: ../../themes/base/sortable.css
	$.widget("ui.sortable",$.ui.mouse,{version:"1.14.2",widgetEventPrefix:"sort",ready:false,options:{appendTo:"parent",axis:false,connectWith:false,containment:false,cursor:"auto",cursorAt:false,dropOnEmpty:true,forcePlaceholderSize:false,forceHelperSize:false,grid:false,handle:false,helper:"original",items:"> *",opacity:false,placeholder:false,revert:false,scroll:true,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1000,// Callbacks
	activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_isOverAxis:function(x,reference,size){return x>=reference&&x<reference+size;},_isFloating:function(item){return /left|right/.test(item.css("float"))||/inline|table-cell/.test(item.css("display"));},_create:function(){this.containerCache={};this._addClass("ui-sortable");//Get the items
	this.refresh();//Let's determine the parent's offset
	this.offset=this.element.offset();//Initialize mouse events for interaction
	this._mouseInit();this._setHandleClassName();//We're ready to go
	this.ready=true;},_setOption:function(key,value){this._super(key,value);if(key==="handle"){this._setHandleClassName();}},_setHandleClassName:function(){var that=this;this._removeClass(this.element.find(".ui-sortable-handle"),"ui-sortable-handle");$.each(this.items,function(){that._addClass(this.instance.options.handle?this.item.find(this.instance.options.handle):this.item,"ui-sortable-handle");});},_destroy:function(){this._mouseDestroy();for(var i=this.items.length-1;i>=0;i--){this.items[i].item.removeData(this.widgetName+"-item");}return this;},_mouseCapture:function(event,overrideHandle){var currentItem=null,validHandle=false,that=this;if(this.reverting){return false;}if(this.options.disabled||this.options.type==="static"){return false;}//We have to refresh the items data once first
	this._refreshItems(event);//Find out if the clicked node (or one of its parents) is a actual item in this.items
	$(event.target).parents().each(function(){if($.data(this,that.widgetName+"-item")===that){currentItem=$(this);return false;}});if($.data(event.target,that.widgetName+"-item")===that){currentItem=$(event.target);}if(!currentItem){return false;}if(this.options.handle&&!overrideHandle){$(this.options.handle,currentItem).find("*").addBack().each(function(){if(this===event.target){validHandle=true;}});if(!validHandle){return false;}}this.currentItem=currentItem;this._removeCurrentsFromItems();return true;},_mouseStart:function(event,overrideHandle,noActivation){var i,body,o=this.options;this.currentContainer=this;//We only need to call refreshPositions, because the refreshItems call has been moved to
	// mouseCapture
	this.refreshPositions();//Prepare the dragged items parent
	this.appendTo=$(o.appendTo!=="parent"?o.appendTo:this.currentItem.parent());//Create and append the visible helper
	this.helper=this._createHelper(event);//Cache the helper size
	this._cacheHelperProportions();/*
				 * - Position generation -
				 * This block generates everything position related - it's the core of draggables.
				 *///Cache the margins of the original element
	this._cacheMargins();//The element's absolute position on the page minus margins
	this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};$.extend(this.offset,{click:{//Where the click happened, relative to the element
	left:event.pageX-this.offset.left,top:event.pageY-this.offset.top},// This is a relative to absolute position minus the actual position calculation -
	// only used for relative positioned helper
	relative:this._getRelativeOffset()});// After we get the helper offset, but before we get the parent offset we can
	// change the helper's position to absolute
	// TODO: Still need to figure out a way to make relative sorting possible
	this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
	if(o.cursorAt){this._adjustOffsetFromHelper(o.cursorAt);}//Cache the former DOM position
	this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};// If the helper is not the original, hide the original so it's not playing any role during
	// the drag, won't cause anything bad this way
	if(this.helper[0]!==this.currentItem[0]){this.currentItem.hide();}//Create the placeholder
	this._createPlaceholder();//Get the next scrolling parent
	this.scrollParent=this.placeholder.scrollParent();$.extend(this.offset,{parent:this._getParentOffset()});//Set a containment if given in the options
	if(o.containment){this._setContainment();}if(o.cursor&&o.cursor!=="auto"){// cursor option
	body=this.document.find("body");this._storedStylesheet=$("<style>*{ cursor: "+o.cursor+" !important; }</style>").appendTo(body);}// We need to make sure to grab the zIndex before setting the
	// opacity, because setting the opacity to anything lower than 1
	// causes the zIndex to change from "auto" to 0.
	if(o.zIndex){// zIndex option
	if(this.helper.css("zIndex")){this._storedZIndex=this.helper.css("zIndex");}this.helper.css("zIndex",o.zIndex);}if(o.opacity){// opacity option
	if(this.helper.css("opacity")){this._storedOpacity=this.helper.css("opacity");}this.helper.css("opacity",o.opacity);}//Prepare scrolling
	if(this.scrollParent[0]!==this.document[0]&&this.scrollParent[0].tagName!=="HTML"){this.overflowOffset=this.scrollParent.offset();}//Call callbacks
	this._trigger("start",event,this._uiHash());//Recache the helper size
	if(!this._preserveHelperProportions){this._cacheHelperProportions();}//Post "activate" events to possible containers
	if(!noActivation){for(i=this.containers.length-1;i>=0;i--){this.containers[i]._trigger("activate",event,this._uiHash(this));}}//Prepare possible droppables
	if($.ui.ddmanager){$.ui.ddmanager.current=this;}if($.ui.ddmanager&&!o.dropBehaviour){$.ui.ddmanager.prepareOffsets(this,event);}this.dragging=true;this._addClass(this.helper,"ui-sortable-helper");//Move the helper, if needed
	if(!this.helper.parent().is(this.appendTo)){this.helper.detach().appendTo(this.appendTo);//Update position
	this.offset.parent=this._getParentOffset();}//Generate the original position
	this.position=this.originalPosition=this._generatePosition(event);this.originalPageX=event.pageX;this.originalPageY=event.pageY;this.lastPositionAbs=this.positionAbs=this._convertPositionTo("absolute");this._mouseDrag(event);return true;},_scroll:function(event){var o=this.options,scrolled=false;if(this.scrollParent[0]!==this.document[0]&&this.scrollParent[0].tagName!=="HTML"){if(this.overflowOffset.top+this.scrollParent[0].offsetHeight-event.pageY<o.scrollSensitivity){this.scrollParent[0].scrollTop=scrolled=this.scrollParent[0].scrollTop+o.scrollSpeed;}else if(event.pageY-this.overflowOffset.top<o.scrollSensitivity){this.scrollParent[0].scrollTop=scrolled=this.scrollParent[0].scrollTop-o.scrollSpeed;}if(this.overflowOffset.left+this.scrollParent[0].offsetWidth-event.pageX<o.scrollSensitivity){this.scrollParent[0].scrollLeft=scrolled=this.scrollParent[0].scrollLeft+o.scrollSpeed;}else if(event.pageX-this.overflowOffset.left<o.scrollSensitivity){this.scrollParent[0].scrollLeft=scrolled=this.scrollParent[0].scrollLeft-o.scrollSpeed;}}else {if(event.pageY-this.document.scrollTop()<o.scrollSensitivity){scrolled=this.document.scrollTop(this.document.scrollTop()-o.scrollSpeed);}else if(this.window.height()-(event.pageY-this.document.scrollTop())<o.scrollSensitivity){scrolled=this.document.scrollTop(this.document.scrollTop()+o.scrollSpeed);}if(event.pageX-this.document.scrollLeft()<o.scrollSensitivity){scrolled=this.document.scrollLeft(this.document.scrollLeft()-o.scrollSpeed);}else if(this.window.width()-(event.pageX-this.document.scrollLeft())<o.scrollSensitivity){scrolled=this.document.scrollLeft(this.document.scrollLeft()+o.scrollSpeed);}}return scrolled;},_mouseDrag:function(event){var i,item,itemElement,intersection,o=this.options;//Compute the helpers position
	this.position=this._generatePosition(event);this.positionAbs=this._convertPositionTo("absolute");//Set the helper position
	if(!this.options.axis||this.options.axis!=="y"){this.helper[0].style.left=this.position.left+"px";}if(!this.options.axis||this.options.axis!=="x"){this.helper[0].style.top=this.position.top+"px";}//Do scrolling
	if(o.scroll){if(this._scroll(event)!==false){//Update item positions used in position checks
	this._refreshItemPositions(true);if($.ui.ddmanager&&!o.dropBehaviour){$.ui.ddmanager.prepareOffsets(this,event);}}}this.dragDirection={vertical:this._getDragVerticalDirection(),horizontal:this._getDragHorizontalDirection()};//Rearrange
	for(i=this.items.length-1;i>=0;i--){//Cache variables and intersection, continue if no intersection
	item=this.items[i];itemElement=item.item[0];intersection=this._intersectsWithPointer(item);if(!intersection){continue;}// Only put the placeholder inside the current Container, skip all
	// items from other containers. This works because when moving
	// an item from one container to another the
	// currentContainer is switched before the placeholder is moved.
	//
	// Without this, moving items in "sub-sortables" can cause
	// the placeholder to jitter between the outer and inner container.
	if(item.instance!==this.currentContainer){continue;}// Cannot intersect with itself
	// no useless actions that have been done before
	// no action if the item moved is the parent of the item checked
	if(itemElement!==this.currentItem[0]&&this.placeholder[intersection===1?"next":"prev"]()[0]!==itemElement&&!$.contains(this.placeholder[0],itemElement)&&(this.options.type==="semi-dynamic"?!$.contains(this.element[0],itemElement):true)){this.direction=intersection===1?"down":"up";if(this.options.tolerance==="pointer"||this._intersectsWithSides(item)){this._rearrange(event,item);}else {break;}this._trigger("change",event,this._uiHash());break;}}//Post events to containers
	this._contactContainers(event);//Interconnect with droppables
	if($.ui.ddmanager){$.ui.ddmanager.drag(this,event);}//Call callbacks
	this._trigger("sort",event,this._uiHash());this.lastPositionAbs=this.positionAbs;return false;},_mouseStop:function(event,noPropagation){if(!event){return;}//If we are using droppables, inform the manager about the drop
	if($.ui.ddmanager&&!this.options.dropBehaviour){$.ui.ddmanager.drop(this,event);}if(this.options.revert){var that=this,cur=this.placeholder.offset(),axis=this.options.axis,animation={};if(!axis||axis==="x"){animation.left=cur.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollLeft);}if(!axis||axis==="y"){animation.top=cur.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollTop);}this.reverting=true;$(this.helper).animate(animation,parseInt(this.options.revert,10)||500,function(){that._clear(event);});}else {this._clear(event,noPropagation);}return false;},cancel:function(){if(this.dragging){this._mouseUp(new $.Event("mouseup",{target:null}));if(this.options.helper==="original"){this.currentItem.css(this._storedCSS);this._removeClass(this.currentItem,"ui-sortable-helper");}else {this.currentItem.show();}//Post deactivating events to containers
	for(var i=this.containers.length-1;i>=0;i--){this.containers[i]._trigger("deactivate",null,this._uiHash(this));if(this.containers[i].containerCache.over){this.containers[i]._trigger("out",null,this._uiHash(this));this.containers[i].containerCache.over=0;}}}if(this.placeholder){//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately,
	// it unbinds ALL events from the original node!
	if(this.placeholder[0].parentNode){this.placeholder[0].parentNode.removeChild(this.placeholder[0]);}if(this.options.helper!=="original"&&this.helper&&this.helper[0].parentNode){this.helper.remove();}$.extend(this,{helper:null,dragging:false,reverting:false,_noFinalSort:null});if(this.domPosition.prev){$(this.domPosition.prev).after(this.currentItem);}else {$(this.domPosition.parent).prepend(this.currentItem);}}return this;},serialize:function(o){var items=this._getItemsAsjQuery(o&&o.connected),str=[];o=o||{};$(items).each(function(){var res=($(o.item||this).attr(o.attribute||"id")||"").match(o.expression||/(.+)[\-=_](.+)/);if(res){str.push((o.key||res[1]+"[]")+"="+(o.key&&o.expression?res[1]:res[2]));}});if(!str.length&&o.key){str.push(o.key+"=");}return str.join("&");},toArray:function(o){var items=this._getItemsAsjQuery(o&&o.connected),ret=[];o=o||{};items.each(function(){ret.push($(o.item||this).attr(o.attribute||"id")||"");});return ret;},/* Be careful with the following core functions */_intersectsWith:function(item){var x1=this.positionAbs.left,x2=x1+this.helperProportions.width,y1=this.positionAbs.top,y2=y1+this.helperProportions.height,l=item.left,r=l+item.width,t=item.top,b=t+item.height,dyClick=this.offset.click.top,dxClick=this.offset.click.left,isOverElementHeight=this.options.axis==="x"||y1+dyClick>t&&y1+dyClick<b,isOverElementWidth=this.options.axis==="y"||x1+dxClick>l&&x1+dxClick<r,isOverElement=isOverElementHeight&&isOverElementWidth;if(this.options.tolerance==="pointer"||this.options.forcePointerForContainers||this.options.tolerance!=="pointer"&&this.helperProportions[this.floating?"width":"height"]>item[this.floating?"width":"height"]){return isOverElement;}else {return l<x1+this.helperProportions.width/2&&// Right Half
	x2-this.helperProportions.width/2<r&&// Left Half
	t<y1+this.helperProportions.height/2&&// Bottom Half
	y2-this.helperProportions.height/2<b;// Top Half
	}},_intersectsWithPointer:function(item){var verticalDirection,horizontalDirection,isOverElementHeight=this.options.axis==="x"||this._isOverAxis(this.positionAbs.top+this.offset.click.top,item.top,item.height),isOverElementWidth=this.options.axis==="y"||this._isOverAxis(this.positionAbs.left+this.offset.click.left,item.left,item.width),isOverElement=isOverElementHeight&&isOverElementWidth;if(!isOverElement){return false;}verticalDirection=this.dragDirection.vertical;horizontalDirection=this.dragDirection.horizontal;return this.floating?horizontalDirection==="right"||verticalDirection==="down"?2:1:verticalDirection&&(verticalDirection==="down"?2:1);},_intersectsWithSides:function(item){var isOverBottomHalf=this._isOverAxis(this.positionAbs.top+this.offset.click.top,item.top+item.height/2,item.height),isOverRightHalf=this._isOverAxis(this.positionAbs.left+this.offset.click.left,item.left+item.width/2,item.width),verticalDirection=this.dragDirection.vertical,horizontalDirection=this.dragDirection.horizontal;if(this.floating&&horizontalDirection){return horizontalDirection==="right"&&isOverRightHalf||horizontalDirection==="left"&&!isOverRightHalf;}else {return verticalDirection&&(verticalDirection==="down"&&isOverBottomHalf||verticalDirection==="up"&&!isOverBottomHalf);}},_getDragVerticalDirection:function(){var delta=this.positionAbs.top-this.lastPositionAbs.top;return delta!==0&&(delta>0?"down":"up");},_getDragHorizontalDirection:function(){var delta=this.positionAbs.left-this.lastPositionAbs.left;return delta!==0&&(delta>0?"right":"left");},refresh:function(event){this._refreshItems(event);this._setHandleClassName();this.refreshPositions();return this;},_connectWith:function(){var options=this.options;return options.connectWith.constructor===String?[options.connectWith]:options.connectWith;},_getItemsAsjQuery:function(connected){var i,j,cur,inst,items=[],queries=[],connectWith=this._connectWith();if(connectWith&&connected){for(i=connectWith.length-1;i>=0;i--){cur=$(connectWith[i],this.document[0]);for(j=cur.length-1;j>=0;j--){inst=$.data(cur[j],this.widgetFullName);if(inst&&inst!==this&&!inst.options.disabled){queries.push([typeof inst.options.items==="function"?inst.options.items.call(inst.element):$(inst.options.items,inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),inst]);}}}}queries.push([typeof this.options.items==="function"?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):$(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);function addItems(){items.push(this);}for(i=queries.length-1;i>=0;i--){queries[i][0].each(addItems);}return $(items);},_removeCurrentsFromItems:function(){var list=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=$.grep(this.items,function(item){for(var j=0;j<list.length;j++){if(list[j]===item.item[0]){return false;}}return true;});},_refreshItems:function(event){this.items=[];this.containers=[this];var i,j,cur,inst,targetData,_queries,item,queriesLength,items=this.items,queries=[[typeof this.options.items==="function"?this.options.items.call(this.element[0],event,{item:this.currentItem}):$(this.options.items,this.element),this]],connectWith=this._connectWith();//Shouldn't be run the first time through due to massive slow-down
	if(connectWith&&this.ready){for(i=connectWith.length-1;i>=0;i--){cur=$(connectWith[i],this.document[0]);for(j=cur.length-1;j>=0;j--){inst=$.data(cur[j],this.widgetFullName);if(inst&&inst!==this&&!inst.options.disabled){queries.push([typeof inst.options.items==="function"?inst.options.items.call(inst.element[0],event,{item:this.currentItem}):$(inst.options.items,inst.element),inst]);this.containers.push(inst);}}}}for(i=queries.length-1;i>=0;i--){targetData=queries[i][1];_queries=queries[i][0];for(j=0,queriesLength=_queries.length;j<queriesLength;j++){item=$(_queries[j]);// Data for target checking (mouse manager)
	item.data(this.widgetName+"-item",targetData);items.push({item:item,instance:targetData,width:0,height:0,left:0,top:0});}}},_refreshItemPositions:function(fast){var i,item,t,p;for(i=this.items.length-1;i>=0;i--){item=this.items[i];//We ignore calculating positions of all connected containers when we're not over them
	if(this.currentContainer&&item.instance!==this.currentContainer&&item.item[0]!==this.currentItem[0]){continue;}t=this.options.toleranceElement?$(this.options.toleranceElement,item.item):item.item;if(!fast){item.width=t.outerWidth();item.height=t.outerHeight();}p=t.offset();item.left=p.left;item.top=p.top;}},refreshPositions:function(fast){// Determine whether items are being displayed horizontally
	this.floating=this.items.length?this.options.axis==="x"||this._isFloating(this.items[0].item):false;// This has to be redone because due to the item being moved out/into the offsetParent,
	// the offsetParent's position will change
	if(this.offsetParent&&this.helper){this.offset.parent=this._getParentOffset();}this._refreshItemPositions(fast);var i,p;if(this.options.custom&&this.options.custom.refreshContainers){this.options.custom.refreshContainers.call(this);}else {for(i=this.containers.length-1;i>=0;i--){p=this.containers[i].element.offset();this.containers[i].containerCache.left=p.left;this.containers[i].containerCache.top=p.top;this.containers[i].containerCache.width=this.containers[i].element.outerWidth();this.containers[i].containerCache.height=this.containers[i].element.outerHeight();}}return this;},_createPlaceholder:function(that){that=that||this;var className,nodeName,o=that.options;if(!o.placeholder||o.placeholder.constructor===String){className=o.placeholder;nodeName=that.currentItem[0].nodeName.toLowerCase();o.placeholder={element:function(){var element=$("<"+nodeName+">",that.document[0]);that._addClass(element,"ui-sortable-placeholder",className||that.currentItem[0].className)._removeClass(element,"ui-sortable-helper");if(nodeName==="tbody"){that._createTrPlaceholder(that.currentItem.find("tr").eq(0),$("<tr>",that.document[0]).appendTo(element));}else if(nodeName==="tr"){that._createTrPlaceholder(that.currentItem,element);}else if(nodeName==="img"){element.attr("src",that.currentItem.attr("src"));}if(!className){element.css("visibility","hidden");}return element;},update:function(container,p){// 1. If a className is set as 'placeholder option, we don't force sizes -
	// the class is responsible for that
	// 2. The option 'forcePlaceholderSize can be enabled to force it even if a
	// class name is specified
	if(className&&!o.forcePlaceholderSize){return;}// If the element doesn't have a actual height or width by itself (without
	// styles coming from a stylesheet), it receives the inline height and width
	// from the dragged item. Or, if it's a tbody or tr, it's going to have a height
	// anyway since we're populating them with <td>s above, but they're unlikely to
	// be the correct height on their own if the row heights are dynamic, so we'll
	// always assign the height of the dragged item given forcePlaceholderSize
	// is true.
	if(!p.height()||o.forcePlaceholderSize&&(nodeName==="tbody"||nodeName==="tr")){p.height(that.currentItem.innerHeight()-parseInt(that.currentItem.css("paddingTop")||0,10)-parseInt(that.currentItem.css("paddingBottom")||0,10));}if(!p.width()){p.width(that.currentItem.innerWidth()-parseInt(that.currentItem.css("paddingLeft")||0,10)-parseInt(that.currentItem.css("paddingRight")||0,10));}}};}//Create the placeholder
	that.placeholder=$(o.placeholder.element.call(that.element,that.currentItem));//Append it after the actual current item
	that.currentItem.after(that.placeholder);//Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
	o.placeholder.update(that,that.placeholder);},_createTrPlaceholder:function(sourceTr,targetTr){var that=this;sourceTr.children().each(function(){$("<td>&#160;</td>",that.document[0]).attr("colspan",$(this).attr("colspan")||1).appendTo(targetTr);});},_contactContainers:function(event){var i,j,dist,itemWithLeastDistance,posProperty,sizeProperty,cur,nearBottom,floating,axis,innermostContainer=null,innermostIndex=null;// Get innermost container that intersects with item
	for(i=this.containers.length-1;i>=0;i--){// Never consider a container that's located within the item itself
	if($.contains(this.currentItem[0],this.containers[i].element[0])){continue;}if(this._intersectsWith(this.containers[i].containerCache)){// If we've already found a container and it's more "inner" than this, then continue
	if(innermostContainer&&$.contains(this.containers[i].element[0],innermostContainer.element[0])){continue;}innermostContainer=this.containers[i];innermostIndex=i;}else {// container doesn't intersect. trigger "out" event if necessary
	if(this.containers[i].containerCache.over){this.containers[i]._trigger("out",event,this._uiHash(this));this.containers[i].containerCache.over=0;}}}// If no intersecting containers found, return
	if(!innermostContainer){return;}// Move the item into the container if it's not there already
	if(this.containers.length===1){if(!this.containers[innermostIndex].containerCache.over){this.containers[innermostIndex]._trigger("over",event,this._uiHash(this));this.containers[innermostIndex].containerCache.over=1;}}else {// When entering a new container, we will find the item with the least distance and
	// append our item near it
	dist=10000;itemWithLeastDistance=null;floating=innermostContainer.floating||this._isFloating(this.currentItem);posProperty=floating?"left":"top";sizeProperty=floating?"width":"height";axis=floating?"pageX":"pageY";for(j=this.items.length-1;j>=0;j--){if(!$.contains(this.containers[innermostIndex].element[0],this.items[j].item[0])){continue;}if(this.items[j].item[0]===this.currentItem[0]){continue;}cur=this.items[j].item.offset()[posProperty];nearBottom=false;if(event[axis]-cur>this.items[j][sizeProperty]/2){nearBottom=true;}if(Math.abs(event[axis]-cur)<dist){dist=Math.abs(event[axis]-cur);itemWithLeastDistance=this.items[j];this.direction=nearBottom?"up":"down";}}//Check if dropOnEmpty is enabled
	if(!itemWithLeastDistance&&!this.options.dropOnEmpty){return;}if(this.currentContainer===this.containers[innermostIndex]){if(!this.currentContainer.containerCache.over){this.containers[innermostIndex]._trigger("over",event,this._uiHash());this.currentContainer.containerCache.over=1;}return;}if(itemWithLeastDistance){this._rearrange(event,itemWithLeastDistance,null,true);}else {this._rearrange(event,null,this.containers[innermostIndex].element,true);}this._trigger("change",event,this._uiHash());this.containers[innermostIndex]._trigger("change",event,this._uiHash(this));this.currentContainer=this.containers[innermostIndex];//Update the placeholder
	this.options.placeholder.update(this.currentContainer,this.placeholder);//Update scrollParent
	this.scrollParent=this.placeholder.scrollParent();//Update overflowOffset
	if(this.scrollParent[0]!==this.document[0]&&this.scrollParent[0].tagName!=="HTML"){this.overflowOffset=this.scrollParent.offset();}this.containers[innermostIndex]._trigger("over",event,this._uiHash(this));this.containers[innermostIndex].containerCache.over=1;}},_createHelper:function(event){var o=this.options,helper=typeof o.helper==="function"?$(o.helper.apply(this.element[0],[event,this.currentItem])):o.helper==="clone"?this.currentItem.clone():this.currentItem;//Add the helper to the DOM if that didn't happen already
	if(!helper.parents("body").length){this.appendTo[0].appendChild(helper[0]);}if(helper[0]===this.currentItem[0]){this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")};}if(!helper[0].style.width||o.forceHelperSize){helper.width(this.currentItem.width());}if(!helper[0].style.height||o.forceHelperSize){helper.height(this.currentItem.height());}return helper;},_adjustOffsetFromHelper:function(obj){if(typeof obj==="string"){obj=obj.split(" ");}if(Array.isArray(obj)){obj={left:+obj[0],top:+obj[1]||0};}if("left"in obj){this.offset.click.left=obj.left+this.margins.left;}if("right"in obj){this.offset.click.left=this.helperProportions.width-obj.right+this.margins.left;}if("top"in obj){this.offset.click.top=obj.top+this.margins.top;}if("bottom"in obj){this.offset.click.top=this.helperProportions.height-obj.bottom+this.margins.top;}},_getParentOffset:function(){//Get the offsetParent and cache its position
	this.offsetParent=this.helper.offsetParent();var po=this.offsetParent.offset();// This is a special case where we need to modify a offset calculated on start, since the
	// following happened:
	// 1. The position of the helper is absolute, so it's position is calculated based on the
	// next positioned parent
	// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't
	// the document, which means that the scroll is included in the initial calculation of the
	// offset of the parent, and never recalculated upon drag
	if(this.cssPosition==="absolute"&&this.scrollParent[0]!==this.document[0]&&$.contains(this.scrollParent[0],this.offsetParent[0])){po.left+=this.scrollParent.scrollLeft();po.top+=this.scrollParent.scrollTop();}// This needs to be actually done for all browsers, since pageX/pageY includes
	// this information.
	if(this.offsetParent[0]===this.document[0].body){po={top:0,left:0};}return {top:po.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:po.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)};},_getRelativeOffset:function(){if(this.cssPosition==="relative"){var p=this.currentItem.position();return {top:p.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:p.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()};}else {return {top:0,left:0};}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0};},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()};},_setContainment:function(){var ce,co,over,o=this.options;if(o.containment==="parent"){o.containment=this.helper[0].parentNode;}if(o.containment==="document"||o.containment==="window"){this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,o.containment==="document"?this.document.width():this.window.width()-this.helperProportions.width-this.margins.left,(o.containment==="document"?this.document.height()||document.body.parentNode.scrollHeight:this.window.height()||this.document[0].body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];}if(!/^(document|window|parent)$/.test(o.containment)){ce=$(o.containment)[0];co=$(o.containment).offset();over=$(ce).css("overflow")!=="hidden";this.containment=[co.left+(parseInt($(ce).css("borderLeftWidth"),10)||0)+(parseInt($(ce).css("paddingLeft"),10)||0)-this.margins.left,co.top+(parseInt($(ce).css("borderTopWidth"),10)||0)+(parseInt($(ce).css("paddingTop"),10)||0)-this.margins.top,co.left+(over?Math.max(ce.scrollWidth,ce.offsetWidth):ce.offsetWidth)-(parseInt($(ce).css("borderLeftWidth"),10)||0)-(parseInt($(ce).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,co.top+(over?Math.max(ce.scrollHeight,ce.offsetHeight):ce.offsetHeight)-(parseInt($(ce).css("borderTopWidth"),10)||0)-(parseInt($(ce).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top];}},_convertPositionTo:function(d,pos){if(!pos){pos=this.position;}var mod=d==="absolute"?1:-1,scroll=this.cssPosition==="absolute"&&!(this.scrollParent[0]!==this.document[0]&&$.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,scrollIsRootNode=/(html|body)/i.test(scroll[0].tagName);return {top:// The absolute mouse position
	pos.top+// Only for relative positioned nodes: Relative offset from element to offset parent
	this.offset.relative.top*mod+// The offsetParent's offset without borders (offset + border)
	this.offset.parent.top*mod-(this.cssPosition==="fixed"?-this.scrollParent.scrollTop():scrollIsRootNode?0:scroll.scrollTop())*mod,left:// The absolute mouse position
	pos.left+// Only for relative positioned nodes: Relative offset from element to offset parent
	this.offset.relative.left*mod+// The offsetParent's offset without borders (offset + border)
	this.offset.parent.left*mod-(this.cssPosition==="fixed"?-this.scrollParent.scrollLeft():scrollIsRootNode?0:scroll.scrollLeft())*mod};},_generatePosition:function(event){var top,left,o=this.options,pageX=event.pageX,pageY=event.pageY,scroll=this.cssPosition==="absolute"&&!(this.scrollParent[0]!==this.document[0]&&$.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,scrollIsRootNode=/(html|body)/i.test(scroll[0].tagName);// This is another very weird special case that only happens for relative elements:
	// 1. If the css position is relative
	// 2. and the scroll parent is the document or similar to the offset parent
	// we have to refresh the relative offset during the scroll so there are no jumps
	if(this.cssPosition==="relative"&&!(this.scrollParent[0]!==this.document[0]&&this.scrollParent[0]!==this.offsetParent[0])){this.offset.relative=this._getRelativeOffset();}/*
				 * - Position constraining -
				 * Constrain the position to a mix of grid, containment.
				 */if(this.originalPosition){//If we are not dragging yet, we won't check for options
	if(this.containment){if(event.pageX-this.offset.click.left<this.containment[0]){pageX=this.containment[0]+this.offset.click.left;}if(event.pageY-this.offset.click.top<this.containment[1]){pageY=this.containment[1]+this.offset.click.top;}if(event.pageX-this.offset.click.left>this.containment[2]){pageX=this.containment[2]+this.offset.click.left;}if(event.pageY-this.offset.click.top>this.containment[3]){pageY=this.containment[3]+this.offset.click.top;}}if(o.grid){top=this.originalPageY+Math.round((pageY-this.originalPageY)/o.grid[1])*o.grid[1];pageY=this.containment?top-this.offset.click.top>=this.containment[1]&&top-this.offset.click.top<=this.containment[3]?top:top-this.offset.click.top>=this.containment[1]?top-o.grid[1]:top+o.grid[1]:top;left=this.originalPageX+Math.round((pageX-this.originalPageX)/o.grid[0])*o.grid[0];pageX=this.containment?left-this.offset.click.left>=this.containment[0]&&left-this.offset.click.left<=this.containment[2]?left:left-this.offset.click.left>=this.containment[0]?left-o.grid[0]:left+o.grid[0]:left;}}return {top:// The absolute mouse position
	pageY-// Click offset (relative to the element)
	this.offset.click.top-// Only for relative positioned nodes: Relative offset from element to offset parent
	this.offset.relative.top-// The offsetParent's offset without borders (offset + border)
	this.offset.parent.top+(this.cssPosition==="fixed"?-this.scrollParent.scrollTop():scrollIsRootNode?0:scroll.scrollTop()),left:// The absolute mouse position
	pageX-// Click offset (relative to the element)
	this.offset.click.left-// Only for relative positioned nodes: Relative offset from element to offset parent
	this.offset.relative.left-// The offsetParent's offset without borders (offset + border)
	this.offset.parent.left+(this.cssPosition==="fixed"?-this.scrollParent.scrollLeft():scrollIsRootNode?0:scroll.scrollLeft())};},_rearrange:function(event,i,a,hardRefresh){if(a){a[0].appendChild(this.placeholder[0]);}else {i.item[0].parentNode.insertBefore(this.placeholder[0],this.direction==="down"?i.item[0]:i.item[0].nextSibling);}//Various things done here to improve the performance:
	// 1. we create a setTimeout, that calls refreshPositions
	// 2. on the instance, we have a counter variable, that get's higher after every append
	// 3. on the local scope, we copy the counter variable, and check in the timeout,
	// if it's still the same
	// 4. this lets only the last addition to the timeout stack through
	this.counter=this.counter?++this.counter:1;var counter=this.counter;this._delay(function(){if(counter===this.counter){//Precompute after each DOM insertion, NOT on mousemove
	this.refreshPositions(!hardRefresh);}});},_clear:function(event,noPropagation){this.reverting=false;// We delay all events that have to be triggered to after the point where the placeholder
	// has been removed and everything else normalized again
	var i,delayedTriggers=[];// We first have to update the dom position of the actual currentItem
	// Note: don't do it if the current item is already removed (by a user), or it gets
	// reappended (see #4088)
	if(!this._noFinalSort&&this.currentItem.parent().length){this.placeholder.before(this.currentItem);}this._noFinalSort=null;if(this.helper[0]===this.currentItem[0]){for(i in this._storedCSS){if(this._storedCSS[i]==="auto"||this._storedCSS[i]==="static"){this._storedCSS[i]="";}}this.currentItem.css(this._storedCSS);this._removeClass(this.currentItem,"ui-sortable-helper");}else {this.currentItem.show();}if(this.fromOutside&&!noPropagation){delayedTriggers.push(function(event){this._trigger("receive",event,this._uiHash(this.fromOutside));});}if((this.fromOutside||this.domPosition.prev!==this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!==this.currentItem.parent()[0])&&!noPropagation){// Trigger update callback if the DOM position has changed
	delayedTriggers.push(function(event){this._trigger("update",event,this._uiHash());});}// Check if the items Container has Changed and trigger appropriate
	// events.
	if(this!==this.currentContainer){if(!noPropagation){delayedTriggers.push(function(event){this._trigger("remove",event,this._uiHash());});delayedTriggers.push(function(c){return function(event){c._trigger("receive",event,this._uiHash(this));};}.call(this,this.currentContainer));delayedTriggers.push(function(c){return function(event){c._trigger("update",event,this._uiHash(this));};}.call(this,this.currentContainer));}}//Post events to containers
	function delayEvent(type,instance,container){return function(event){container._trigger(type,event,instance._uiHash(instance));};}for(i=this.containers.length-1;i>=0;i--){if(!noPropagation){delayedTriggers.push(delayEvent("deactivate",this,this.containers[i]));}if(this.containers[i].containerCache.over){delayedTriggers.push(delayEvent("out",this,this.containers[i]));this.containers[i].containerCache.over=0;}}//Do what was originally in plugins
	if(this._storedStylesheet){this._storedStylesheet.remove();this._storedStylesheet=null;}if(this._storedOpacity){this.helper.css("opacity",this._storedOpacity);}if(this._storedZIndex){this.helper.css("zIndex",this._storedZIndex==="auto"?"":this._storedZIndex);}this.dragging=false;if(!noPropagation){this._trigger("beforeStop",event,this._uiHash());}//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately,
	// it unbinds ALL events from the original node!
	this.placeholder[0].parentNode.removeChild(this.placeholder[0]);if(!this.cancelHelperRemoval){if(this.helper[0]!==this.currentItem[0]){this.helper.remove();}this.helper=null;}if(!noPropagation){for(i=0;i<delayedTriggers.length;i++){// Trigger all delayed events
	delayedTriggers[i].call(this,event);}this._trigger("stop",event,this._uiHash());}this.fromOutside=false;return !this.cancelHelperRemoval;},_trigger:function(){if($.Widget.prototype._trigger.apply(this,arguments)===false){this.cancel();}},_uiHash:function(_inst){var inst=_inst||this;return {helper:inst.helper,placeholder:inst.placeholder||$([]),position:inst.position,originalPosition:inst.originalPosition,offset:inst.positionAbs,item:inst.currentItem,sender:_inst?_inst.element:null};}});/*!
		 * jQuery UI Spinner 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Spinner
	//>>group: Widgets
	//>>description: Displays buttons to easily input numbers via the keyboard or mouse.
	//>>docs: https://api.jqueryui.com/spinner/
	//>>demos: https://jqueryui.com/spinner/
	//>>css.structure: ../../themes/base/core.css
	//>>css.structure: ../../themes/base/spinner.css
	//>>css.theme: ../../themes/base/theme.css
	function spinnerModifier(fn){return function(){var previous=this.element.val();fn.apply(this,arguments);this._refresh();if(previous!==this.element.val()){this._trigger("change");}};}$.widget("ui.spinner",{version:"1.14.2",defaultElement:"<input>",widgetEventPrefix:"spin",options:{classes:{"ui-spinner":"ui-corner-all","ui-spinner-down":"ui-corner-br","ui-spinner-up":"ui-corner-tr"},culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:true,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){// handle string values that need to be parsed
	this._setOption("max",this.options.max);this._setOption("min",this.options.min);this._setOption("step",this.options.step);// Only format if there is a value, prevents the field from being marked
	// as invalid in Firefox, see #9573.
	if(this.value()!==""){// Format the value, but don't constrain.
	this._value(this.element.val(),true);}this._draw();this._on(this._events);this._refresh();// Turning off autocomplete prevents the browser from remembering the
	// value when navigating through history, so we re-enable autocomplete
	// if the page is unloaded before the widget is destroyed. #7790
	this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete");}});},_getCreateOptions:function(){var options=this._super();var element=this.element;$.each(["min","max","step"],function(i,option){var value=element.attr(option);if(value!=null&&value.length){options[option]=value;}});return options;},_events:{keydown:function(event){if(this._start(event)&&this._keydown(event)){event.preventDefault();}},keyup:"_stop",focus:function(){this.previous=this.element.val();},blur:function(event){this._stop();this._refresh();if(this.previous!==this.element.val()){this._trigger("change",event);}},wheel:function(event){var activeElement=this.document[0].activeElement;var isActive=this.element[0]===activeElement;var delta=event.deltaY||event.originalEvent&&event.originalEvent.deltaY;if(!isActive||!delta){return;}if(!this.spinning&&!this._start(event)){return false;}this._spin((delta>0?-1:1)*this.options.step,event);clearTimeout(this.mousewheelTimer);this.mousewheelTimer=this._delay(function(){if(this.spinning){this._stop(event);}},100);event.preventDefault();},// DEPRECATED
	// Kept for backwards compatibility. Please use the modern `wheel`
	// event. The `delta` parameter is provided by the jQuery Mousewheel
	// plugin if one is loaded.
	mousewheel:function(event,delta){if(!event.isTrigger){// If this is not a trigger call, the `wheel` handler will
	// fire as well, let's not duplicate it.
	return;}var wheelEvent=$.Event(event);wheelEvent.type="wheel";if(delta){wheelEvent.deltaY=-delta;}return this._events.wheel.call(this,wheelEvent);},"mousedown .ui-spinner-button":function(event){var previous;// We never want the buttons to have focus; whenever the user is
	// interacting with the spinner, the focus should be on the input.
	// If the input is focused then this.previous is properly set from
	// when the input first received focus. If the input is not focused
	// then we need to set this.previous based on the value before spinning.
	previous=this.element[0]===this.document[0].activeElement?this.previous:this.element.val();function checkFocus(){var isActive=this.element[0]===this.document[0].activeElement;if(!isActive){this.element.trigger("focus");this.previous=previous;}}// Ensure focus is on (or stays on) the text field
	event.preventDefault();checkFocus.call(this);if(this._start(event)===false){return;}this._repeat(null,$(event.currentTarget).hasClass("ui-spinner-up")?1:-1,event);},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(event){// button will add ui-state-active if mouse was down while mouseleave and kept down
	if(!$(event.currentTarget).hasClass("ui-state-active")){return;}if(this._start(event)===false){return false;}this._repeat(null,$(event.currentTarget).hasClass("ui-spinner-up")?1:-1,event);},// TODO: do we really want to consider this a stop?
	// shouldn't we just stop the repeater and wait until mouseup before
	// we trigger the stop event?
	"mouseleave .ui-spinner-button":"_stop"},// Support mobile enhanced option and make backcompat more sane
	_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap("<span>").parent()// Add buttons
	.append("<a></a><a></a>");},_draw:function(){this._enhance();this._addClass(this.uiSpinner,"ui-spinner","ui-widget ui-widget-content");this._addClass("ui-spinner-input");this.element.attr("role","spinbutton");// Button bindings
	this.buttons=this.uiSpinner.children("a").attr("tabIndex",-1).attr("aria-hidden",true).button({classes:{"ui-button":""}});// TODO: Right now button does not support classes this is already updated in button PR
	this._removeClass(this.buttons,"ui-corner-all");this._addClass(this.buttons.first(),"ui-spinner-button ui-spinner-up");this._addClass(this.buttons.last(),"ui-spinner-button ui-spinner-down");this.buttons.first().button({"icon":this.options.icons.up,"showLabel":false});this.buttons.last().button({"icon":this.options.icons.down,"showLabel":false});// IE 6 doesn't understand height: 50% for the buttons
	// unless the wrapper has an explicit height
	if(this.buttons.height()>Math.ceil(this.uiSpinner.height()*0.5)&&this.uiSpinner.height()>0){this.uiSpinner.height(this.uiSpinner.height());}},_keydown:function(event){var options=this.options,keyCode=$.ui.keyCode;switch(event.keyCode){case keyCode.UP:this._repeat(null,1,event);return true;case keyCode.DOWN:this._repeat(null,-1,event);return true;case keyCode.PAGE_UP:this._repeat(null,options.page,event);return true;case keyCode.PAGE_DOWN:this._repeat(null,-options.page,event);return true;}return false;},_start:function(event){if(!this.spinning&&this._trigger("start",event)===false){return false;}if(!this.counter){this.counter=1;}this.spinning=true;return true;},_repeat:function(i,steps,event){i=i||500;clearTimeout(this.timer);this.timer=this._delay(function(){this._repeat(40,steps,event);},i);this._spin(steps*this.options.step,event);},_spin:function(step,event){var value=this.value()||0;if(!this.counter){this.counter=1;}value=this._adjustValue(value+step*this._increment(this.counter));if(!this.spinning||this._trigger("spin",event,{value:value})!==false){this._value(value);this.counter++;}},_increment:function(i){var incremental=this.options.incremental;if(incremental){return typeof incremental==="function"?incremental(i):Math.floor(i*i*i/50000-i*i/500+17*i/200+1);}return 1;},_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;},_adjustValue:function(value){var base,aboveMin,options=this.options;// Make sure we're at a valid step
	// - find out where we are relative to the base (min or 0)
	base=options.min!==null?options.min:0;aboveMin=value-base;// - round to the nearest step
	aboveMin=Math.round(aboveMin/options.step)*options.step;// - rounding is based on 0, so adjust back to our base
	value=base+aboveMin;// Fix precision from bad JS floating point math
	value=parseFloat(value.toFixed(this._precision()));// Clamp the value
	if(options.max!==null&&value>options.max){return options.max;}if(options.min!==null&&value<options.min){return options.min;}return value;},_stop:function(event){if(!this.spinning){return;}clearTimeout(this.timer);clearTimeout(this.mousewheelTimer);this.counter=0;this.spinning=false;this._trigger("stop",event);},_setOption:function(key,value){var prevValue,first,last;if(key==="culture"||key==="numberFormat"){prevValue=this._parse(this.element.val());this.options[key]=value;this.element.val(this._format(prevValue));return;}if(key==="max"||key==="min"||key==="step"){if(typeof value==="string"){value=this._parse(value);}}if(key==="icons"){first=this.buttons.first().find(".ui-icon");this._removeClass(first,null,this.options.icons.up);this._addClass(first,null,value.up);last=this.buttons.last().find(".ui-icon");this._removeClass(last,null,this.options.icons.down);this._addClass(last,null,value.down);}this._super(key,value);},_setOptionDisabled:function(value){this._super(value);this._toggleClass(this.uiSpinner,null,"ui-state-disabled",!!value);this.element.prop("disabled",!!value);this.buttons.button(value?"disable":"enable");},_setOptions:spinnerModifier(function(options){this._super(options);}),_parse:function(val){if(typeof val==="string"&&val!==""){val=window.Globalize&&this.options.numberFormat?Globalize.parseFloat(val,10,this.options.culture):+val;}return val===""||isNaN(val)?null:val;},_format:function(value){if(value===""){return "";}return window.Globalize&&this.options.numberFormat?Globalize.format(value,this.options.numberFormat,this.options.culture):value;},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,// TODO: what should we do with values that can't be parsed?
	"aria-valuenow":this._parse(this.element.val())});},isValid:function(){var value=this.value();// Null is invalid
	if(value===null){return false;}// If value gets adjusted, it's invalid
	return value===this._adjustValue(value);},// Update the value without triggering change
	_value:function(value,allowAny){var parsed;if(value!==""){parsed=this._parse(value);if(parsed!==null){if(!allowAny){parsed=this._adjustValue(parsed);}value=this._format(parsed);}}this.element.val(value);this._refresh();},_destroy:function(){this.element.prop("disabled",false).removeAttr("autocomplete role aria-valuemin aria-valuemax aria-valuenow");this.uiSpinner.replaceWith(this.element);},stepUp:spinnerModifier(function(steps){this._stepUp(steps);}),_stepUp:function(steps){if(this._start()){this._spin((steps||1)*this.options.step);this._stop();}},stepDown:spinnerModifier(function(steps){this._stepDown(steps);}),_stepDown:function(steps){if(this._start()){this._spin((steps||1)*-this.options.step);this._stop();}},pageUp:spinnerModifier(function(pages){this._stepUp((pages||1)*this.options.page);}),pageDown:spinnerModifier(function(pages){this._stepDown((pages||1)*this.options.page);}),value:function(newVal){if(!arguments.length){return this._parse(this.element.val());}spinnerModifier(this._value).call(this,newVal);},widget:function(){return this.uiSpinner;}});// DEPRECATED
	// TODO: switch return back to widget declaration at top of file when this is removed
	if($.uiBackCompat===true){// Backcompat for spinner html extension points
	$.widget("ui.spinner",$.ui.spinner,{_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent()// Add buttons
	.append(this._buttonHtml());},_uiSpinnerHtml:function(){return "<span>";},_buttonHtml:function(){return "<a></a><a></a>";}});}$.ui.spinner;/*!
		 * jQuery UI Tabs 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Tabs
	//>>group: Widgets
	//>>description: Transforms a set of container elements into a tab structure.
	//>>docs: https://api.jqueryui.com/tabs/
	//>>demos: https://jqueryui.com/tabs/
	//>>css.structure: ../../themes/base/core.css
	//>>css.structure: ../../themes/base/tabs.css
	//>>css.theme: ../../themes/base/theme.css
	$.widget("ui.tabs",{version:"1.14.2",delay:300,options:{active:null,classes:{"ui-tabs":"ui-corner-all","ui-tabs-nav":"ui-corner-all","ui-tabs-panel":"ui-corner-bottom","ui-tabs-tab":"ui-corner-top"},collapsible:false,event:"click",heightStyle:"content",hide:null,show:null,// Callbacks
	activate:null,beforeActivate:null,beforeLoad:null,load:null},_isLocal:function(anchor){var anchorUrl=new URL(anchor.href),locationUrl=new URL(location.href);return anchor.hash.length>1&&// `href` may contain a hash but also username & password;
	// we want to ignore them, so we check the three fields
	// below instead.
	anchorUrl.origin===locationUrl.origin&&anchorUrl.pathname===locationUrl.pathname&&anchorUrl.search===locationUrl.search;},_create:function(){var that=this,options=this.options;this.running=false;this._addClass("ui-tabs","ui-widget ui-widget-content");this._toggleClass("ui-tabs-collapsible",null,options.collapsible);this._processTabs();options.active=this._initialActive();// Take disabling tabs via class attribute from HTML
	// into account and update option properly.
	if(Array.isArray(options.disabled)){options.disabled=$.uniqueSort(options.disabled.concat($.map(this.tabs.filter(".ui-state-disabled"),function(li){return that.tabs.index(li);}))).sort();}// Check for length avoids error when initializing empty list
	if(this.options.active!==false&&this.anchors.length){this.active=this._findActive(options.active);}else {this.active=$();}this._refresh();if(this.active.length){this.load(options.active);}},_initialActive:function(){var active=this.options.active,collapsible=this.options.collapsible,locationHash=location.hash.substring(1),locationHashDecoded=decodeURIComponent(locationHash);if(active===null){// check the fragment identifier in the URL
	if(locationHash){this.tabs.each(function(i,tab){if($(tab).attr("aria-controls")===locationHash){active=i;return false;}});// If not found, decode the hash & try again.
	// See the comment in `_processTabs` under the `_isLocal` check
	// for more information.
	if(active===null){this.tabs.each(function(i,tab){if($(tab).attr("aria-controls")===locationHashDecoded){active=i;return false;}});}}// Check for a tab marked active via a class
	if(active===null){active=this.tabs.index(this.tabs.filter(".ui-tabs-active"));}// No active tab, set to false
	if(active===null||active===-1){active=this.tabs.length?0:false;}}// Handle numbers: negative, out of range
	if(active!==false){active=this.tabs.index(this.tabs.eq(active));if(active===-1){active=collapsible?false:0;}}// Don't allow collapsible: false and active: false
	if(!collapsible&&active===false&&this.anchors.length){active=0;}return active;},_getCreateEventData:function(){return {tab:this.active,panel:!this.active.length?$():this._getPanelForTab(this.active)};},_tabKeydown:function(event){var focusedTab=$(this.document[0].activeElement).closest("li"),selectedIndex=this.tabs.index(focusedTab),goingForward=true;if(this._handlePageNav(event)){return;}switch(event.keyCode){case $.ui.keyCode.RIGHT:case $.ui.keyCode.DOWN:selectedIndex++;break;case $.ui.keyCode.UP:case $.ui.keyCode.LEFT:goingForward=false;selectedIndex--;break;case $.ui.keyCode.END:selectedIndex=this.anchors.length-1;break;case $.ui.keyCode.HOME:selectedIndex=0;break;case $.ui.keyCode.SPACE:// Activate only, no collapsing
	event.preventDefault();clearTimeout(this.activating);this._activate(selectedIndex);return;case $.ui.keyCode.ENTER:// Toggle (cancel delayed activation, allow collapsing)
	event.preventDefault();clearTimeout(this.activating);// Determine if we should collapse or activate
	this._activate(selectedIndex===this.options.active?false:selectedIndex);return;default:return;}// Focus the appropriate tab, based on which key was pressed
	event.preventDefault();clearTimeout(this.activating);selectedIndex=this._focusNextTab(selectedIndex,goingForward);// Navigating with control/command key will prevent automatic activation
	if(!event.ctrlKey&&!event.metaKey){// Update aria-selected immediately so that AT think the tab is already selected.
	// Otherwise AT may confuse the user by stating that they need to activate the tab,
	// but the tab will already be activated by the time the announcement finishes.
	focusedTab.attr("aria-selected","false");this.tabs.eq(selectedIndex).attr("aria-selected","true");this.activating=this._delay(function(){this.option("active",selectedIndex);},this.delay);}},_panelKeydown:function(event){if(this._handlePageNav(event)){return;}// Ctrl+up moves focus to the current tab
	if(event.ctrlKey&&event.keyCode===$.ui.keyCode.UP){event.preventDefault();this.active.trigger("focus");}},// Alt+page up/down moves focus to the previous/next tab (and activates)
	_handlePageNav:function(event){if(event.altKey&&event.keyCode===$.ui.keyCode.PAGE_UP){this._activate(this._focusNextTab(this.options.active-1,false));return true;}if(event.altKey&&event.keyCode===$.ui.keyCode.PAGE_DOWN){this._activate(this._focusNextTab(this.options.active+1,true));return true;}},_findNextTab:function(index,goingForward){var lastTabIndex=this.tabs.length-1;function constrain(){if(index>lastTabIndex){index=0;}if(index<0){index=lastTabIndex;}return index;}while($.inArray(constrain(),this.options.disabled)!==-1){index=goingForward?index+1:index-1;}return index;},_focusNextTab:function(index,goingForward){index=this._findNextTab(index,goingForward);this.tabs.eq(index).trigger("focus");return index;},_setOption:function(key,value){if(key==="active"){// _activate() will handle invalid values and update this.options
	this._activate(value);return;}this._super(key,value);if(key==="collapsible"){this._toggleClass("ui-tabs-collapsible",null,value);// Setting collapsible: false while collapsed; open first panel
	if(!value&&this.options.active===false){this._activate(0);}}if(key==="event"){this._setupEvents(value);}if(key==="heightStyle"){this._setupHeightStyle(value);}},refresh:function(){var options=this.options,lis=this.tablist.children(":has(a[href])");// Get disabled tabs from class attribute from HTML
	// this will get converted to a boolean if needed in _refresh()
	options.disabled=$.map(lis.filter(".ui-state-disabled"),function(tab){return lis.index(tab);});this._processTabs();// Was collapsed or no tabs
	if(options.active===false||!this.anchors.length){options.active=false;this.active=$();// was active, but active tab is gone
	}else if(this.active.length&&!$.contains(this.tablist[0],this.active[0])){// all remaining tabs are disabled
	if(this.tabs.length===options.disabled.length){options.active=false;this.active=$();// activate previous tab
	}else {this._activate(this._findNextTab(Math.max(0,options.active-1),false));}// was active, active tab still exists
	}else {// make sure active index is correct
	options.active=this.tabs.index(this.active);}this._refresh();},_refresh:function(){this._setOptionDisabled(this.options.disabled);this._setupEvents(this.options.event);this._setupHeightStyle(this.options.heightStyle);this.tabs.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1});this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-hidden":"true"});// Make sure one tab is in the tab order
	if(!this.active.length){this.tabs.eq(0).attr("tabIndex",0);}else {this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0});this._addClass(this.active,"ui-tabs-active","ui-state-active");this._getPanelForTab(this.active).show().attr({"aria-hidden":"false"});}},_processTabs:function(){var that=this,prevTabs=this.tabs,prevAnchors=this.anchors,prevPanels=this.panels;this.tablist=this._getList().attr("role","tablist");this._addClass(this.tablist,"ui-tabs-nav","ui-helper-reset ui-helper-clearfix ui-widget-header");// Prevent users from focusing disabled tabs via click
	this.tablist.on("mousedown"+this.eventNamespace,"> li",function(event){if($(this).is(".ui-state-disabled")){event.preventDefault();}});this.tabs=this.tablist.find("> li:has(a[href])").attr({role:"tab",tabIndex:-1});this._addClass(this.tabs,"ui-tabs-tab","ui-state-default");this.anchors=this.tabs.map(function(){return $("a",this)[0];}).attr({tabIndex:-1});this._addClass(this.anchors,"ui-tabs-anchor");this.panels=$();this.anchors.each(function(i,anchor){var selector,panel,panelId,anchorId=$(anchor).uniqueId().attr("id"),tab=$(anchor).closest("li"),originalAriaControls=tab.attr("aria-controls");// Inline tab
	if(that._isLocal(anchor)){// The "scrolling to a fragment" section of the HTML spec:
	// https://html.spec.whatwg.org/#scrolling-to-a-fragment
	// uses a concept of document's indicated part:
	// https://html.spec.whatwg.org/#the-indicated-part-of-the-document
	// Slightly below there's an algorithm to compute the indicated
	// part:
	// https://html.spec.whatwg.org/#the-indicated-part-of-the-document
	// First, the algorithm tries the hash as-is, without decoding.
	// Then, if one is not found, the same is attempted with a decoded
	// hash. Replicate this logic.
	selector=anchor.hash;panelId=selector.substring(1);panel=that.element.find("#"+CSS.escape(panelId));if(!panel.length){panelId=decodeURIComponent(panelId);panel=that.element.find("#"+CSS.escape(panelId));}// remote tab
	}else {// If the tab doesn't already have aria-controls,
	// generate an id by using a throw-away element
	panelId=tab.attr("aria-controls")||$({}).uniqueId()[0].id;selector="#"+panelId;panel=that.element.find(selector);if(!panel.length){panel=that._createPanel(panelId);panel.insertAfter(that.panels[i-1]||that.tablist);}panel.attr("aria-live","polite");}if(panel.length){that.panels=that.panels.add(panel);}if(originalAriaControls){tab.data("ui-tabs-aria-controls",originalAriaControls);}tab.attr({"aria-controls":panelId,"aria-labelledby":anchorId});panel.attr("aria-labelledby",anchorId);});this.panels.attr("role","tabpanel");this._addClass(this.panels,"ui-tabs-panel","ui-widget-content");// Avoid memory leaks (#10056)
	if(prevTabs){this._off(prevTabs.not(this.tabs));this._off(prevAnchors.not(this.anchors));this._off(prevPanels.not(this.panels));}},// Allow overriding how to find the list for rare usage scenarios (#7715)
	_getList:function(){return this.tablist||this.element.find("ol, ul").eq(0);},_createPanel:function(id){return $("<div>").attr("id",id).data("ui-tabs-destroy",true);},_setOptionDisabled:function(disabled){var currentItem,li,i;if(Array.isArray(disabled)){if(!disabled.length){disabled=false;}else if(disabled.length===this.anchors.length){disabled=true;}}// Disable tabs
	for(i=0;li=this.tabs[i];i++){currentItem=$(li);if(disabled===true||$.inArray(i,disabled)!==-1){currentItem.attr("aria-disabled","true");this._addClass(currentItem,null,"ui-state-disabled");}else {currentItem.removeAttr("aria-disabled");this._removeClass(currentItem,null,"ui-state-disabled");}}this.options.disabled=disabled;this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,disabled===true);},_setupEvents:function(event){var events={};if(event){$.each(event.split(" "),function(index,eventName){events[eventName]="_eventHandler";});}this._off(this.anchors.add(this.tabs).add(this.panels));// Always prevent the default action, even when disabled
	this._on(true,this.anchors,{click:function(event){event.preventDefault();}});this._on(this.anchors,events);this._on(this.tabs,{keydown:"_tabKeydown"});this._on(this.panels,{keydown:"_panelKeydown"});this._focusable(this.tabs);this._hoverable(this.tabs);},_setupHeightStyle:function(heightStyle){var maxHeight,parent=this.element.parent();if(heightStyle==="fill"){maxHeight=parent.height();maxHeight-=this.element.outerHeight()-this.element.height();this.element.siblings(":visible").each(function(){var elem=$(this),position=elem.css("position");if(position==="absolute"||position==="fixed"){return;}maxHeight-=elem.outerHeight(true);});this.element.children().not(this.panels).each(function(){maxHeight-=$(this).outerHeight(true);});this.panels.each(function(){$(this).height(Math.max(0,maxHeight-$(this).innerHeight()+$(this).height()));}).css("overflow","auto");}else if(heightStyle==="auto"){maxHeight=0;this.panels.each(function(){maxHeight=Math.max(maxHeight,$(this).height("").height());}).height(maxHeight);}},_eventHandler:function(event){var options=this.options,active=this.active,anchor=$(event.currentTarget),tab=anchor.closest("li"),clickedIsActive=tab[0]===active[0],collapsing=clickedIsActive&&options.collapsible,toShow=collapsing?$():this._getPanelForTab(tab),toHide=!active.length?$():this._getPanelForTab(active),eventData={oldTab:active,oldPanel:toHide,newTab:collapsing?$():tab,newPanel:toShow};event.preventDefault();if(tab.hasClass("ui-state-disabled")||// tab is already loading
	tab.hasClass("ui-tabs-loading")||// can't switch durning an animation
	this.running||// click on active header, but not collapsible
	clickedIsActive&&!options.collapsible||// allow canceling activation
	this._trigger("beforeActivate",event,eventData)===false){return;}options.active=collapsing?false:this.tabs.index(tab);this.active=clickedIsActive?$():tab;if(this.xhr){this.xhr.abort();}if(!toHide.length&&!toShow.length){$.error("jQuery UI Tabs: Mismatching fragment identifier.");}if(toShow.length){this.load(this.tabs.index(tab),event);}this._toggle(event,eventData);},// Handles show/hide for selecting tabs
	_toggle:function(event,eventData){var that=this,toShow=eventData.newPanel,toHide=eventData.oldPanel;this.running=true;function complete(){that.running=false;that._trigger("activate",event,eventData);}function show(){that._addClass(eventData.newTab.closest("li"),"ui-tabs-active","ui-state-active");if(toShow.length&&that.options.show){that._show(toShow,that.options.show,complete);}else {toShow.show();complete();}}// Start out by hiding, then showing, then completing
	if(toHide.length&&this.options.hide){this._hide(toHide,this.options.hide,function(){that._removeClass(eventData.oldTab.closest("li"),"ui-tabs-active","ui-state-active");show();});}else {this._removeClass(eventData.oldTab.closest("li"),"ui-tabs-active","ui-state-active");toHide.hide();show();}toHide.attr("aria-hidden","true");eventData.oldTab.attr({"aria-selected":"false","aria-expanded":"false"});// If we're switching tabs, remove the old tab from the tab order.
	// If we're opening from collapsed state, remove the previous tab from the tab order.
	// If we're collapsing, then keep the collapsing tab in the tab order.
	if(toShow.length&&toHide.length){eventData.oldTab.attr("tabIndex",-1);}else if(toShow.length){this.tabs.filter(function(){return $(this).attr("tabIndex")===0;}).attr("tabIndex",-1);}toShow.attr("aria-hidden","false");eventData.newTab.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0});},_activate:function(index){var anchor,active=this._findActive(index);// Trying to activate the already active panel
	if(active[0]===this.active[0]){return;}// Trying to collapse, simulate a click on the current active header
	if(!active.length){active=this.active;}anchor=active.find(".ui-tabs-anchor")[0];this._eventHandler({target:anchor,currentTarget:anchor,preventDefault:$.noop});},_findActive:function(index){return index===false?$():this.tabs.eq(index);},_getIndex:function(index){// meta-function to give users option to provide a href string instead of a numerical index.
	if(typeof index==="string"){index=this.anchors.index(this.anchors.filter("[href$='"+CSS.escape(index)+"']"));}return index;},_destroy:function(){if(this.xhr){this.xhr.abort();}this.tablist.removeAttr("role").off(this.eventNamespace);this.anchors.removeAttr("role tabIndex").removeUniqueId();this.tabs.add(this.panels).each(function(){if($.data(this,"ui-tabs-destroy")){$(this).remove();}else {$(this).removeAttr("role tabIndex "+"aria-live aria-busy aria-selected aria-labelledby aria-hidden aria-expanded");}});this.tabs.each(function(){var li=$(this),prev=li.data("ui-tabs-aria-controls");if(prev){li.attr("aria-controls",prev).removeData("ui-tabs-aria-controls");}else {li.removeAttr("aria-controls");}});this.panels.show();if(this.options.heightStyle!=="content"){this.panels.css("height","");}},enable:function(index){var disabled=this.options.disabled;if(disabled===false){return;}if(index===undefined){disabled=false;}else {index=this._getIndex(index);if(Array.isArray(disabled)){disabled=$.map(disabled,function(num){return num!==index?num:null;});}else {disabled=$.map(this.tabs,function(li,num){return num!==index?num:null;});}}this._setOptionDisabled(disabled);},disable:function(index){var disabled=this.options.disabled;if(disabled===true){return;}if(index===undefined){disabled=true;}else {index=this._getIndex(index);if($.inArray(index,disabled)!==-1){return;}if(Array.isArray(disabled)){disabled=$.merge([index],disabled).sort();}else {disabled=[index];}}this._setOptionDisabled(disabled);},load:function(index,event){index=this._getIndex(index);var that=this,tab=this.tabs.eq(index),anchor=tab.find(".ui-tabs-anchor"),panel=this._getPanelForTab(tab),eventData={tab:tab,panel:panel},complete=function(jqXHR,status){if(status==="abort"){that.panels.stop(false,true);}that._removeClass(tab,"ui-tabs-loading");panel.removeAttr("aria-busy");if(jqXHR===that.xhr){delete that.xhr;}};// Not remote
	if(this._isLocal(anchor[0])){return;}this.xhr=$.ajax(this._ajaxSettings(anchor,event,eventData));if(this.xhr.statusText!=="canceled"){this._addClass(tab,"ui-tabs-loading");panel.attr("aria-busy","true");this.xhr.done(function(response,status,jqXHR){panel.html(response);that._trigger("load",event,eventData);complete(jqXHR,status);}).fail(function(jqXHR,status){complete(jqXHR,status);});}},_ajaxSettings:function(anchor,event,eventData){var that=this;return {url:anchor.attr("href"),beforeSend:function(jqXHR,settings){return that._trigger("beforeLoad",event,$.extend({jqXHR:jqXHR,ajaxSettings:settings},eventData));}};},_getPanelForTab:function(tab){var id=$(tab).attr("aria-controls");return this.element.find("#"+CSS.escape(id));}});// DEPRECATED
	// TODO: Switch return back to widget declaration at top of file when this is removed
	if($.uiBackCompat===true){// Backcompat for ui-tab class (now ui-tabs-tab)
	$.widget("ui.tabs",$.ui.tabs,{_processTabs:function(){this._superApply(arguments);this._addClass(this.tabs,"ui-tab");}});}$.ui.tabs;/*!
		 * jQuery UI Tooltip 1.14.2
		 * https://jqueryui.com
		 *
		 * Copyright OpenJS Foundation and other contributors
		 * Released under the MIT license.
		 * https://jquery.org/license
		 *///>>label: Tooltip
	//>>group: Widgets
	//>>description: Shows additional information for any element on hover or focus.
	//>>docs: https://api.jqueryui.com/tooltip/
	//>>demos: https://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.14.2",options:{classes:{"ui-tooltip":"ui-corner-all ui-widget-shadow"},content:function(){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",String.prototype.trim.call(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=String.prototype.trim.call(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){// 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;}that._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);}},13);}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(){var targetElement=this._find(target);if(targetElement){this._removeTooltip(targetElement.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){// Clear the interval for delayed tracking tooltips
	clearInterval(this.delayedShow);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===true){// 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;}});}$.ui.tooltip;});return jqueryUi;}

	requireJqueryUi();

	/* Javascript plotting library for jQuery, version 0.8.3.

	Copyright (c) 2007-2014 IOLA and Ole Laursen.
	Licensed under the MIT license.

	*/

	// first an inline dependency, jquery.colorhelpers.js, we inline it here
	// for convenience

	/* Plugin for jQuery for working with colors.
	 *
	 * Version 1.1.
	 *
	 * Inspiration from jQuery color animation plugin by John Resig.
	 *
	 * Released under the MIT license by Ole Laursen, October 2009.
	 *
	 * Examples:
	 *
	 *   $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
	 *   var c = $.color.extract($("#mydiv"), 'background-color');
	 *   console.log(c.r, c.g, c.b, c.a);
	 *   $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
	 *
	 * Note that .scale() and .add() return the same modified object
	 * instead of making a new one.
	 *
	 * V. 1.1: Fix error handling so e.g. parsing an empty string does
	 * produce a color rather than just crashing.
	 */
	(function ($) {
	  $.color = {};
	  $.color.make = function (r, g, b, a) {
	    var o = {};
	    o.r = r || 0;
	    o.g = g || 0;
	    o.b = b || 0;
	    o.a = a != null ? a : 1;
	    o.add = function (c, d) {
	      for (var i = 0; i < c.length; ++i) o[c.charAt(i)] += d;
	      return o.normalize();
	    };
	    o.scale = function (c, f) {
	      for (var i = 0; i < c.length; ++i) o[c.charAt(i)] *= f;
	      return o.normalize();
	    };
	    o.toString = function () {
	      if (o.a >= 1) {
	        return "rgb(" + [o.r, o.g, o.b].join(",") + ")";
	      } else {
	        return "rgba(" + [o.r, o.g, o.b, o.a].join(",") + ")";
	      }
	    };
	    o.normalize = function () {
	      function clamp(min, value, max) {
	        return value < min ? min : value > max ? max : value;
	      }
	      o.r = clamp(0, parseInt(o.r), 255);
	      o.g = clamp(0, parseInt(o.g), 255);
	      o.b = clamp(0, parseInt(o.b), 255);
	      o.a = clamp(0, o.a, 1);
	      return o;
	    };
	    o.clone = function () {
	      return $.color.make(o.r, o.b, o.g, o.a);
	    };
	    return o.normalize();
	  };
	  $.color.extract = function (elem, css) {
	    var c;
	    do {
	      c = elem.css(css).toLowerCase();
	      if (c != "" && c != "transparent") break;
	      elem = elem.parent();
	    } while (elem.length && !$.nodeName(elem.get(0), "body"));
	    if (c == "rgba(0, 0, 0, 0)") c = "transparent";
	    return $.color.parse(c);
	  };
	  $.color.parse = function (str) {
	    var res,
	      m = $.color.make;
	    if (res = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str)) return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10));
	    if (res = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str)) return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10), parseFloat(res[4]));
	    if (res = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str)) return m(parseFloat(res[1]) * 2.55, parseFloat(res[2]) * 2.55, parseFloat(res[3]) * 2.55);
	    if (res = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str)) return m(parseFloat(res[1]) * 2.55, parseFloat(res[2]) * 2.55, parseFloat(res[3]) * 2.55, parseFloat(res[4]));
	    if (res = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str)) return m(parseInt(res[1], 16), parseInt(res[2], 16), parseInt(res[3], 16));
	    if (res = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str)) return m(parseInt(res[1] + res[1], 16), parseInt(res[2] + res[2], 16), parseInt(res[3] + res[3], 16));
	    var name = $.trim(str).toLowerCase();
	    if (name == "transparent") return m(255, 255, 255, 0);else {
	      res = lookupColors[name] || [0, 0, 0];
	      return m(res[0], res[1], res[2]);
	    }
	  };
	  var lookupColors = {
	    aqua: [0, 255, 255],
	    azure: [240, 255, 255],
	    beige: [245, 245, 220],
	    black: [0, 0, 0],
	    blue: [0, 0, 255],
	    brown: [165, 42, 42],
	    cyan: [0, 255, 255],
	    darkblue: [0, 0, 139],
	    darkcyan: [0, 139, 139],
	    darkgrey: [169, 169, 169],
	    darkgreen: [0, 100, 0],
	    darkkhaki: [189, 183, 107],
	    darkmagenta: [139, 0, 139],
	    darkolivegreen: [85, 107, 47],
	    darkorange: [255, 140, 0],
	    darkorchid: [153, 50, 204],
	    darkred: [139, 0, 0],
	    darksalmon: [233, 150, 122],
	    darkviolet: [148, 0, 211],
	    fuchsia: [255, 0, 255],
	    gold: [255, 215, 0],
	    green: [0, 128, 0],
	    indigo: [75, 0, 130],
	    khaki: [240, 230, 140],
	    lightblue: [173, 216, 230],
	    lightcyan: [224, 255, 255],
	    lightgreen: [144, 238, 144],
	    lightgrey: [211, 211, 211],
	    lightpink: [255, 182, 193],
	    lightyellow: [255, 255, 224],
	    lime: [0, 255, 0],
	    magenta: [255, 0, 255],
	    maroon: [128, 0, 0],
	    navy: [0, 0, 128],
	    olive: [128, 128, 0],
	    orange: [255, 165, 0],
	    pink: [255, 192, 203],
	    purple: [128, 0, 128],
	    violet: [128, 0, 128],
	    red: [255, 0, 0],
	    silver: [192, 192, 192],
	    white: [255, 255, 255],
	    yellow: [255, 255, 0]
	  };
	})(jQuery);

	// the actual Flot code
	(function ($) {
	  // Cache the prototype hasOwnProperty for faster access

	  var hasOwnProperty = Object.prototype.hasOwnProperty;

	  // A shim to provide 'detach' to jQuery versions prior to 1.4.  Using a DOM
	  // operation produces the same effect as detach, i.e. removing the element
	  // without touching its jQuery data.

	  // Do not merge this into Flot 0.9, since it requires jQuery 1.4.4+.

	  if (!$.fn.detach) {
	    $.fn.detach = function () {
	      return this.each(function () {
	        if (this.parentNode) {
	          this.parentNode.removeChild(this);
	        }
	      });
	    };
	  }

	  ///////////////////////////////////////////////////////////////////////////
	  // The Canvas object is a wrapper around an HTML5 <canvas> tag.
	  //
	  // @constructor
	  // @param {string} cls List of classes to apply to the canvas.
	  // @param {element} container Element onto which to append the canvas.
	  //
	  // Requiring a container is a little iffy, but unfortunately canvas
	  // operations don't work unless the canvas is attached to the DOM.

	  function Canvas(cls, container) {
	    var element = container.children("." + cls)[0];
	    if (element == null) {
	      element = document.createElement("canvas");
	      element.className = cls;
	      $(element).css({
	        direction: "ltr",
	        position: "absolute",
	        left: 0,
	        top: 0
	      }).appendTo(container);

	      // If HTML5 Canvas isn't available, fall back to [Ex|Flash]canvas

	      if (!element.getContext) {
	        if (window.G_vmlCanvasManager) {
	          element = window.G_vmlCanvasManager.initElement(element);
	        } else {
	          throw new Error("Canvas is not available. If you're using IE with a fall-back such as Excanvas, then there's either a mistake in your conditional include, or the page has no DOCTYPE and is rendering in Quirks Mode.");
	        }
	      }
	    }
	    this.element = element;
	    var context = this.context = element.getContext("2d");

	    // Determine the screen's ratio of physical to device-independent
	    // pixels.  This is the ratio between the canvas width that the browser
	    // advertises and the number of pixels actually present in that space.

	    // The iPhone 4, for example, has a device-independent width of 320px,
	    // but its screen is actually 640px wide.  It therefore has a pixel
	    // ratio of 2, while most normal devices have a ratio of 1.

	    var devicePixelRatio = window.devicePixelRatio || 1,
	      backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
	    this.pixelRatio = devicePixelRatio / backingStoreRatio;

	    // Size the canvas to match the internal dimensions of its container

	    this.resize(container.width(), container.height());

	    // Collection of HTML div layers for text overlaid onto the canvas

	    this.textContainer = null;
	    this.text = {};

	    // Cache of text fragments and metrics, so we can avoid expensively
	    // re-calculating them when the plot is re-rendered in a loop.

	    this._textCache = {};
	  }

	  // Resizes the canvas to the given dimensions.
	  //
	  // @param {number} width New width of the canvas, in pixels.
	  // @param {number} width New height of the canvas, in pixels.

	  Canvas.prototype.resize = function (width, height) {
	    if (width <= 0 || height <= 0) {
	      throw new Error("Invalid dimensions for plot, width = " + width + ", height = " + height);
	    }
	    var element = this.element,
	      context = this.context,
	      pixelRatio = this.pixelRatio;

	    // Resize the canvas, increasing its density based on the display's
	    // pixel ratio; basically giving it more pixels without increasing the
	    // size of its element, to take advantage of the fact that retina
	    // displays have that many more pixels in the same advertised space.

	    // Resizing should reset the state (excanvas seems to be buggy though)

	    if (this.width != width) {
	      element.width = width * pixelRatio;
	      element.style.width = width + "px";
	      this.width = width;
	    }
	    if (this.height != height) {
	      element.height = height * pixelRatio;
	      element.style.height = height + "px";
	      this.height = height;
	    }

	    // Save the context, so we can reset in case we get replotted.  The
	    // restore ensure that we're really back at the initial state, and
	    // should be safe even if we haven't saved the initial state yet.

	    context.restore();
	    context.save();

	    // Scale the coordinate space to match the display density; so even though we
	    // may have twice as many pixels, we still want lines and other drawing to
	    // appear at the same size; the extra pixels will just make them crisper.

	    context.scale(pixelRatio, pixelRatio);
	  };

	  // Clears the entire canvas area, not including any overlaid HTML text

	  Canvas.prototype.clear = function () {
	    this.context.clearRect(0, 0, this.width, this.height);
	  };

	  // Finishes rendering the canvas, including managing the text overlay.

	  Canvas.prototype.render = function () {
	    var cache = this._textCache;

	    // For each text layer, add elements marked as active that haven't
	    // already been rendered, and remove those that are no longer active.

	    for (var layerKey in cache) {
	      if (hasOwnProperty.call(cache, layerKey)) {
	        var layer = this.getTextLayer(layerKey),
	          layerCache = cache[layerKey];
	        layer.hide();
	        for (var styleKey in layerCache) {
	          if (hasOwnProperty.call(layerCache, styleKey)) {
	            var styleCache = layerCache[styleKey];
	            for (var key in styleCache) {
	              if (hasOwnProperty.call(styleCache, key)) {
	                var positions = styleCache[key].positions;
	                for (var i = 0, position; position = positions[i]; i++) {
	                  if (position.active) {
	                    if (!position.rendered) {
	                      layer.append(position.element);
	                      position.rendered = true;
	                    }
	                  } else {
	                    positions.splice(i--, 1);
	                    if (position.rendered) {
	                      position.element.detach();
	                    }
	                  }
	                }
	                if (positions.length == 0) {
	                  delete styleCache[key];
	                }
	              }
	            }
	          }
	        }
	        layer.show();
	      }
	    }
	  };

	  // Creates (if necessary) and returns the text overlay container.
	  //
	  // @param {string} classes String of space-separated CSS classes used to
	  //     uniquely identify the text layer.
	  // @return {object} The jQuery-wrapped text-layer div.

	  Canvas.prototype.getTextLayer = function (classes) {
	    var layer = this.text[classes];

	    // Create the text layer if it doesn't exist

	    if (layer == null) {
	      // Create the text layer container, if it doesn't exist

	      if (this.textContainer == null) {
	        this.textContainer = $("<div class='flot-text'></div>").css({
	          position: "absolute",
	          top: 0,
	          left: 0,
	          bottom: 0,
	          right: 0,
	          'font-size': "smaller",
	          color: "#545454"
	        }).insertAfter(this.element);
	      }
	      layer = this.text[classes] = $("<div></div>").addClass(classes).css({
	        position: "absolute",
	        top: 0,
	        left: 0,
	        bottom: 0,
	        right: 0
	      }).appendTo(this.textContainer);
	    }
	    return layer;
	  };

	  // Creates (if necessary) and returns a text info object.
	  //
	  // The object looks like this:
	  //
	  // {
	  //     width: Width of the text's wrapper div.
	  //     height: Height of the text's wrapper div.
	  //     element: The jQuery-wrapped HTML div containing the text.
	  //     positions: Array of positions at which this text is drawn.
	  // }
	  //
	  // The positions array contains objects that look like this:
	  //
	  // {
	  //     active: Flag indicating whether the text should be visible.
	  //     rendered: Flag indicating whether the text is currently visible.
	  //     element: The jQuery-wrapped HTML div containing the text.
	  //     x: X coordinate at which to draw the text.
	  //     y: Y coordinate at which to draw the text.
	  // }
	  //
	  // Each position after the first receives a clone of the original element.
	  //
	  // The idea is that that the width, height, and general 'identity' of the
	  // text is constant no matter where it is placed; the placements are a
	  // secondary property.
	  //
	  // Canvas maintains a cache of recently-used text info objects; getTextInfo
	  // either returns the cached element or creates a new entry.
	  //
	  // @param {string} layer A string of space-separated CSS classes uniquely
	  //     identifying the layer containing this text.
	  // @param {string} text Text string to retrieve info for.
	  // @param {(string|object)=} font Either a string of space-separated CSS
	  //     classes or a font-spec object, defining the text's font and style.
	  // @param {number=} angle Angle at which to rotate the text, in degrees.
	  //     Angle is currently unused, it will be implemented in the future.
	  // @param {number=} width Maximum width of the text before it wraps.
	  // @return {object} a text info object.

	  Canvas.prototype.getTextInfo = function (layer, text, font, angle, width) {
	    var textStyle, layerCache, styleCache, info;

	    // Cast the value to a string, in case we were given a number or such

	    text = "" + text;

	    // If the font is a font-spec object, generate a CSS font definition

	    if (typeof font === "object") {
	      textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px/" + font.lineHeight + "px " + font.family;
	    } else {
	      textStyle = font;
	    }

	    // Retrieve (or create) the cache for the text's layer and styles

	    layerCache = this._textCache[layer];
	    if (layerCache == null) {
	      layerCache = this._textCache[layer] = {};
	    }
	    styleCache = layerCache[textStyle];
	    if (styleCache == null) {
	      styleCache = layerCache[textStyle] = {};
	    }
	    info = styleCache[text];

	    // If we can't find a matching element in our cache, create a new one

	    if (info == null) {
	      var element = $("<div></div>").html(text).css({
	        position: "absolute",
	        'max-width': width,
	        top: -9999
	      }).appendTo(this.getTextLayer(layer));
	      if (typeof font === "object") {
	        element.css({
	          font: textStyle,
	          color: font.color
	        });
	      } else if (typeof font === "string") {
	        element.addClass(font);
	      }
	      info = styleCache[text] = {
	        width: element.outerWidth(true),
	        height: element.outerHeight(true),
	        element: element,
	        positions: []
	      };
	      element.detach();
	    }
	    return info;
	  };

	  // Adds a text string to the canvas text overlay.
	  //
	  // The text isn't drawn immediately; it is marked as rendering, which will
	  // result in its addition to the canvas on the next render pass.
	  //
	  // @param {string} layer A string of space-separated CSS classes uniquely
	  //     identifying the layer containing this text.
	  // @param {number} x X coordinate at which to draw the text.
	  // @param {number} y Y coordinate at which to draw the text.
	  // @param {string} text Text string to draw.
	  // @param {(string|object)=} font Either a string of space-separated CSS
	  //     classes or a font-spec object, defining the text's font and style.
	  // @param {number=} angle Angle at which to rotate the text, in degrees.
	  //     Angle is currently unused, it will be implemented in the future.
	  // @param {number=} width Maximum width of the text before it wraps.
	  // @param {string=} halign Horizontal alignment of the text; either "left",
	  //     "center" or "right".
	  // @param {string=} valign Vertical alignment of the text; either "top",
	  //     "middle" or "bottom".

	  Canvas.prototype.addText = function (layer, x, y, text, font, angle, width, halign, valign) {
	    var info = this.getTextInfo(layer, text, font, angle, width),
	      positions = info.positions;

	    // Tweak the div's position to match the text's alignment

	    if (halign == "center") {
	      x -= info.width / 2;
	    } else if (halign == "right") {
	      x -= info.width;
	    }
	    if (valign == "middle") {
	      y -= info.height / 2;
	    } else if (valign == "bottom") {
	      y -= info.height;
	    }

	    // Determine whether this text already exists at this position.
	    // If so, mark it for inclusion in the next render pass.

	    for (var i = 0, position; position = positions[i]; i++) {
	      if (position.x == x && position.y == y) {
	        position.active = true;
	        return;
	      }
	    }

	    // If the text doesn't exist at this position, create a new entry

	    // For the very first position we'll re-use the original element,
	    // while for subsequent ones we'll clone it.

	    position = {
	      active: true,
	      rendered: false,
	      element: positions.length ? info.element.clone() : info.element,
	      x: x,
	      y: y
	    };
	    positions.push(position);

	    // Move the element to its final position within the container

	    position.element.css({
	      top: Math.round(y),
	      left: Math.round(x),
	      'text-align': halign // In case the text wraps
	    });
	  };

	  // Removes one or more text strings from the canvas text overlay.
	  //
	  // If no parameters are given, all text within the layer is removed.
	  //
	  // Note that the text is not immediately removed; it is simply marked as
	  // inactive, which will result in its removal on the next render pass.
	  // This avoids the performance penalty for 'clear and redraw' behavior,
	  // where we potentially get rid of all text on a layer, but will likely
	  // add back most or all of it later, as when redrawing axes, for example.
	  //
	  // @param {string} layer A string of space-separated CSS classes uniquely
	  //     identifying the layer containing this text.
	  // @param {number=} x X coordinate of the text.
	  // @param {number=} y Y coordinate of the text.
	  // @param {string=} text Text string to remove.
	  // @param {(string|object)=} font Either a string of space-separated CSS
	  //     classes or a font-spec object, defining the text's font and style.
	  // @param {number=} angle Angle at which the text is rotated, in degrees.
	  //     Angle is currently unused, it will be implemented in the future.

	  Canvas.prototype.removeText = function (layer, x, y, text, font, angle) {
	    if (text == null) {
	      var layerCache = this._textCache[layer];
	      if (layerCache != null) {
	        for (var styleKey in layerCache) {
	          if (hasOwnProperty.call(layerCache, styleKey)) {
	            var styleCache = layerCache[styleKey];
	            for (var key in styleCache) {
	              if (hasOwnProperty.call(styleCache, key)) {
	                var positions = styleCache[key].positions;
	                for (var i = 0, position; position = positions[i]; i++) {
	                  position.active = false;
	                }
	              }
	            }
	          }
	        }
	      }
	    } else {
	      var positions = this.getTextInfo(layer, text, font, angle).positions;
	      for (var i = 0, position; position = positions[i]; i++) {
	        if (position.x == x && position.y == y) {
	          position.active = false;
	        }
	      }
	    }
	  };

	  ///////////////////////////////////////////////////////////////////////////
	  // The top-level container for the entire plot.

	  function Plot(placeholder, data_, options_, plugins) {
	    // data is on the form:
	    //   [ series1, series2 ... ]
	    // where series is either just the data as [ [x1, y1], [x2, y2], ... ]
	    // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... }

	    var series = [],
	      options = {
	        // the color theme used for graphs
	        colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"],
	        legend: {
	          show: true,
	          noColumns: 1,
	          // number of colums in legend table
	          labelFormatter: null,
	          // fn: string -> string
	          labelBoxBorderColor: "#ccc",
	          // border color for the little label boxes
	          container: null,
	          // container (as jQuery object) to put legend in, null means default on top of graph
	          position: "ne",
	          // position of default legend container within plot
	          margin: 5,
	          // distance from grid edge to default legend container within plot
	          backgroundColor: null,
	          // null means auto-detect
	          backgroundOpacity: 0.85,
	          // set to 0 to avoid background
	          sorted: null // default to no legend sorting
	        },
	        xaxis: {
	          show: null,
	          // null = auto-detect, true = always, false = never
	          position: "bottom",
	          // or "top"
	          mode: null,
	          // null or "time"
	          font: null,
	          // null (derived from CSS in placeholder) or object like { size: 11, lineHeight: 13, style: "italic", weight: "bold", family: "sans-serif", variant: "small-caps" }
	          color: null,
	          // base color, labels, ticks
	          tickColor: null,
	          // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)"
	          transform: null,
	          // null or f: number -> number to transform axis
	          inverseTransform: null,
	          // if transform is set, this should be the inverse function
	          min: null,
	          // min. value to show, null means set automatically
	          max: null,
	          // max. value to show, null means set automatically
	          autoscaleMargin: null,
	          // margin in % to add if auto-setting min/max
	          ticks: null,
	          // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks
	          tickFormatter: null,
	          // fn: number -> string
	          labelWidth: null,
	          // size of tick labels in pixels
	          labelHeight: null,
	          reserveSpace: null,
	          // whether to reserve space even if axis isn't shown
	          tickLength: null,
	          // size in pixels of ticks, or "full" for whole line
	          alignTicksWithAxis: null,
	          // axis number or null for no sync
	          tickDecimals: null,
	          // no. of decimals, null means auto
	          tickSize: null,
	          // number or [number, "unit"]
	          minTickSize: null // number or [number, "unit"]
	        },
	        yaxis: {
	          autoscaleMargin: 0.02,
	          position: "left" // or "right"
	        },
	        xaxes: [],
	        yaxes: [],
	        series: {
	          points: {
	            show: false,
	            radius: 3,
	            lineWidth: 2,
	            // in pixels
	            fill: true,
	            fillColor: "#ffffff",
	            symbol: "circle" // or callback
	          },
	          lines: {
	            // we don't put in show: false so we can see
	            // whether lines were actively disabled
	            lineWidth: 2,
	            // in pixels
	            fill: false,
	            fillColor: null,
	            steps: false
	            // Omit 'zero', so we can later default its value to
	            // match that of the 'fill' option.
	          },
	          bars: {
	            show: false,
	            lineWidth: 2,
	            // in pixels
	            barWidth: 1,
	            // in units of the x axis
	            fill: true,
	            fillColor: null,
	            align: "left",
	            // "left", "right", or "center"
	            horizontal: false,
	            zero: true
	          },
	          shadowSize: 3,
	          highlightColor: null
	        },
	        grid: {
	          show: true,
	          aboveData: false,
	          color: "#545454",
	          // primary color used for outline and labels
	          backgroundColor: null,
	          // null for transparent, else color
	          borderColor: null,
	          // set if different from the grid color
	          tickColor: null,
	          // color for the ticks, e.g. "rgba(0,0,0,0.15)"
	          margin: 0,
	          // distance from the canvas edge to the grid
	          labelMargin: 5,
	          // in pixels
	          axisMargin: 8,
	          // in pixels
	          borderWidth: 2,
	          // in pixels
	          minBorderMargin: null,
	          // in pixels, null means taken from points radius
	          markings: null,
	          // array of ranges or fn: axes -> array of ranges
	          markingsColor: "#f4f4f4",
	          markingsLineWidth: 2,
	          // interactive stuff
	          clickable: false,
	          hoverable: false,
	          autoHighlight: true,
	          // highlight in case mouse is near
	          mouseActiveRadius: 10 // how far the mouse can be away to activate an item
	        },
	        interaction: {
	          redrawOverlayInterval: 1000 / 60 // time between updates, -1 means in same flow
	        },
	        hooks: {}
	      },
	      surface = null,
	      // the canvas for the plot itself
	      overlay = null,
	      // canvas for interactive stuff on top of plot
	      eventHolder = null,
	      // jQuery object that events should be bound to
	      ctx = null,
	      octx = null,
	      xaxes = [],
	      yaxes = [],
	      plotOffset = {
	        left: 0,
	        right: 0,
	        top: 0,
	        bottom: 0
	      },
	      plotWidth = 0,
	      plotHeight = 0,
	      hooks = {
	        processOptions: [],
	        processRawData: [],
	        processDatapoints: [],
	        processOffset: [],
	        drawBackground: [],
	        drawSeries: [],
	        draw: [],
	        bindEvents: [],
	        drawOverlay: [],
	        shutdown: []
	      },
	      plot = this;

	    // public functions
	    plot.setData = setData;
	    plot.setupGrid = setupGrid;
	    plot.draw = draw;
	    plot.getPlaceholder = function () {
	      return placeholder;
	    };
	    plot.getCanvas = function () {
	      return surface.element;
	    };
	    plot.getPlotOffset = function () {
	      return plotOffset;
	    };
	    plot.width = function () {
	      return plotWidth;
	    };
	    plot.height = function () {
	      return plotHeight;
	    };
	    plot.offset = function () {
	      var o = eventHolder.offset();
	      o.left += plotOffset.left;
	      o.top += plotOffset.top;
	      return o;
	    };
	    plot.getData = function () {
	      return series;
	    };
	    plot.getAxes = function () {
	      var res = {};
	      $.each(xaxes.concat(yaxes), function (_, axis) {
	        if (axis) res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis;
	      });
	      return res;
	    };
	    plot.getXAxes = function () {
	      return xaxes;
	    };
	    plot.getYAxes = function () {
	      return yaxes;
	    };
	    plot.c2p = canvasToAxisCoords;
	    plot.p2c = axisToCanvasCoords;
	    plot.getOptions = function () {
	      return options;
	    };
	    plot.highlight = highlight;
	    plot.unhighlight = unhighlight;
	    plot.triggerRedrawOverlay = triggerRedrawOverlay;
	    plot.pointOffset = function (point) {
	      return {
	        left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left, 10),
	        top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top, 10)
	      };
	    };
	    plot.shutdown = shutdown;
	    plot.destroy = function () {
	      shutdown();
	      placeholder.removeData("plot").empty();
	      series = [];
	      options = null;
	      surface = null;
	      overlay = null;
	      eventHolder = null;
	      ctx = null;
	      octx = null;
	      xaxes = [];
	      yaxes = [];
	      hooks = null;
	      highlights = [];
	      plot = null;
	    };
	    plot.resize = function () {
	      var width = placeholder.width(),
	        height = placeholder.height();
	      surface.resize(width, height);
	      overlay.resize(width, height);
	    };

	    // public attributes
	    plot.hooks = hooks;

	    // initialize
	    initPlugins();
	    parseOptions(options_);
	    setupCanvases();
	    setData(data_);
	    setupGrid();
	    draw();
	    bindEvents();
	    function executeHooks(hook, args) {
	      args = [plot].concat(args);
	      for (var i = 0; i < hook.length; ++i) hook[i].apply(this, args);
	    }
	    function initPlugins() {
	      // References to key classes, allowing plugins to modify them

	      var classes = {
	        Canvas: Canvas
	      };
	      for (var i = 0; i < plugins.length; ++i) {
	        var p = plugins[i];
	        p.init(plot, classes);
	        if (p.options) $.extend(true, options, p.options);
	      }
	    }
	    function parseOptions(opts) {
	      $.extend(true, options, opts);

	      // $.extend merges arrays, rather than replacing them.  When less
	      // colors are provided than the size of the default palette, we
	      // end up with those colors plus the remaining defaults, which is
	      // not expected behavior; avoid it by replacing them here.

	      if (opts && opts.colors) {
	        options.colors = opts.colors;
	      }
	      if (options.xaxis.color == null) options.xaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
	      if (options.yaxis.color == null) options.yaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
	      if (options.xaxis.tickColor == null)
	        // grid.tickColor for back-compatibility
	        options.xaxis.tickColor = options.grid.tickColor || options.xaxis.color;
	      if (options.yaxis.tickColor == null)
	        // grid.tickColor for back-compatibility
	        options.yaxis.tickColor = options.grid.tickColor || options.yaxis.color;
	      if (options.grid.borderColor == null) options.grid.borderColor = options.grid.color;
	      if (options.grid.tickColor == null) options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString();

	      // Fill in defaults for axis options, including any unspecified
	      // font-spec fields, if a font-spec was provided.

	      // If no x/y axis options were provided, create one of each anyway,
	      // since the rest of the code assumes that they exist.

	      var i,
	        axisOptions,
	        axisCount,
	        fontSize = placeholder.css("font-size"),
	        fontSizeDefault = fontSize ? +fontSize.replace("px", "") : 13,
	        fontDefaults = {
	          style: placeholder.css("font-style"),
	          size: Math.round(0.8 * fontSizeDefault),
	          variant: placeholder.css("font-variant"),
	          weight: placeholder.css("font-weight"),
	          family: placeholder.css("font-family")
	        };
	      axisCount = options.xaxes.length || 1;
	      for (i = 0; i < axisCount; ++i) {
	        axisOptions = options.xaxes[i];
	        if (axisOptions && !axisOptions.tickColor) {
	          axisOptions.tickColor = axisOptions.color;
	        }
	        axisOptions = $.extend(true, {}, options.xaxis, axisOptions);
	        options.xaxes[i] = axisOptions;
	        if (axisOptions.font) {
	          axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
	          if (!axisOptions.font.color) {
	            axisOptions.font.color = axisOptions.color;
	          }
	          if (!axisOptions.font.lineHeight) {
	            axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15);
	          }
	        }
	      }
	      axisCount = options.yaxes.length || 1;
	      for (i = 0; i < axisCount; ++i) {
	        axisOptions = options.yaxes[i];
	        if (axisOptions && !axisOptions.tickColor) {
	          axisOptions.tickColor = axisOptions.color;
	        }
	        axisOptions = $.extend(true, {}, options.yaxis, axisOptions);
	        options.yaxes[i] = axisOptions;
	        if (axisOptions.font) {
	          axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
	          if (!axisOptions.font.color) {
	            axisOptions.font.color = axisOptions.color;
	          }
	          if (!axisOptions.font.lineHeight) {
	            axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15);
	          }
	        }
	      }

	      // backwards compatibility, to be removed in future
	      if (options.xaxis.noTicks && options.xaxis.ticks == null) options.xaxis.ticks = options.xaxis.noTicks;
	      if (options.yaxis.noTicks && options.yaxis.ticks == null) options.yaxis.ticks = options.yaxis.noTicks;
	      if (options.x2axis) {
	        options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis);
	        options.xaxes[1].position = "top";
	        // Override the inherit to allow the axis to auto-scale
	        if (options.x2axis.min == null) {
	          options.xaxes[1].min = null;
	        }
	        if (options.x2axis.max == null) {
	          options.xaxes[1].max = null;
	        }
	      }
	      if (options.y2axis) {
	        options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis);
	        options.yaxes[1].position = "right";
	        // Override the inherit to allow the axis to auto-scale
	        if (options.y2axis.min == null) {
	          options.yaxes[1].min = null;
	        }
	        if (options.y2axis.max == null) {
	          options.yaxes[1].max = null;
	        }
	      }
	      if (options.grid.coloredAreas) options.grid.markings = options.grid.coloredAreas;
	      if (options.grid.coloredAreasColor) options.grid.markingsColor = options.grid.coloredAreasColor;
	      if (options.lines) $.extend(true, options.series.lines, options.lines);
	      if (options.points) $.extend(true, options.series.points, options.points);
	      if (options.bars) $.extend(true, options.series.bars, options.bars);
	      if (options.shadowSize != null) options.series.shadowSize = options.shadowSize;
	      if (options.highlightColor != null) options.series.highlightColor = options.highlightColor;

	      // save options on axes for future reference
	      for (i = 0; i < options.xaxes.length; ++i) getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i];
	      for (i = 0; i < options.yaxes.length; ++i) getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i];

	      // add hooks from options
	      for (var n in hooks) if (options.hooks[n] && options.hooks[n].length) hooks[n] = hooks[n].concat(options.hooks[n]);
	      executeHooks(hooks.processOptions, [options]);
	    }
	    function setData(d) {
	      series = parseData(d);
	      fillInSeriesOptions();
	      processData();
	    }
	    function parseData(d) {
	      var res = [];
	      for (var i = 0; i < d.length; ++i) {
	        var s = $.extend(true, {}, options.series);
	        if (d[i].data != null) {
	          s.data = d[i].data; // move the data instead of deep-copy
	          delete d[i].data;
	          $.extend(true, s, d[i]);
	          d[i].data = s.data;
	        } else s.data = d[i];
	        res.push(s);
	      }
	      return res;
	    }
	    function axisNumber(obj, coord) {
	      var a = obj[coord + "axis"];
	      if (typeof a == "object")
	        // if we got a real axis, extract number
	        a = a.n;
	      if (typeof a != "number") a = 1; // default to first axis
	      return a;
	    }
	    function allAxes() {
	      // return flat array without annoying null entries
	      return $.grep(xaxes.concat(yaxes), function (a) {
	        return a;
	      });
	    }
	    function canvasToAxisCoords(pos) {
	      // return an object with x/y corresponding to all used axes
	      var res = {},
	        i,
	        axis;
	      for (i = 0; i < xaxes.length; ++i) {
	        axis = xaxes[i];
	        if (axis && axis.used) res["x" + axis.n] = axis.c2p(pos.left);
	      }
	      for (i = 0; i < yaxes.length; ++i) {
	        axis = yaxes[i];
	        if (axis && axis.used) res["y" + axis.n] = axis.c2p(pos.top);
	      }
	      if (res.x1 !== undefined) res.x = res.x1;
	      if (res.y1 !== undefined) res.y = res.y1;
	      return res;
	    }
	    function axisToCanvasCoords(pos) {
	      // get canvas coords from the first pair of x/y found in pos
	      var res = {},
	        i,
	        axis,
	        key;
	      for (i = 0; i < xaxes.length; ++i) {
	        axis = xaxes[i];
	        if (axis && axis.used) {
	          key = "x" + axis.n;
	          if (pos[key] == null && axis.n == 1) key = "x";
	          if (pos[key] != null) {
	            res.left = axis.p2c(pos[key]);
	            break;
	          }
	        }
	      }
	      for (i = 0; i < yaxes.length; ++i) {
	        axis = yaxes[i];
	        if (axis && axis.used) {
	          key = "y" + axis.n;
	          if (pos[key] == null && axis.n == 1) key = "y";
	          if (pos[key] != null) {
	            res.top = axis.p2c(pos[key]);
	            break;
	          }
	        }
	      }
	      return res;
	    }
	    function getOrCreateAxis(axes, number) {
	      if (!axes[number - 1]) axes[number - 1] = {
	        n: number,
	        // save the number for future reference
	        direction: axes == xaxes ? "x" : "y",
	        options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis)
	      };
	      return axes[number - 1];
	    }
	    function fillInSeriesOptions() {
	      var neededColors = series.length,
	        maxIndex = -1,
	        i;

	      // Subtract the number of series that already have fixed colors or
	      // color indexes from the number that we still need to generate.

	      for (i = 0; i < series.length; ++i) {
	        var sc = series[i].color;
	        if (sc != null) {
	          neededColors--;
	          if (typeof sc == "number" && sc > maxIndex) {
	            maxIndex = sc;
	          }
	        }
	      }

	      // If any of the series have fixed color indexes, then we need to
	      // generate at least as many colors as the highest index.

	      if (neededColors <= maxIndex) {
	        neededColors = maxIndex + 1;
	      }

	      // Generate all the colors, using first the option colors and then
	      // variations on those colors once they're exhausted.

	      var c,
	        colors = [],
	        colorPool = options.colors,
	        colorPoolSize = colorPool.length,
	        variation = 0;
	      for (i = 0; i < neededColors; i++) {
	        c = $.color.parse(colorPool[i % colorPoolSize] || "#666");

	        // Each time we exhaust the colors in the pool we adjust
	        // a scaling factor used to produce more variations on
	        // those colors. The factor alternates negative/positive
	        // to produce lighter/darker colors.

	        // Reset the variation after every few cycles, or else
	        // it will end up producing only white or black colors.

	        if (i % colorPoolSize == 0 && i) {
	          if (variation >= 0) {
	            if (variation < 0.5) {
	              variation = -variation - 0.2;
	            } else variation = 0;
	          } else variation = -variation;
	        }
	        colors[i] = c.scale('rgb', 1 + variation);
	      }

	      // Finalize the series options, filling in their colors

	      var colori = 0,
	        s;
	      for (i = 0; i < series.length; ++i) {
	        s = series[i];

	        // assign colors
	        if (s.color == null) {
	          s.color = colors[colori].toString();
	          ++colori;
	        } else if (typeof s.color == "number") s.color = colors[s.color].toString();

	        // turn on lines automatically in case nothing is set
	        if (s.lines.show == null) {
	          var v,
	            show = true;
	          for (v in s) if (s[v] && s[v].show) {
	            show = false;
	            break;
	          }
	          if (show) s.lines.show = true;
	        }

	        // If nothing was provided for lines.zero, default it to match
	        // lines.fill, since areas by default should extend to zero.

	        if (s.lines.zero == null) {
	          s.lines.zero = !!s.lines.fill;
	        }

	        // setup axes
	        s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x"));
	        s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y"));
	      }
	    }
	    function processData() {
	      var topSentry = Number.POSITIVE_INFINITY,
	        bottomSentry = Number.NEGATIVE_INFINITY,
	        fakeInfinity = Number.MAX_VALUE,
	        i,
	        j,
	        k,
	        m,
	        s,
	        points,
	        ps,
	        val,
	        f,
	        p,
	        data,
	        format;
	      function updateAxis(axis, min, max) {
	        if (min < axis.datamin && min != -fakeInfinity) axis.datamin = min;
	        if (max > axis.datamax && max != fakeInfinity) axis.datamax = max;
	      }
	      $.each(allAxes(), function (_, axis) {
	        // init axis
	        axis.datamin = topSentry;
	        axis.datamax = bottomSentry;
	        axis.used = false;
	      });
	      for (i = 0; i < series.length; ++i) {
	        s = series[i];
	        s.datapoints = {
	          points: []
	        };
	        executeHooks(hooks.processRawData, [s, s.data, s.datapoints]);
	      }

	      // first pass: clean and copy data
	      for (i = 0; i < series.length; ++i) {
	        s = series[i];
	        data = s.data;
	        format = s.datapoints.format;
	        if (!format) {
	          format = [];
	          // find out how to copy
	          format.push({
	            x: true,
	            number: true,
	            required: true
	          });
	          format.push({
	            y: true,
	            number: true,
	            required: true
	          });
	          if (s.bars.show || s.lines.show && s.lines.fill) {
	            var autoscale = !!(s.bars.show && s.bars.zero || s.lines.show && s.lines.zero);
	            format.push({
	              y: true,
	              number: true,
	              required: false,
	              defaultValue: 0,
	              autoscale: autoscale
	            });
	            if (s.bars.horizontal) {
	              delete format[format.length - 1].y;
	              format[format.length - 1].x = true;
	            }
	          }
	          s.datapoints.format = format;
	        }
	        if (s.datapoints.pointsize != null) continue; // already filled in

	        s.datapoints.pointsize = format.length;
	        ps = s.datapoints.pointsize;
	        points = s.datapoints.points;
	        var insertSteps = s.lines.show && s.lines.steps;
	        s.xaxis.used = s.yaxis.used = true;
	        for (j = k = 0; j < data.length; ++j, k += ps) {
	          p = data[j];
	          var nullify = p == null;
	          if (!nullify) {
	            for (m = 0; m < ps; ++m) {
	              val = p[m];
	              f = format[m];
	              if (f) {
	                if (f.number && val != null) {
	                  val = +val; // convert to number
	                  if (isNaN(val)) val = null;else if (val == Infinity) val = fakeInfinity;else if (val == -Infinity) val = -fakeInfinity;
	                }
	                if (val == null) {
	                  if (f.required) nullify = true;
	                  if (f.defaultValue != null) val = f.defaultValue;
	                }
	              }
	              points[k + m] = val;
	            }
	          }
	          if (nullify) {
	            for (m = 0; m < ps; ++m) {
	              val = points[k + m];
	              if (val != null) {
	                f = format[m];
	                // extract min/max info
	                if (f.autoscale !== false) {
	                  if (f.x) {
	                    updateAxis(s.xaxis, val, val);
	                  }
	                  if (f.y) {
	                    updateAxis(s.yaxis, val, val);
	                  }
	                }
	              }
	              points[k + m] = null;
	            }
	          } else {
	            // a little bit of line specific stuff that
	            // perhaps shouldn't be here, but lacking
	            // better means...
	            if (insertSteps && k > 0 && points[k - ps] != null && points[k - ps] != points[k] && points[k - ps + 1] != points[k + 1]) {
	              // copy the point to make room for a middle point
	              for (m = 0; m < ps; ++m) points[k + ps + m] = points[k + m];

	              // middle point has same y
	              points[k + 1] = points[k - ps + 1];

	              // we've added a point, better reflect that
	              k += ps;
	            }
	          }
	        }
	      }

	      // give the hooks a chance to run
	      for (i = 0; i < series.length; ++i) {
	        s = series[i];
	        executeHooks(hooks.processDatapoints, [s, s.datapoints]);
	      }

	      // second pass: find datamax/datamin for auto-scaling
	      for (i = 0; i < series.length; ++i) {
	        s = series[i];
	        points = s.datapoints.points;
	        ps = s.datapoints.pointsize;
	        format = s.datapoints.format;
	        var xmin = topSentry,
	          ymin = topSentry,
	          xmax = bottomSentry,
	          ymax = bottomSentry;
	        for (j = 0; j < points.length; j += ps) {
	          if (points[j] == null) continue;
	          for (m = 0; m < ps; ++m) {
	            val = points[j + m];
	            f = format[m];
	            if (!f || f.autoscale === false || val == fakeInfinity || val == -fakeInfinity) continue;
	            if (f.x) {
	              if (val < xmin) xmin = val;
	              if (val > xmax) xmax = val;
	            }
	            if (f.y) {
	              if (val < ymin) ymin = val;
	              if (val > ymax) ymax = val;
	            }
	          }
	        }
	        if (s.bars.show) {
	          // make sure we got room for the bar on the dancing floor
	          var delta;
	          switch (s.bars.align) {
	            case "left":
	              delta = 0;
	              break;
	            case "right":
	              delta = -s.bars.barWidth;
	              break;
	            default:
	              delta = -s.bars.barWidth / 2;
	          }
	          if (s.bars.horizontal) {
	            ymin += delta;
	            ymax += delta + s.bars.barWidth;
	          } else {
	            xmin += delta;
	            xmax += delta + s.bars.barWidth;
	          }
	        }
	        updateAxis(s.xaxis, xmin, xmax);
	        updateAxis(s.yaxis, ymin, ymax);
	      }
	      $.each(allAxes(), function (_, axis) {
	        if (axis.datamin == topSentry) axis.datamin = null;
	        if (axis.datamax == bottomSentry) axis.datamax = null;
	      });
	    }
	    function setupCanvases() {
	      // Make sure the placeholder is clear of everything except canvases
	      // from a previous plot in this container that we'll try to re-use.

	      placeholder.css("padding", 0) // padding messes up the positioning
	      .children().filter(function () {
	        return !$(this).hasClass("flot-overlay") && !$(this).hasClass('flot-base');
	      }).remove();
	      if (placeholder.css("position") == 'static') placeholder.css("position", "relative"); // for positioning labels and overlay

	      surface = new Canvas("flot-base", placeholder);
	      overlay = new Canvas("flot-overlay", placeholder); // overlay canvas for interactive features

	      ctx = surface.context;
	      octx = overlay.context;

	      // define which element we're listening for events on
	      eventHolder = $(overlay.element).unbind();

	      // If we're re-using a plot object, shut down the old one

	      var existing = placeholder.data("plot");
	      if (existing) {
	        existing.shutdown();
	        overlay.clear();
	      }

	      // save in case we get replotted
	      placeholder.data("plot", plot);
	    }
	    function bindEvents() {
	      // bind events
	      if (options.grid.hoverable) {
	        eventHolder.mousemove(onMouseMove);

	        // Use bind, rather than .mouseleave, because we officially
	        // still support jQuery 1.2.6, which doesn't define a shortcut
	        // for mouseenter or mouseleave.  This was a bug/oversight that
	        // was fixed somewhere around 1.3.x.  We can return to using
	        // .mouseleave when we drop support for 1.2.6.

	        eventHolder.bind("mouseleave", onMouseLeave);
	      }
	      if (options.grid.clickable) eventHolder.click(onClick);
	      executeHooks(hooks.bindEvents, [eventHolder]);
	    }
	    function shutdown() {
	      if (redrawTimeout) clearTimeout(redrawTimeout);
	      eventHolder.unbind("mousemove", onMouseMove);
	      eventHolder.unbind("mouseleave", onMouseLeave);
	      eventHolder.unbind("click", onClick);
	      executeHooks(hooks.shutdown, [eventHolder]);
	    }
	    function setTransformationHelpers(axis) {
	      // set helper functions on the axis, assumes plot area
	      // has been computed already

	      function identity(x) {
	        return x;
	      }
	      var s,
	        m,
	        t = axis.options.transform || identity,
	        it = axis.options.inverseTransform;

	      // precompute how much the axis is scaling a point
	      // in canvas space
	      if (axis.direction == "x") {
	        s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min));
	        m = Math.min(t(axis.max), t(axis.min));
	      } else {
	        s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min));
	        s = -s;
	        m = Math.max(t(axis.max), t(axis.min));
	      }

	      // data point to canvas coordinate
	      if (t == identity)
	        // slight optimization
	        axis.p2c = function (p) {
	          return (p - m) * s;
	        };else axis.p2c = function (p) {
	        return (t(p) - m) * s;
	      };
	      // canvas coordinate to data point
	      if (!it) axis.c2p = function (c) {
	        return m + c / s;
	      };else axis.c2p = function (c) {
	        return it(m + c / s);
	      };
	    }
	    function measureTickLabels(axis) {
	      var opts = axis.options,
	        ticks = axis.ticks || [],
	        labelWidth = opts.labelWidth || 0,
	        labelHeight = opts.labelHeight || 0,
	        maxWidth = labelWidth || (axis.direction == "x" ? Math.floor(surface.width / (ticks.length || 1)) : null),
	        legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis",
	        layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles,
	        font = opts.font || "flot-tick-label tickLabel";
	      for (var i = 0; i < ticks.length; ++i) {
	        var t = ticks[i];
	        if (!t.label) continue;
	        var info = surface.getTextInfo(layer, t.label, font, null, maxWidth);
	        labelWidth = Math.max(labelWidth, info.width);
	        labelHeight = Math.max(labelHeight, info.height);
	      }
	      axis.labelWidth = opts.labelWidth || labelWidth;
	      axis.labelHeight = opts.labelHeight || labelHeight;
	    }
	    function allocateAxisBoxFirstPhase(axis) {
	      // find the bounding box of the axis by looking at label
	      // widths/heights and ticks, make room by diminishing the
	      // plotOffset; this first phase only looks at one
	      // dimension per axis, the other dimension depends on the
	      // other axes so will have to wait

	      var lw = axis.labelWidth,
	        lh = axis.labelHeight,
	        pos = axis.options.position,
	        isXAxis = axis.direction === "x",
	        tickLength = axis.options.tickLength,
	        axisMargin = options.grid.axisMargin,
	        padding = options.grid.labelMargin,
	        innermost = true,
	        outermost = true,
	        first = true,
	        found = false;

	      // Determine the axis's position in its direction and on its side

	      $.each(isXAxis ? xaxes : yaxes, function (i, a) {
	        if (a && (a.show || a.reserveSpace)) {
	          if (a === axis) {
	            found = true;
	          } else if (a.options.position === pos) {
	            if (found) {
	              outermost = false;
	            } else {
	              innermost = false;
	            }
	          }
	          if (!found) {
	            first = false;
	          }
	        }
	      });

	      // The outermost axis on each side has no margin

	      if (outermost) {
	        axisMargin = 0;
	      }

	      // The ticks for the first axis in each direction stretch across

	      if (tickLength == null) {
	        tickLength = first ? "full" : 5;
	      }
	      if (!isNaN(+tickLength)) padding += +tickLength;
	      if (isXAxis) {
	        lh += padding;
	        if (pos == "bottom") {
	          plotOffset.bottom += lh + axisMargin;
	          axis.box = {
	            top: surface.height - plotOffset.bottom,
	            height: lh
	          };
	        } else {
	          axis.box = {
	            top: plotOffset.top + axisMargin,
	            height: lh
	          };
	          plotOffset.top += lh + axisMargin;
	        }
	      } else {
	        lw += padding;
	        if (pos == "left") {
	          axis.box = {
	            left: plotOffset.left + axisMargin,
	            width: lw
	          };
	          plotOffset.left += lw + axisMargin;
	        } else {
	          plotOffset.right += lw + axisMargin;
	          axis.box = {
	            left: surface.width - plotOffset.right,
	            width: lw
	          };
	        }
	      }

	      // save for future reference
	      axis.position = pos;
	      axis.tickLength = tickLength;
	      axis.box.padding = padding;
	      axis.innermost = innermost;
	    }
	    function allocateAxisBoxSecondPhase(axis) {
	      // now that all axis boxes have been placed in one
	      // dimension, we can set the remaining dimension coordinates
	      if (axis.direction == "x") {
	        axis.box.left = plotOffset.left - axis.labelWidth / 2;
	        axis.box.width = surface.width - plotOffset.left - plotOffset.right + axis.labelWidth;
	      } else {
	        axis.box.top = plotOffset.top - axis.labelHeight / 2;
	        axis.box.height = surface.height - plotOffset.bottom - plotOffset.top + axis.labelHeight;
	      }
	    }
	    function adjustLayoutForThingsStickingOut() {
	      // possibly adjust plot offset to ensure everything stays
	      // inside the canvas and isn't clipped off

	      var minMargin = options.grid.minBorderMargin,
	        i;

	      // check stuff from the plot (FIXME: this should just read
	      // a value from the series, otherwise it's impossible to
	      // customize)
	      if (minMargin == null) {
	        minMargin = 0;
	        for (i = 0; i < series.length; ++i) minMargin = Math.max(minMargin, 2 * (series[i].points.radius + series[i].points.lineWidth / 2));
	      }
	      var margins = {
	        left: minMargin,
	        right: minMargin,
	        top: minMargin,
	        bottom: minMargin
	      };

	      // check axis labels, note we don't check the actual
	      // labels but instead use the overall width/height to not
	      // jump as much around with replots
	      $.each(allAxes(), function (_, axis) {
	        if (axis.reserveSpace && axis.ticks && axis.ticks.length) {
	          if (axis.direction === "x") {
	            margins.left = Math.max(margins.left, axis.labelWidth / 2);
	            margins.right = Math.max(margins.right, axis.labelWidth / 2);
	          } else {
	            margins.bottom = Math.max(margins.bottom, axis.labelHeight / 2);
	            margins.top = Math.max(margins.top, axis.labelHeight / 2);
	          }
	        }
	      });
	      plotOffset.left = Math.ceil(Math.max(margins.left, plotOffset.left));
	      plotOffset.right = Math.ceil(Math.max(margins.right, plotOffset.right));
	      plotOffset.top = Math.ceil(Math.max(margins.top, plotOffset.top));
	      plotOffset.bottom = Math.ceil(Math.max(margins.bottom, plotOffset.bottom));
	    }
	    function setupGrid() {
	      var i,
	        axes = allAxes(),
	        showGrid = options.grid.show;

	      // Initialize the plot's offset from the edge of the canvas

	      for (var a in plotOffset) {
	        var margin = options.grid.margin || 0;
	        plotOffset[a] = typeof margin == "number" ? margin : margin[a] || 0;
	      }
	      executeHooks(hooks.processOffset, [plotOffset]);

	      // If the grid is visible, add its border width to the offset

	      for (var a in plotOffset) {
	        if (typeof options.grid.borderWidth == "object") {
	          plotOffset[a] += showGrid ? options.grid.borderWidth[a] : 0;
	        } else {
	          plotOffset[a] += showGrid ? options.grid.borderWidth : 0;
	        }
	      }
	      $.each(axes, function (_, axis) {
	        var axisOpts = axis.options;
	        axis.show = axisOpts.show == null ? axis.used : axisOpts.show;
	        axis.reserveSpace = axisOpts.reserveSpace == null ? axis.show : axisOpts.reserveSpace;
	        setRange(axis);
	      });
	      if (showGrid) {
	        var allocatedAxes = $.grep(axes, function (axis) {
	          return axis.show || axis.reserveSpace;
	        });
	        $.each(allocatedAxes, function (_, axis) {
	          // make the ticks
	          setupTickGeneration(axis);
	          setTicks(axis);
	          snapRangeToTicks(axis, axis.ticks);
	          // find labelWidth/Height for axis
	          measureTickLabels(axis);
	        });

	        // with all dimensions calculated, we can compute the
	        // axis bounding boxes, start from the outside
	        // (reverse order)
	        for (i = allocatedAxes.length - 1; i >= 0; --i) allocateAxisBoxFirstPhase(allocatedAxes[i]);

	        // make sure we've got enough space for things that
	        // might stick out
	        adjustLayoutForThingsStickingOut();
	        $.each(allocatedAxes, function (_, axis) {
	          allocateAxisBoxSecondPhase(axis);
	        });
	      }
	      plotWidth = surface.width - plotOffset.left - plotOffset.right;
	      plotHeight = surface.height - plotOffset.bottom - plotOffset.top;

	      // now we got the proper plot dimensions, we can compute the scaling
	      $.each(axes, function (_, axis) {
	        setTransformationHelpers(axis);
	      });
	      if (showGrid) {
	        drawAxisLabels();
	      }
	      insertLegend();
	    }
	    function setRange(axis) {
	      var opts = axis.options,
	        min = +(opts.min != null ? opts.min : axis.datamin),
	        max = +(opts.max != null ? opts.max : axis.datamax),
	        delta = max - min;
	      if (delta == 0.0) {
	        // degenerate case
	        var widen = max == 0 ? 1 : 0.01;
	        if (opts.min == null) min -= widen;
	        // always widen max if we couldn't widen min to ensure we
	        // don't fall into min == max which doesn't work
	        if (opts.max == null || opts.min != null) max += widen;
	      } else {
	        // consider autoscaling
	        var margin = opts.autoscaleMargin;
	        if (margin != null) {
	          if (opts.min == null) {
	            min -= delta * margin;
	            // make sure we don't go below zero if all values
	            // are positive
	            if (min < 0 && axis.datamin != null && axis.datamin >= 0) min = 0;
	          }
	          if (opts.max == null) {
	            max += delta * margin;
	            if (max > 0 && axis.datamax != null && axis.datamax <= 0) max = 0;
	          }
	        }
	      }
	      axis.min = min;
	      axis.max = max;
	    }
	    function setupTickGeneration(axis) {
	      var opts = axis.options;

	      // estimate number of ticks
	      var noTicks;
	      if (typeof opts.ticks == "number" && opts.ticks > 0) noTicks = opts.ticks;else
	        // heuristic based on the model a*sqrt(x) fitted to
	        // some data points that seemed reasonable
	        noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? surface.width : surface.height);
	      var delta = (axis.max - axis.min) / noTicks,
	        dec = -Math.floor(Math.log(delta) / Math.LN10),
	        maxDec = opts.tickDecimals;
	      if (maxDec != null && dec > maxDec) {
	        dec = maxDec;
	      }
	      var magn = Math.pow(10, -dec),
	        norm = delta / magn,
	        // norm is between 1.0 and 10.0
	        size;
	      if (norm < 1.5) {
	        size = 1;
	      } else if (norm < 3) {
	        size = 2;
	        // special case for 2.5, requires an extra decimal
	        if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) {
	          size = 2.5;
	          ++dec;
	        }
	      } else if (norm < 7.5) {
	        size = 5;
	      } else {
	        size = 10;
	      }
	      size *= magn;
	      if (opts.minTickSize != null && size < opts.minTickSize) {
	        size = opts.minTickSize;
	      }
	      axis.delta = delta;
	      axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec);
	      axis.tickSize = opts.tickSize || size;

	      // Time mode was moved to a plug-in in 0.8, and since so many people use it
	      // we'll add an especially friendly reminder to make sure they included it.

	      if (opts.mode == "time" && !axis.tickGenerator) {
	        throw new Error("Time mode requires the flot.time plugin.");
	      }

	      // Flot supports base-10 axes; any other mode else is handled by a plug-in,
	      // like flot.time.js.

	      if (!axis.tickGenerator) {
	        axis.tickGenerator = function (axis) {
	          var ticks = [],
	            start = floorInBase(axis.min, axis.tickSize),
	            i = 0,
	            v = Number.NaN,
	            prev;
	          do {
	            prev = v;
	            v = start + i * axis.tickSize;
	            ticks.push(v);
	            ++i;
	          } while (v < axis.max && v != prev);
	          return ticks;
	        };
	        axis.tickFormatter = function (value, axis) {
	          var factor = axis.tickDecimals ? Math.pow(10, axis.tickDecimals) : 1;
	          var formatted = "" + Math.round(value * factor) / factor;

	          // If tickDecimals was specified, ensure that we have exactly that
	          // much precision; otherwise default to the value's own precision.

	          if (axis.tickDecimals != null) {
	            var decimal = formatted.indexOf(".");
	            var precision = decimal == -1 ? 0 : formatted.length - decimal - 1;
	            if (precision < axis.tickDecimals) {
	              return (precision ? formatted : formatted + ".") + ("" + factor).substr(1, axis.tickDecimals - precision);
	            }
	          }
	          return formatted;
	        };
	      }
	      if ($.isFunction(opts.tickFormatter)) axis.tickFormatter = function (v, axis) {
	        return "" + opts.tickFormatter(v, axis);
	      };
	      if (opts.alignTicksWithAxis != null) {
	        var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1];
	        if (otherAxis && otherAxis.used && otherAxis != axis) {
	          // consider snapping min/max to outermost nice ticks
	          var niceTicks = axis.tickGenerator(axis);
	          if (niceTicks.length > 0) {
	            if (opts.min == null) axis.min = Math.min(axis.min, niceTicks[0]);
	            if (opts.max == null && niceTicks.length > 1) axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]);
	          }
	          axis.tickGenerator = function (axis) {
	            // copy ticks, scaled to this axis
	            var ticks = [],
	              v,
	              i;
	            for (i = 0; i < otherAxis.ticks.length; ++i) {
	              v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min);
	              v = axis.min + v * (axis.max - axis.min);
	              ticks.push(v);
	            }
	            return ticks;
	          };

	          // we might need an extra decimal since forced
	          // ticks don't necessarily fit naturally
	          if (!axis.mode && opts.tickDecimals == null) {
	            var extraDec = Math.max(0, -Math.floor(Math.log(axis.delta) / Math.LN10) + 1),
	              ts = axis.tickGenerator(axis);

	            // only proceed if the tick interval rounded
	            // with an extra decimal doesn't give us a
	            // zero at end
	            if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec)))) axis.tickDecimals = extraDec;
	          }
	        }
	      }
	    }
	    function setTicks(axis) {
	      var oticks = axis.options.ticks,
	        ticks = [];
	      if (oticks == null || typeof oticks == "number" && oticks > 0) ticks = axis.tickGenerator(axis);else if (oticks) {
	        if ($.isFunction(oticks))
	          // generate the ticks
	          ticks = oticks(axis);else ticks = oticks;
	      }

	      // clean up/labelify the supplied ticks, copy them over
	      var i, v;
	      axis.ticks = [];
	      for (i = 0; i < ticks.length; ++i) {
	        var label = null;
	        var t = ticks[i];
	        if (typeof t == "object") {
	          v = +t[0];
	          if (t.length > 1) label = t[1];
	        } else v = +t;
	        if (label == null) label = axis.tickFormatter(v, axis);
	        if (!isNaN(v)) axis.ticks.push({
	          v: v,
	          label: label
	        });
	      }
	    }
	    function snapRangeToTicks(axis, ticks) {
	      if (axis.options.autoscaleMargin && ticks.length > 0) {
	        // snap to ticks
	        if (axis.options.min == null) axis.min = Math.min(axis.min, ticks[0].v);
	        if (axis.options.max == null && ticks.length > 1) axis.max = Math.max(axis.max, ticks[ticks.length - 1].v);
	      }
	    }
	    function draw() {
	      surface.clear();
	      executeHooks(hooks.drawBackground, [ctx]);
	      var grid = options.grid;

	      // draw background, if any
	      if (grid.show && grid.backgroundColor) drawBackground();
	      if (grid.show && !grid.aboveData) {
	        drawGrid();
	      }
	      for (var i = 0; i < series.length; ++i) {
	        executeHooks(hooks.drawSeries, [ctx, series[i]]);
	        drawSeries(series[i]);
	      }
	      executeHooks(hooks.draw, [ctx]);
	      if (grid.show && grid.aboveData) {
	        drawGrid();
	      }
	      surface.render();

	      // A draw implies that either the axes or data have changed, so we
	      // should probably update the overlay highlights as well.

	      triggerRedrawOverlay();
	    }
	    function extractRange(ranges, coord) {
	      var axis,
	        from,
	        to,
	        key,
	        axes = allAxes();
	      for (var i = 0; i < axes.length; ++i) {
	        axis = axes[i];
	        if (axis.direction == coord) {
	          key = coord + axis.n + "axis";
	          if (!ranges[key] && axis.n == 1) key = coord + "axis"; // support x1axis as xaxis
	          if (ranges[key]) {
	            from = ranges[key].from;
	            to = ranges[key].to;
	            break;
	          }
	        }
	      }

	      // backwards-compat stuff - to be removed in future
	      if (!ranges[key]) {
	        axis = coord == "x" ? xaxes[0] : yaxes[0];
	        from = ranges[coord + "1"];
	        to = ranges[coord + "2"];
	      }

	      // auto-reverse as an added bonus
	      if (from != null && to != null && from > to) {
	        var tmp = from;
	        from = to;
	        to = tmp;
	      }
	      return {
	        from: from,
	        to: to,
	        axis: axis
	      };
	    }
	    function drawBackground() {
	      ctx.save();
	      ctx.translate(plotOffset.left, plotOffset.top);
	      ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)");
	      ctx.fillRect(0, 0, plotWidth, plotHeight);
	      ctx.restore();
	    }
	    function drawGrid() {
	      var i, axes, bw, bc;
	      ctx.save();
	      ctx.translate(plotOffset.left, plotOffset.top);

	      // draw markings
	      var markings = options.grid.markings;
	      if (markings) {
	        if ($.isFunction(markings)) {
	          axes = plot.getAxes();
	          // xmin etc. is backwards compatibility, to be
	          // removed in the future
	          axes.xmin = axes.xaxis.min;
	          axes.xmax = axes.xaxis.max;
	          axes.ymin = axes.yaxis.min;
	          axes.ymax = axes.yaxis.max;
	          markings = markings(axes);
	        }
	        for (i = 0; i < markings.length; ++i) {
	          var m = markings[i],
	            xrange = extractRange(m, "x"),
	            yrange = extractRange(m, "y");

	          // fill in missing
	          if (xrange.from == null) xrange.from = xrange.axis.min;
	          if (xrange.to == null) xrange.to = xrange.axis.max;
	          if (yrange.from == null) yrange.from = yrange.axis.min;
	          if (yrange.to == null) yrange.to = yrange.axis.max;

	          // clip
	          if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max || yrange.to < yrange.axis.min || yrange.from > yrange.axis.max) continue;
	          xrange.from = Math.max(xrange.from, xrange.axis.min);
	          xrange.to = Math.min(xrange.to, xrange.axis.max);
	          yrange.from = Math.max(yrange.from, yrange.axis.min);
	          yrange.to = Math.min(yrange.to, yrange.axis.max);
	          var xequal = xrange.from === xrange.to,
	            yequal = yrange.from === yrange.to;
	          if (xequal && yequal) {
	            continue;
	          }

	          // then draw
	          xrange.from = Math.floor(xrange.axis.p2c(xrange.from));
	          xrange.to = Math.floor(xrange.axis.p2c(xrange.to));
	          yrange.from = Math.floor(yrange.axis.p2c(yrange.from));
	          yrange.to = Math.floor(yrange.axis.p2c(yrange.to));
	          if (xequal || yequal) {
	            var lineWidth = m.lineWidth || options.grid.markingsLineWidth,
	              subPixel = lineWidth % 2 ? 0.5 : 0;
	            ctx.beginPath();
	            ctx.strokeStyle = m.color || options.grid.markingsColor;
	            ctx.lineWidth = lineWidth;
	            if (xequal) {
	              ctx.moveTo(xrange.to + subPixel, yrange.from);
	              ctx.lineTo(xrange.to + subPixel, yrange.to);
	            } else {
	              ctx.moveTo(xrange.from, yrange.to + subPixel);
	              ctx.lineTo(xrange.to, yrange.to + subPixel);
	            }
	            ctx.stroke();
	          } else {
	            ctx.fillStyle = m.color || options.grid.markingsColor;
	            ctx.fillRect(xrange.from, yrange.to, xrange.to - xrange.from, yrange.from - yrange.to);
	          }
	        }
	      }

	      // draw the ticks
	      axes = allAxes();
	      bw = options.grid.borderWidth;
	      for (var j = 0; j < axes.length; ++j) {
	        var axis = axes[j],
	          box = axis.box,
	          t = axis.tickLength,
	          x,
	          y,
	          xoff,
	          yoff;
	        if (!axis.show || axis.ticks.length == 0) continue;
	        ctx.lineWidth = 1;

	        // find the edges
	        if (axis.direction == "x") {
	          x = 0;
	          if (t == "full") y = axis.position == "top" ? 0 : plotHeight;else y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0);
	        } else {
	          y = 0;
	          if (t == "full") x = axis.position == "left" ? 0 : plotWidth;else x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0);
	        }

	        // draw tick bar
	        if (!axis.innermost) {
	          ctx.strokeStyle = axis.options.color;
	          ctx.beginPath();
	          xoff = yoff = 0;
	          if (axis.direction == "x") xoff = plotWidth + 1;else yoff = plotHeight + 1;
	          if (ctx.lineWidth == 1) {
	            if (axis.direction == "x") {
	              y = Math.floor(y) + 0.5;
	            } else {
	              x = Math.floor(x) + 0.5;
	            }
	          }
	          ctx.moveTo(x, y);
	          ctx.lineTo(x + xoff, y + yoff);
	          ctx.stroke();
	        }

	        // draw ticks

	        ctx.strokeStyle = axis.options.tickColor;
	        ctx.beginPath();
	        for (i = 0; i < axis.ticks.length; ++i) {
	          var v = axis.ticks[i].v;
	          xoff = yoff = 0;
	          if (isNaN(v) || v < axis.min || v > axis.max
	          // skip those lying on the axes if we got a border
	          || t == "full" && (typeof bw == "object" && bw[axis.position] > 0 || bw > 0) && (v == axis.min || v == axis.max)) continue;
	          if (axis.direction == "x") {
	            x = axis.p2c(v);
	            yoff = t == "full" ? -plotHeight : t;
	            if (axis.position == "top") yoff = -yoff;
	          } else {
	            y = axis.p2c(v);
	            xoff = t == "full" ? -plotWidth : t;
	            if (axis.position == "left") xoff = -xoff;
	          }
	          if (ctx.lineWidth == 1) {
	            if (axis.direction == "x") x = Math.floor(x) + 0.5;else y = Math.floor(y) + 0.5;
	          }
	          ctx.moveTo(x, y);
	          ctx.lineTo(x + xoff, y + yoff);
	        }
	        ctx.stroke();
	      }

	      // draw border
	      if (bw) {
	        // If either borderWidth or borderColor is an object, then draw the border
	        // line by line instead of as one rectangle
	        bc = options.grid.borderColor;
	        if (typeof bw == "object" || typeof bc == "object") {
	          if (typeof bw !== "object") {
	            bw = {
	              top: bw,
	              right: bw,
	              bottom: bw,
	              left: bw
	            };
	          }
	          if (typeof bc !== "object") {
	            bc = {
	              top: bc,
	              right: bc,
	              bottom: bc,
	              left: bc
	            };
	          }
	          if (bw.top > 0) {
	            ctx.strokeStyle = bc.top;
	            ctx.lineWidth = bw.top;
	            ctx.beginPath();
	            ctx.moveTo(0 - bw.left, 0 - bw.top / 2);
	            ctx.lineTo(plotWidth, 0 - bw.top / 2);
	            ctx.stroke();
	          }
	          if (bw.right > 0) {
	            ctx.strokeStyle = bc.right;
	            ctx.lineWidth = bw.right;
	            ctx.beginPath();
	            ctx.moveTo(plotWidth + bw.right / 2, 0 - bw.top);
	            ctx.lineTo(plotWidth + bw.right / 2, plotHeight);
	            ctx.stroke();
	          }
	          if (bw.bottom > 0) {
	            ctx.strokeStyle = bc.bottom;
	            ctx.lineWidth = bw.bottom;
	            ctx.beginPath();
	            ctx.moveTo(plotWidth + bw.right, plotHeight + bw.bottom / 2);
	            ctx.lineTo(0, plotHeight + bw.bottom / 2);
	            ctx.stroke();
	          }
	          if (bw.left > 0) {
	            ctx.strokeStyle = bc.left;
	            ctx.lineWidth = bw.left;
	            ctx.beginPath();
	            ctx.moveTo(0 - bw.left / 2, plotHeight + bw.bottom);
	            ctx.lineTo(0 - bw.left / 2, 0);
	            ctx.stroke();
	          }
	        } else {
	          ctx.lineWidth = bw;
	          ctx.strokeStyle = options.grid.borderColor;
	          ctx.strokeRect(-bw / 2, -bw / 2, plotWidth + bw, plotHeight + bw);
	        }
	      }
	      ctx.restore();
	    }
	    function drawAxisLabels() {
	      $.each(allAxes(), function (_, axis) {
	        var box = axis.box,
	          legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis",
	          layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles,
	          font = axis.options.font || "flot-tick-label tickLabel",
	          tick,
	          x,
	          y,
	          halign,
	          valign;

	        // Remove text before checking for axis.show and ticks.length;
	        // otherwise plugins, like flot-tickrotor, that draw their own
	        // tick labels will end up with both theirs and the defaults.

	        surface.removeText(layer);
	        if (!axis.show || axis.ticks.length == 0) return;
	        for (var i = 0; i < axis.ticks.length; ++i) {
	          tick = axis.ticks[i];
	          if (!tick.label || tick.v < axis.min || tick.v > axis.max) continue;
	          if (axis.direction == "x") {
	            halign = "center";
	            x = plotOffset.left + axis.p2c(tick.v);
	            if (axis.position == "bottom") {
	              y = box.top + box.padding;
	            } else {
	              y = box.top + box.height - box.padding;
	              valign = "bottom";
	            }
	          } else {
	            valign = "middle";
	            y = plotOffset.top + axis.p2c(tick.v);
	            if (axis.position == "left") {
	              x = box.left + box.width - box.padding;
	              halign = "right";
	            } else {
	              x = box.left + box.padding;
	            }
	          }
	          surface.addText(layer, x, y, tick.label, font, null, null, halign, valign);
	        }
	      });
	    }
	    function drawSeries(series) {
	      if (series.lines.show) drawSeriesLines(series);
	      if (series.bars.show) drawSeriesBars(series);
	      if (series.points.show) drawSeriesPoints(series);
	    }
	    function drawSeriesLines(series) {
	      function plotLine(datapoints, xoffset, yoffset, axisx, axisy) {
	        var points = datapoints.points,
	          ps = datapoints.pointsize,
	          prevx = null,
	          prevy = null;
	        ctx.beginPath();
	        for (var i = ps; i < points.length; i += ps) {
	          var x1 = points[i - ps],
	            y1 = points[i - ps + 1],
	            x2 = points[i],
	            y2 = points[i + 1];
	          if (x1 == null || x2 == null) continue;

	          // clip with ymin
	          if (y1 <= y2 && y1 < axisy.min) {
	            if (y2 < axisy.min) continue; // line segment is outside
	            // compute new intersection point
	            x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
	            y1 = axisy.min;
	          } else if (y2 <= y1 && y2 < axisy.min) {
	            if (y1 < axisy.min) continue;
	            x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
	            y2 = axisy.min;
	          }

	          // clip with ymax
	          if (y1 >= y2 && y1 > axisy.max) {
	            if (y2 > axisy.max) continue;
	            x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
	            y1 = axisy.max;
	          } else if (y2 >= y1 && y2 > axisy.max) {
	            if (y1 > axisy.max) continue;
	            x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
	            y2 = axisy.max;
	          }

	          // clip with xmin
	          if (x1 <= x2 && x1 < axisx.min) {
	            if (x2 < axisx.min) continue;
	            y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
	            x1 = axisx.min;
	          } else if (x2 <= x1 && x2 < axisx.min) {
	            if (x1 < axisx.min) continue;
	            y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
	            x2 = axisx.min;
	          }

	          // clip with xmax
	          if (x1 >= x2 && x1 > axisx.max) {
	            if (x2 > axisx.max) continue;
	            y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
	            x1 = axisx.max;
	          } else if (x2 >= x1 && x2 > axisx.max) {
	            if (x1 > axisx.max) continue;
	            y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
	            x2 = axisx.max;
	          }
	          if (x1 != prevx || y1 != prevy) ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset);
	          prevx = x2;
	          prevy = y2;
	          ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset);
	        }
	        ctx.stroke();
	      }
	      function plotLineArea(datapoints, axisx, axisy) {
	        var points = datapoints.points,
	          ps = datapoints.pointsize,
	          bottom = Math.min(Math.max(0, axisy.min), axisy.max),
	          i = 0,
	          areaOpen = false,
	          ypos = 1,
	          segmentStart = 0,
	          segmentEnd = 0;

	        // we process each segment in two turns, first forward
	        // direction to sketch out top, then once we hit the
	        // end we go backwards to sketch the bottom
	        while (true) {
	          if (ps > 0 && i > points.length + ps) break;
	          i += ps; // ps is negative if going backwards

	          var x1 = points[i - ps],
	            y1 = points[i - ps + ypos],
	            x2 = points[i],
	            y2 = points[i + ypos];
	          if (areaOpen) {
	            if (ps > 0 && x1 != null && x2 == null) {
	              // at turning point
	              segmentEnd = i;
	              ps = -ps;
	              ypos = 2;
	              continue;
	            }
	            if (ps < 0 && i == segmentStart + ps) {
	              // done with the reverse sweep
	              ctx.fill();
	              areaOpen = false;
	              ps = -ps;
	              ypos = 1;
	              i = segmentStart = segmentEnd + ps;
	              continue;
	            }
	          }
	          if (x1 == null || x2 == null) continue;

	          // clip x values

	          // clip with xmin
	          if (x1 <= x2 && x1 < axisx.min) {
	            if (x2 < axisx.min) continue;
	            y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
	            x1 = axisx.min;
	          } else if (x2 <= x1 && x2 < axisx.min) {
	            if (x1 < axisx.min) continue;
	            y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
	            x2 = axisx.min;
	          }

	          // clip with xmax
	          if (x1 >= x2 && x1 > axisx.max) {
	            if (x2 > axisx.max) continue;
	            y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
	            x1 = axisx.max;
	          } else if (x2 >= x1 && x2 > axisx.max) {
	            if (x1 > axisx.max) continue;
	            y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
	            x2 = axisx.max;
	          }
	          if (!areaOpen) {
	            // open area
	            ctx.beginPath();
	            ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom));
	            areaOpen = true;
	          }

	          // now first check the case where both is outside
	          if (y1 >= axisy.max && y2 >= axisy.max) {
	            ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max));
	            ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max));
	            continue;
	          } else if (y1 <= axisy.min && y2 <= axisy.min) {
	            ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min));
	            ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min));
	            continue;
	          }

	          // else it's a bit more complicated, there might
	          // be a flat maxed out rectangle first, then a
	          // triangular cutout or reverse; to find these
	          // keep track of the current x values
	          var x1old = x1,
	            x2old = x2;

	          // clip the y values, without shortcutting, we
	          // go through all cases in turn

	          // clip with ymin
	          if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) {
	            x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
	            y1 = axisy.min;
	          } else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) {
	            x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
	            y2 = axisy.min;
	          }

	          // clip with ymax
	          if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) {
	            x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
	            y1 = axisy.max;
	          } else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) {
	            x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
	            y2 = axisy.max;
	          }

	          // if the x value was changed we got a rectangle
	          // to fill
	          if (x1 != x1old) {
	            ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1));
	            // it goes to (x1, y1), but we fill that below
	          }

	          // fill triangular section, this sometimes result
	          // in redundant points if (x1, y1) hasn't changed
	          // from previous line to, but we just ignore that
	          ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1));
	          ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));

	          // fill the other rectangle if it's there
	          if (x2 != x2old) {
	            ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
	            ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2));
	          }
	        }
	      }
	      ctx.save();
	      ctx.translate(plotOffset.left, plotOffset.top);
	      ctx.lineJoin = "round";
	      var lw = series.lines.lineWidth,
	        sw = series.shadowSize;
	      // FIXME: consider another form of shadow when filling is turned on
	      if (lw > 0 && sw > 0) {
	        // draw shadow as a thick and thin line with transparency
	        ctx.lineWidth = sw;
	        ctx.strokeStyle = "rgba(0,0,0,0.1)";
	        // position shadow at angle from the mid of line
	        var angle = Math.PI / 18;
	        plotLine(series.datapoints, Math.sin(angle) * (lw / 2 + sw / 2), Math.cos(angle) * (lw / 2 + sw / 2), series.xaxis, series.yaxis);
	        ctx.lineWidth = sw / 2;
	        plotLine(series.datapoints, Math.sin(angle) * (lw / 2 + sw / 4), Math.cos(angle) * (lw / 2 + sw / 4), series.xaxis, series.yaxis);
	      }
	      ctx.lineWidth = lw;
	      ctx.strokeStyle = series.color;
	      var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight);
	      if (fillStyle) {
	        ctx.fillStyle = fillStyle;
	        plotLineArea(series.datapoints, series.xaxis, series.yaxis);
	      }
	      if (lw > 0) plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis);
	      ctx.restore();
	    }
	    function drawSeriesPoints(series) {
	      function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) {
	        var points = datapoints.points,
	          ps = datapoints.pointsize;
	        for (var i = 0; i < points.length; i += ps) {
	          var x = points[i],
	            y = points[i + 1];
	          if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) continue;
	          ctx.beginPath();
	          x = axisx.p2c(x);
	          y = axisy.p2c(y) + offset;
	          if (symbol == "circle") ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false);else symbol(ctx, x, y, radius, shadow);
	          ctx.closePath();
	          if (fillStyle) {
	            ctx.fillStyle = fillStyle;
	            ctx.fill();
	          }
	          ctx.stroke();
	        }
	      }
	      ctx.save();
	      ctx.translate(plotOffset.left, plotOffset.top);
	      var lw = series.points.lineWidth,
	        sw = series.shadowSize,
	        radius = series.points.radius,
	        symbol = series.points.symbol;

	      // If the user sets the line width to 0, we change it to a very 
	      // small value. A line width of 0 seems to force the default of 1.
	      // Doing the conditional here allows the shadow setting to still be 
	      // optional even with a lineWidth of 0.

	      if (lw == 0) lw = 0.0001;
	      if (lw > 0 && sw > 0) {
	        // draw shadow in two steps
	        var w = sw / 2;
	        ctx.lineWidth = w;
	        ctx.strokeStyle = "rgba(0,0,0,0.1)";
	        plotPoints(series.datapoints, radius, null, w + w / 2, true, series.xaxis, series.yaxis, symbol);
	        ctx.strokeStyle = "rgba(0,0,0,0.2)";
	        plotPoints(series.datapoints, radius, null, w / 2, true, series.xaxis, series.yaxis, symbol);
	      }
	      ctx.lineWidth = lw;
	      ctx.strokeStyle = series.color;
	      plotPoints(series.datapoints, radius, getFillStyle(series.points, series.color), 0, false, series.xaxis, series.yaxis, symbol);
	      ctx.restore();
	    }
	    function drawBar(x, y, b, barLeft, barRight, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) {
	      var left, right, bottom, top, drawLeft, drawRight, drawTop, drawBottom, tmp;

	      // in horizontal mode, we start the bar from the left
	      // instead of from the bottom so it appears to be
	      // horizontal rather than vertical
	      if (horizontal) {
	        drawBottom = drawRight = drawTop = true;
	        drawLeft = false;
	        left = b;
	        right = x;
	        top = y + barLeft;
	        bottom = y + barRight;

	        // account for negative bars
	        if (right < left) {
	          tmp = right;
	          right = left;
	          left = tmp;
	          drawLeft = true;
	          drawRight = false;
	        }
	      } else {
	        drawLeft = drawRight = drawTop = true;
	        drawBottom = false;
	        left = x + barLeft;
	        right = x + barRight;
	        bottom = b;
	        top = y;

	        // account for negative bars
	        if (top < bottom) {
	          tmp = top;
	          top = bottom;
	          bottom = tmp;
	          drawBottom = true;
	          drawTop = false;
	        }
	      }

	      // clip
	      if (right < axisx.min || left > axisx.max || top < axisy.min || bottom > axisy.max) return;
	      if (left < axisx.min) {
	        left = axisx.min;
	        drawLeft = false;
	      }
	      if (right > axisx.max) {
	        right = axisx.max;
	        drawRight = false;
	      }
	      if (bottom < axisy.min) {
	        bottom = axisy.min;
	        drawBottom = false;
	      }
	      if (top > axisy.max) {
	        top = axisy.max;
	        drawTop = false;
	      }
	      left = axisx.p2c(left);
	      bottom = axisy.p2c(bottom);
	      right = axisx.p2c(right);
	      top = axisy.p2c(top);

	      // fill the bar
	      if (fillStyleCallback) {
	        c.fillStyle = fillStyleCallback(bottom, top);
	        c.fillRect(left, top, right - left, bottom - top);
	      }

	      // draw outline
	      if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) {
	        c.beginPath();

	        // FIXME: inline moveTo is buggy with excanvas
	        c.moveTo(left, bottom);
	        if (drawLeft) c.lineTo(left, top);else c.moveTo(left, top);
	        if (drawTop) c.lineTo(right, top);else c.moveTo(right, top);
	        if (drawRight) c.lineTo(right, bottom);else c.moveTo(right, bottom);
	        if (drawBottom) c.lineTo(left, bottom);else c.moveTo(left, bottom);
	        c.stroke();
	      }
	    }
	    function drawSeriesBars(series) {
	      function plotBars(datapoints, barLeft, barRight, fillStyleCallback, axisx, axisy) {
	        var points = datapoints.points,
	          ps = datapoints.pointsize;
	        for (var i = 0; i < points.length; i += ps) {
	          if (points[i] == null) continue;
	          drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth);
	        }
	      }
	      ctx.save();
	      ctx.translate(plotOffset.left, plotOffset.top);

	      // FIXME: figure out a way to add shadows (for instance along the right edge)
	      ctx.lineWidth = series.bars.lineWidth;
	      ctx.strokeStyle = series.color;
	      var barLeft;
	      switch (series.bars.align) {
	        case "left":
	          barLeft = 0;
	          break;
	        case "right":
	          barLeft = -series.bars.barWidth;
	          break;
	        default:
	          barLeft = -series.bars.barWidth / 2;
	      }
	      var fillStyleCallback = series.bars.fill ? function (bottom, top) {
	        return getFillStyle(series.bars, series.color, bottom, top);
	      } : null;
	      plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, fillStyleCallback, series.xaxis, series.yaxis);
	      ctx.restore();
	    }
	    function getFillStyle(filloptions, seriesColor, bottom, top) {
	      var fill = filloptions.fill;
	      if (!fill) return null;
	      if (filloptions.fillColor) return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor);
	      var c = $.color.parse(seriesColor);
	      c.a = typeof fill == "number" ? fill : 0.4;
	      c.normalize();
	      return c.toString();
	    }
	    function insertLegend() {
	      if (options.legend.container != null) {
	        $(options.legend.container).html("");
	      } else {
	        placeholder.find(".legend").remove();
	      }
	      if (!options.legend.show) {
	        return;
	      }
	      var fragments = [],
	        entries = [],
	        rowStarted = false,
	        lf = options.legend.labelFormatter,
	        s,
	        label;

	      // Build a list of legend entries, with each having a label and a color

	      for (var i = 0; i < series.length; ++i) {
	        s = series[i];
	        if (s.label) {
	          label = lf ? lf(s.label, s) : s.label;
	          if (label) {
	            entries.push({
	              label: label,
	              color: s.color
	            });
	          }
	        }
	      }

	      // Sort the legend using either the default or a custom comparator

	      if (options.legend.sorted) {
	        if ($.isFunction(options.legend.sorted)) {
	          entries.sort(options.legend.sorted);
	        } else if (options.legend.sorted == "reverse") {
	          entries.reverse();
	        } else {
	          var ascending = options.legend.sorted != "descending";
	          entries.sort(function (a, b) {
	            return a.label == b.label ? 0 : a.label < b.label != ascending ? 1 : -1 // Logical XOR
	;
	          });
	        }
	      }

	      // Generate markup for the list of entries, in their final order

	      for (var i = 0; i < entries.length; ++i) {
	        var entry = entries[i];
	        if (i % options.legend.noColumns == 0) {
	          if (rowStarted) fragments.push('</tr>');
	          fragments.push('<tr>');
	          rowStarted = true;
	        }
	        fragments.push('<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + entry.color + ';overflow:hidden"></div></div></td>' + '<td class="legendLabel">' + entry.label + '</td>');
	      }
	      if (rowStarted) fragments.push('</tr>');
	      if (fragments.length == 0) return;
	      var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>';
	      if (options.legend.container != null) $(options.legend.container).html(table);else {
	        var pos = "",
	          p = options.legend.position,
	          m = options.legend.margin;
	        if (m[0] == null) m = [m, m];
	        if (p.charAt(0) == "n") pos += 'top:' + (m[1] + plotOffset.top) + 'px;';else if (p.charAt(0) == "s") pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;';
	        if (p.charAt(1) == "e") pos += 'right:' + (m[0] + plotOffset.right) + 'px;';else if (p.charAt(1) == "w") pos += 'left:' + (m[0] + plotOffset.left) + 'px;';
	        var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos + ';') + '</div>').appendTo(placeholder);
	        if (options.legend.backgroundOpacity != 0.0) {
	          // put in the transparent background
	          // separately to avoid blended labels and
	          // label boxes
	          var c = options.legend.backgroundColor;
	          if (c == null) {
	            c = options.grid.backgroundColor;
	            if (c && typeof c == "string") c = $.color.parse(c);else c = $.color.extract(legend, 'background-color');
	            c.a = 1;
	            c = c.toString();
	          }
	          var div = legend.children();
	          $('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos + 'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity);
	        }
	      }
	    }

	    // interactive features

	    var highlights = [],
	      redrawTimeout = null;

	    // returns the data item the mouse is over, or null if none is found
	    function findNearbyItem(mouseX, mouseY, seriesFilter) {
	      var maxDistance = options.grid.mouseActiveRadius,
	        smallestDistance = maxDistance * maxDistance + 1,
	        item = null,
	        i,
	        j,
	        ps;
	      for (i = series.length - 1; i >= 0; --i) {
	        if (!seriesFilter(series[i])) continue;
	        var s = series[i],
	          axisx = s.xaxis,
	          axisy = s.yaxis,
	          points = s.datapoints.points,
	          mx = axisx.c2p(mouseX),
	          // precompute some stuff to make the loop faster
	          my = axisy.c2p(mouseY),
	          maxx = maxDistance / axisx.scale,
	          maxy = maxDistance / axisy.scale;
	        ps = s.datapoints.pointsize;
	        // with inverse transforms, we can't use the maxx/maxy
	        // optimization, sadly
	        if (axisx.options.inverseTransform) maxx = Number.MAX_VALUE;
	        if (axisy.options.inverseTransform) maxy = Number.MAX_VALUE;
	        if (s.lines.show || s.points.show) {
	          for (j = 0; j < points.length; j += ps) {
	            var x = points[j],
	              y = points[j + 1];
	            if (x == null) continue;

	            // For points and lines, the cursor must be within a
	            // certain distance to the data point
	            if (x - mx > maxx || x - mx < -maxx || y - my > maxy || y - my < -maxy) continue;

	            // We have to calculate distances in pixels, not in
	            // data units, because the scales of the axes may be different
	            var dx = Math.abs(axisx.p2c(x) - mouseX),
	              dy = Math.abs(axisy.p2c(y) - mouseY),
	              dist = dx * dx + dy * dy; // we save the sqrt

	            // use <= to ensure last point takes precedence
	            // (last generally means on top of)
	            if (dist < smallestDistance) {
	              smallestDistance = dist;
	              item = [i, j / ps];
	            }
	          }
	        }
	        if (s.bars.show && !item) {
	          // no other point can be nearby

	          var barLeft, barRight;
	          switch (s.bars.align) {
	            case "left":
	              barLeft = 0;
	              break;
	            case "right":
	              barLeft = -s.bars.barWidth;
	              break;
	            default:
	              barLeft = -s.bars.barWidth / 2;
	          }
	          barRight = barLeft + s.bars.barWidth;
	          for (j = 0; j < points.length; j += ps) {
	            var x = points[j],
	              y = points[j + 1],
	              b = points[j + 2];
	            if (x == null) continue;

	            // for a bar graph, the cursor must be inside the bar
	            if (series[i].bars.horizontal ? mx <= Math.max(b, x) && mx >= Math.min(b, x) && my >= y + barLeft && my <= y + barRight : mx >= x + barLeft && mx <= x + barRight && my >= Math.min(b, y) && my <= Math.max(b, y)) item = [i, j / ps];
	          }
	        }
	      }
	      if (item) {
	        i = item[0];
	        j = item[1];
	        ps = series[i].datapoints.pointsize;
	        return {
	          datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps),
	          dataIndex: j,
	          series: series[i],
	          seriesIndex: i
	        };
	      }
	      return null;
	    }
	    function onMouseMove(e) {
	      if (options.grid.hoverable) triggerClickHoverEvent("plothover", e, function (s) {
	        return s["hoverable"] != false;
	      });
	    }
	    function onMouseLeave(e) {
	      if (options.grid.hoverable) triggerClickHoverEvent("plothover", e, function (s) {
	        return false;
	      });
	    }
	    function onClick(e) {
	      triggerClickHoverEvent("plotclick", e, function (s) {
	        return s["clickable"] != false;
	      });
	    }

	    // trigger click or hover event (they send the same parameters
	    // so we share their code)
	    function triggerClickHoverEvent(eventname, event, seriesFilter) {
	      var offset = eventHolder.offset(),
	        canvasX = event.pageX - offset.left - plotOffset.left,
	        canvasY = event.pageY - offset.top - plotOffset.top,
	        pos = canvasToAxisCoords({
	          left: canvasX,
	          top: canvasY
	        });
	      pos.pageX = event.pageX;
	      pos.pageY = event.pageY;
	      var item = findNearbyItem(canvasX, canvasY, seriesFilter);
	      if (item) {
	        // fill in mouse pos for any listeners out there
	        item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left, 10);
	        item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top, 10);
	      }
	      if (options.grid.autoHighlight) {
	        // clear auto-highlights
	        for (var i = 0; i < highlights.length; ++i) {
	          var h = highlights[i];
	          if (h.auto == eventname && !(item && h.series == item.series && h.point[0] == item.datapoint[0] && h.point[1] == item.datapoint[1])) unhighlight(h.series, h.point);
	        }
	        if (item) highlight(item.series, item.datapoint, eventname);
	      }
	      placeholder.trigger(eventname, [pos, item]);
	    }
	    function triggerRedrawOverlay() {
	      var t = options.interaction.redrawOverlayInterval;
	      if (t == -1) {
	        // skip event queue
	        drawOverlay();
	        return;
	      }
	      if (!redrawTimeout) redrawTimeout = setTimeout(drawOverlay, t);
	    }
	    function drawOverlay() {
	      redrawTimeout = null;

	      // draw highlights
	      octx.save();
	      overlay.clear();
	      octx.translate(plotOffset.left, plotOffset.top);
	      var i, hi;
	      for (i = 0; i < highlights.length; ++i) {
	        hi = highlights[i];
	        if (hi.series.bars.show) drawBarHighlight(hi.series, hi.point);else drawPointHighlight(hi.series, hi.point);
	      }
	      octx.restore();
	      executeHooks(hooks.drawOverlay, [octx]);
	    }
	    function highlight(s, point, auto) {
	      if (typeof s == "number") s = series[s];
	      if (typeof point == "number") {
	        var ps = s.datapoints.pointsize;
	        point = s.datapoints.points.slice(ps * point, ps * (point + 1));
	      }
	      var i = indexOfHighlight(s, point);
	      if (i == -1) {
	        highlights.push({
	          series: s,
	          point: point,
	          auto: auto
	        });
	        triggerRedrawOverlay();
	      } else if (!auto) highlights[i].auto = false;
	    }
	    function unhighlight(s, point) {
	      if (s == null && point == null) {
	        highlights = [];
	        triggerRedrawOverlay();
	        return;
	      }
	      if (typeof s == "number") s = series[s];
	      if (typeof point == "number") {
	        var ps = s.datapoints.pointsize;
	        point = s.datapoints.points.slice(ps * point, ps * (point + 1));
	      }
	      var i = indexOfHighlight(s, point);
	      if (i != -1) {
	        highlights.splice(i, 1);
	        triggerRedrawOverlay();
	      }
	    }
	    function indexOfHighlight(s, p) {
	      for (var i = 0; i < highlights.length; ++i) {
	        var h = highlights[i];
	        if (h.series == s && h.point[0] == p[0] && h.point[1] == p[1]) return i;
	      }
	      return -1;
	    }
	    function drawPointHighlight(series, point) {
	      var x = point[0],
	        y = point[1],
	        axisx = series.xaxis,
	        axisy = series.yaxis,
	        highlightColor = typeof series.highlightColor === "string" ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString();
	      if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) return;
	      var pointRadius = series.points.radius + series.points.lineWidth / 2;
	      octx.lineWidth = pointRadius;
	      octx.strokeStyle = highlightColor;
	      var radius = 1.5 * pointRadius;
	      x = axisx.p2c(x);
	      y = axisy.p2c(y);
	      octx.beginPath();
	      if (series.points.symbol == "circle") octx.arc(x, y, radius, 0, 2 * Math.PI, false);else series.points.symbol(octx, x, y, radius, false);
	      octx.closePath();
	      octx.stroke();
	    }
	    function drawBarHighlight(series, point) {
	      var highlightColor = typeof series.highlightColor === "string" ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString(),
	        fillStyle = highlightColor,
	        barLeft;
	      switch (series.bars.align) {
	        case "left":
	          barLeft = 0;
	          break;
	        case "right":
	          barLeft = -series.bars.barWidth;
	          break;
	        default:
	          barLeft = -series.bars.barWidth / 2;
	      }
	      octx.lineWidth = series.bars.lineWidth;
	      octx.strokeStyle = highlightColor;
	      drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth, function () {
	        return fillStyle;
	      }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth);
	    }
	    function getColorOrGradient(spec, bottom, top, defaultColor) {
	      if (typeof spec == "string") return spec;else {
	        // assume this is a gradient spec; IE currently only
	        // supports a simple vertical gradient properly, so that's
	        // what we support too
	        var gradient = ctx.createLinearGradient(0, top, 0, bottom);
	        for (var i = 0, l = spec.colors.length; i < l; ++i) {
	          var c = spec.colors[i];
	          if (typeof c != "string") {
	            var co = $.color.parse(defaultColor);
	            if (c.brightness != null) co = co.scale('rgb', c.brightness);
	            if (c.opacity != null) co.a *= c.opacity;
	            c = co.toString();
	          }
	          gradient.addColorStop(i / (l - 1), c);
	        }
	        return gradient;
	      }
	    }
	  }

	  // Add the plot function to the top level of the jQuery object

	  $.plot = function (placeholder, data, options) {
	    //var t0 = new Date();
	    var plot = new Plot($(placeholder), data, options, $.plot.plugins);
	    //(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime()));
	    return plot;
	  };
	  $.plot.version = "0.8.3";
	  $.plot.plugins = [];

	  // Also add the plot function as a chainable property

	  $.fn.plot = function (data, options) {
	    return this.each(function () {
	      $.plot(this, data, options);
	    });
	  };

	  // round to nearby lower multiple of base
	  function floorInBase(n, base) {
	    return base * Math.floor(n / base);
	  }
	})(jQuery);

	var jquery_flot_pie = {};

	/* Flot plugin for rendering pie charts.

	Copyright (c) 2007-2014 IOLA and Ole Laursen.
	Licensed under the MIT license.

	The plugin assumes that each series has a single data value, and that each
	value is a positive integer or zero.  Negative numbers don't make sense for a
	pie chart, and have unpredictable results.  The values do NOT need to be
	passed in as percentages; the plugin will calculate the total and per-slice
	percentages internally.

	* Created by Brian Medendorp

	* Updated with contributions from btburnett3, Anthony Aragues and Xavi Ivars

	The plugin supports these options:

		series: {
			pie: {
				show: true/false
				radius: 0-1 for percentage of fullsize, or a specified pixel length, or 'auto'
				innerRadius: 0-1 for percentage of fullsize or a specified pixel length, for creating a donut effect
				startAngle: 0-2 factor of PI used for starting angle (in radians) i.e 3/2 starts at the top, 0 and 2 have the same result
				tilt: 0-1 for percentage to tilt the pie, where 1 is no tilt, and 0 is completely flat (nothing will show)
				offset: {
					top: integer value to move the pie up or down
					left: integer value to move the pie left or right, or 'auto'
				},
				stroke: {
					color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#FFF')
					width: integer pixel width of the stroke
				},
				label: {
					show: true/false, or 'auto'
					formatter:  a user-defined function that modifies the text/style of the label text
					radius: 0-1 for percentage of fullsize, or a specified pixel length
					background: {
						color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#000')
						opacity: 0-1
					},
					threshold: 0-1 for the percentage value at which to hide labels (if they're too small)
				},
				combine: {
					threshold: 0-1 for the percentage value at which to combine slices (if they're too small)
					color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#CCC'), if null, the plugin will automatically use the color of the first slice to be combined
					label: any text value of what the combined slice should be labeled
				}
				highlight: {
					opacity: 0-1
				}
			}
		}

	More detail and specific examples can be found in the included HTML file.

	*/
	var hasRequiredJquery_flot_pie;
	function requireJquery_flot_pie() {
	  if (hasRequiredJquery_flot_pie) return jquery_flot_pie;
	  hasRequiredJquery_flot_pie = 1;
	  (function ($) {
	    // Maximum redraw attempts when fitting labels within the plot

	    var REDRAW_ATTEMPTS = 10;

	    // Factor by which to shrink the pie when fitting labels within the plot

	    var REDRAW_SHRINK = 0.95;
	    function init(plot) {
	      var canvas = null,
	        target = null,
	        options = null,
	        maxRadius = null,
	        centerLeft = null,
	        centerTop = null,
	        processed = false,
	        ctx = null;

	      // interactive variables

	      var highlights = [];

	      // add hook to determine if pie plugin in enabled, and then perform necessary operations

	      plot.hooks.processOptions.push(function (plot, options) {
	        if (options.series.pie.show) {
	          options.grid.show = false;

	          // set labels.show

	          if (options.series.pie.label.show == "auto") {
	            if (options.legend.show) {
	              options.series.pie.label.show = false;
	            } else {
	              options.series.pie.label.show = true;
	            }
	          }

	          // set radius

	          if (options.series.pie.radius == "auto") {
	            if (options.series.pie.label.show) {
	              options.series.pie.radius = 3 / 4;
	            } else {
	              options.series.pie.radius = 1;
	            }
	          }

	          // ensure sane tilt

	          if (options.series.pie.tilt > 1) {
	            options.series.pie.tilt = 1;
	          } else if (options.series.pie.tilt < 0) {
	            options.series.pie.tilt = 0;
	          }
	        }
	      });
	      plot.hooks.bindEvents.push(function (plot, eventHolder) {
	        var options = plot.getOptions();
	        if (options.series.pie.show) {
	          if (options.grid.hoverable) {
	            eventHolder.unbind("mousemove").mousemove(onMouseMove);
	          }
	          if (options.grid.clickable) {
	            eventHolder.unbind("click").click(onClick);
	          }
	        }
	      });
	      plot.hooks.processDatapoints.push(function (plot, series, data, datapoints) {
	        var options = plot.getOptions();
	        if (options.series.pie.show) {
	          processDatapoints(plot);
	        }
	      });
	      plot.hooks.drawOverlay.push(function (plot, octx) {
	        var options = plot.getOptions();
	        if (options.series.pie.show) {
	          drawOverlay(plot, octx);
	        }
	      });
	      plot.hooks.draw.push(function (plot, newCtx) {
	        var options = plot.getOptions();
	        if (options.series.pie.show) {
	          draw(plot, newCtx);
	        }
	      });
	      function processDatapoints(plot, series, datapoints) {
	        if (!processed) {
	          processed = true;
	          canvas = plot.getCanvas();
	          target = $(canvas).parent();
	          options = plot.getOptions();
	          plot.setData(combine(plot.getData()));
	        }
	      }
	      function combine(data) {
	        var total = 0,
	          combined = 0,
	          numCombined = 0,
	          color = options.series.pie.combine.color,
	          newdata = [];

	        // Fix up the raw data from Flot, ensuring the data is numeric

	        for (var i = 0; i < data.length; ++i) {
	          var value = data[i].data;

	          // If the data is an array, we'll assume that it's a standard
	          // Flot x-y pair, and are concerned only with the second value.

	          // Note how we use the original array, rather than creating a
	          // new one; this is more efficient and preserves any extra data
	          // that the user may have stored in higher indexes.

	          if ($.isArray(value) && value.length == 1) {
	            value = value[0];
	          }
	          if ($.isArray(value)) {
	            // Equivalent to $.isNumeric() but compatible with jQuery < 1.7
	            if (!isNaN(parseFloat(value[1])) && isFinite(value[1])) {
	              value[1] = +value[1];
	            } else {
	              value[1] = 0;
	            }
	          } else if (!isNaN(parseFloat(value)) && isFinite(value)) {
	            value = [1, +value];
	          } else {
	            value = [1, 0];
	          }
	          data[i].data = [value];
	        }

	        // Sum up all the slices, so we can calculate percentages for each

	        for (var i = 0; i < data.length; ++i) {
	          total += data[i].data[0][1];
	        }

	        // Count the number of slices with percentages below the combine
	        // threshold; if it turns out to be just one, we won't combine.

	        for (var i = 0; i < data.length; ++i) {
	          var value = data[i].data[0][1];
	          if (value / total <= options.series.pie.combine.threshold) {
	            combined += value;
	            numCombined++;
	            if (!color) {
	              color = data[i].color;
	            }
	          }
	        }
	        for (var i = 0; i < data.length; ++i) {
	          var value = data[i].data[0][1];
	          if (numCombined < 2 || value / total > options.series.pie.combine.threshold) {
	            newdata.push($.extend(data[i], {
	              /* extend to allow keeping all other original data values
	                 and using them e.g. in labelFormatter. */
	              data: [[1, value]],
	              color: data[i].color,
	              label: data[i].label,
	              angle: value * Math.PI * 2 / total,
	              percent: value / (total / 100)
	            }));
	          }
	        }
	        if (numCombined > 1) {
	          newdata.push({
	            data: [[1, combined]],
	            color: color,
	            label: options.series.pie.combine.label,
	            angle: combined * Math.PI * 2 / total,
	            percent: combined / (total / 100)
	          });
	        }
	        return newdata;
	      }
	      function draw(plot, newCtx) {
	        if (!target) {
	          return; // if no series were passed
	        }
	        var canvasWidth = plot.getPlaceholder().width(),
	          canvasHeight = plot.getPlaceholder().height(),
	          legendWidth = target.children().filter(".legend").children().width() || 0;
	        ctx = newCtx;

	        // WARNING: HACK! REWRITE THIS CODE AS SOON AS POSSIBLE!

	        // When combining smaller slices into an 'other' slice, we need to
	        // add a new series.  Since Flot gives plugins no way to modify the
	        // list of series, the pie plugin uses a hack where the first call
	        // to processDatapoints results in a call to setData with the new
	        // list of series, then subsequent processDatapoints do nothing.

	        // The plugin-global 'processed' flag is used to control this hack;
	        // it starts out false, and is set to true after the first call to
	        // processDatapoints.

	        // Unfortunately this turns future setData calls into no-ops; they
	        // call processDatapoints, the flag is true, and nothing happens.

	        // To fix this we'll set the flag back to false here in draw, when
	        // all series have been processed, so the next sequence of calls to
	        // processDatapoints once again starts out with a slice-combine.
	        // This is really a hack; in 0.9 we need to give plugins a proper
	        // way to modify series before any processing begins.

	        processed = false;

	        // calculate maximum radius and center point

	        maxRadius = Math.min(canvasWidth, canvasHeight / options.series.pie.tilt) / 2;
	        centerTop = canvasHeight / 2 + options.series.pie.offset.top;
	        centerLeft = canvasWidth / 2;
	        if (options.series.pie.offset.left == "auto") {
	          if (options.legend.position.match("w")) {
	            centerLeft += legendWidth / 2;
	          } else {
	            centerLeft -= legendWidth / 2;
	          }
	          if (centerLeft < maxRadius) {
	            centerLeft = maxRadius;
	          } else if (centerLeft > canvasWidth - maxRadius) {
	            centerLeft = canvasWidth - maxRadius;
	          }
	        } else {
	          centerLeft += options.series.pie.offset.left;
	        }
	        var slices = plot.getData(),
	          attempts = 0;

	        // Keep shrinking the pie's radius until drawPie returns true,
	        // indicating that all the labels fit, or we try too many times.

	        do {
	          if (attempts > 0) {
	            maxRadius *= REDRAW_SHRINK;
	          }
	          attempts += 1;
	          clear();
	          if (options.series.pie.tilt <= 0.8) {
	            drawShadow();
	          }
	        } while (!drawPie() && attempts < REDRAW_ATTEMPTS);
	        if (attempts >= REDRAW_ATTEMPTS) {
	          clear();
	          target.prepend("<div class='error'>Could not draw pie with labels contained inside canvas</div>");
	        }
	        if (plot.setSeries && plot.insertLegend) {
	          plot.setSeries(slices);
	          plot.insertLegend();
	        }

	        // we're actually done at this point, just defining internal functions at this point

	        function clear() {
	          ctx.clearRect(0, 0, canvasWidth, canvasHeight);
	          target.children().filter(".pieLabel, .pieLabelBackground").remove();
	        }
	        function drawShadow() {
	          var shadowLeft = options.series.pie.shadow.left;
	          var shadowTop = options.series.pie.shadow.top;
	          var edge = 10;
	          var alpha = options.series.pie.shadow.alpha;
	          var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
	          if (radius >= canvasWidth / 2 - shadowLeft || radius * options.series.pie.tilt >= canvasHeight / 2 - shadowTop || radius <= edge) {
	            return; // shadow would be outside canvas, so don't draw it
	          }
	          ctx.save();
	          ctx.translate(shadowLeft, shadowTop);
	          ctx.globalAlpha = alpha;
	          ctx.fillStyle = "#000";

	          // center and rotate to starting position

	          ctx.translate(centerLeft, centerTop);
	          ctx.scale(1, options.series.pie.tilt);

	          //radius -= edge;

	          for (var i = 1; i <= edge; i++) {
	            ctx.beginPath();
	            ctx.arc(0, 0, radius, 0, Math.PI * 2, false);
	            ctx.fill();
	            radius -= i;
	          }
	          ctx.restore();
	        }
	        function drawPie() {
	          var startAngle = Math.PI * options.series.pie.startAngle;
	          var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;

	          // center and rotate to starting position

	          ctx.save();
	          ctx.translate(centerLeft, centerTop);
	          ctx.scale(1, options.series.pie.tilt);
	          //ctx.rotate(startAngle); // start at top; -- This doesn't work properly in Opera

	          // draw slices

	          ctx.save();
	          var currentAngle = startAngle;
	          for (var i = 0; i < slices.length; ++i) {
	            slices[i].startAngle = currentAngle;
	            drawSlice(slices[i].angle, slices[i].color, true);
	          }
	          ctx.restore();

	          // draw slice outlines

	          if (options.series.pie.stroke.width > 0) {
	            ctx.save();
	            ctx.lineWidth = options.series.pie.stroke.width;
	            currentAngle = startAngle;
	            for (var i = 0; i < slices.length; ++i) {
	              drawSlice(slices[i].angle, options.series.pie.stroke.color, false);
	            }
	            ctx.restore();
	          }

	          // draw donut hole

	          drawDonutHole(ctx);
	          ctx.restore();

	          // Draw the labels, returning true if they fit within the plot

	          if (options.series.pie.label.show) {
	            return drawLabels();
	          } else return true;
	          function drawSlice(angle, color, fill) {
	            if (angle <= 0 || isNaN(angle)) {
	              return;
	            }
	            if (fill) {
	              ctx.fillStyle = color;
	            } else {
	              ctx.strokeStyle = color;
	              ctx.lineJoin = "round";
	            }
	            ctx.beginPath();
	            if (Math.abs(angle - Math.PI * 2) > 0.000000001) {
	              ctx.moveTo(0, 0); // Center of the pie
	            }

	            //ctx.arc(0, 0, radius, 0, angle, false); // This doesn't work properly in Opera
	            ctx.arc(0, 0, radius, currentAngle, currentAngle + angle / 2, false);
	            ctx.arc(0, 0, radius, currentAngle + angle / 2, currentAngle + angle, false);
	            ctx.closePath();
	            //ctx.rotate(angle); // This doesn't work properly in Opera
	            currentAngle += angle;
	            if (fill) {
	              ctx.fill();
	            } else {
	              ctx.stroke();
	            }
	          }
	          function drawLabels() {
	            var currentAngle = startAngle;
	            var radius = options.series.pie.label.radius > 1 ? options.series.pie.label.radius : maxRadius * options.series.pie.label.radius;
	            for (var i = 0; i < slices.length; ++i) {
	              if (slices[i].percent >= options.series.pie.label.threshold * 100) {
	                if (!drawLabel(slices[i], currentAngle, i)) {
	                  return false;
	                }
	              }
	              currentAngle += slices[i].angle;
	            }
	            return true;
	            function drawLabel(slice, startAngle, index) {
	              if (slice.data[0][1] == 0) {
	                return true;
	              }

	              // format label text

	              var lf = options.legend.labelFormatter,
	                text,
	                plf = options.series.pie.label.formatter;
	              if (lf) {
	                text = lf(slice.label, slice);
	              } else {
	                text = slice.label;
	              }
	              if (plf) {
	                text = plf(text, slice);
	              }
	              var halfAngle = (startAngle + slice.angle + startAngle) / 2;
	              var x = centerLeft + Math.round(Math.cos(halfAngle) * radius);
	              var y = centerTop + Math.round(Math.sin(halfAngle) * radius) * options.series.pie.tilt;
	              var html = "<span class='pieLabel' id='pieLabel" + index + "' style='position:absolute;top:" + y + "px;left:" + x + "px;'>" + text + "</span>";
	              target.append(html);
	              var label = target.children("#pieLabel" + index);
	              var labelTop = y - label.height() / 2;
	              var labelLeft = x - label.width() / 2;
	              label.css("top", labelTop);
	              label.css("left", labelLeft);

	              // check to make sure that the label is not outside the canvas

	              if (0 - labelTop > 0 || 0 - labelLeft > 0 || canvasHeight - (labelTop + label.height()) < 0 || canvasWidth - (labelLeft + label.width()) < 0) {
	                return false;
	              }
	              if (options.series.pie.label.background.opacity != 0) {
	                // put in the transparent background separately to avoid blended labels and label boxes

	                var c = options.series.pie.label.background.color;
	                if (c == null) {
	                  c = slice.color;
	                }
	                var pos = "top:" + labelTop + "px;left:" + labelLeft + "px;";
	                $("<div class='pieLabelBackground' style='position:absolute;width:" + label.width() + "px;height:" + label.height() + "px;" + pos + "background-color:" + c + ";'></div>").css("opacity", options.series.pie.label.background.opacity).insertBefore(label);
	              }
	              return true;
	            } // end individual label function
	          } // end drawLabels function
	        } // end drawPie function
	      } // end draw function

	      // Placed here because it needs to be accessed from multiple locations

	      function drawDonutHole(layer) {
	        if (options.series.pie.innerRadius > 0) {
	          // subtract the center

	          layer.save();
	          var innerRadius = options.series.pie.innerRadius > 1 ? options.series.pie.innerRadius : maxRadius * options.series.pie.innerRadius;
	          layer.globalCompositeOperation = "destination-out"; // this does not work with excanvas, but it will fall back to using the stroke color
	          layer.beginPath();
	          layer.fillStyle = options.series.pie.stroke.color;
	          layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false);
	          layer.fill();
	          layer.closePath();
	          layer.restore();

	          // add inner stroke

	          layer.save();
	          layer.beginPath();
	          layer.strokeStyle = options.series.pie.stroke.color;
	          layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false);
	          layer.stroke();
	          layer.closePath();
	          layer.restore();

	          // TODO: add extra shadow inside hole (with a mask) if the pie is tilted.
	        }
	      }

	      //-- Additional Interactive related functions --

	      function isPointInPoly(poly, pt) {
	        for (var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i) (poly[i][1] <= pt[1] && pt[1] < poly[j][1] || poly[j][1] <= pt[1] && pt[1] < poly[i][1]) && pt[0] < (poly[j][0] - poly[i][0]) * (pt[1] - poly[i][1]) / (poly[j][1] - poly[i][1]) + poly[i][0] && (c = !c);
	        return c;
	      }
	      function findNearbySlice(mouseX, mouseY) {
	        var slices = plot.getData(),
	          options = plot.getOptions(),
	          radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius,
	          x,
	          y;
	        for (var i = 0; i < slices.length; ++i) {
	          var s = slices[i];
	          if (s.pie.show) {
	            ctx.save();
	            ctx.beginPath();
	            ctx.moveTo(0, 0); // Center of the pie
	            //ctx.scale(1, options.series.pie.tilt);	// this actually seems to break everything when here.
	            ctx.arc(0, 0, radius, s.startAngle, s.startAngle + s.angle / 2, false);
	            ctx.arc(0, 0, radius, s.startAngle + s.angle / 2, s.startAngle + s.angle, false);
	            ctx.closePath();
	            x = mouseX - centerLeft;
	            y = mouseY - centerTop;
	            if (ctx.isPointInPath) {
	              if (ctx.isPointInPath(mouseX - centerLeft, mouseY - centerTop)) {
	                ctx.restore();
	                return {
	                  datapoint: [s.percent, s.data],
	                  dataIndex: 0,
	                  series: s,
	                  seriesIndex: i
	                };
	              }
	            } else {
	              // excanvas for IE doesn;t support isPointInPath, this is a workaround.

	              var p1X = radius * Math.cos(s.startAngle),
	                p1Y = radius * Math.sin(s.startAngle),
	                p2X = radius * Math.cos(s.startAngle + s.angle / 4),
	                p2Y = radius * Math.sin(s.startAngle + s.angle / 4),
	                p3X = radius * Math.cos(s.startAngle + s.angle / 2),
	                p3Y = radius * Math.sin(s.startAngle + s.angle / 2),
	                p4X = radius * Math.cos(s.startAngle + s.angle / 1.5),
	                p4Y = radius * Math.sin(s.startAngle + s.angle / 1.5),
	                p5X = radius * Math.cos(s.startAngle + s.angle),
	                p5Y = radius * Math.sin(s.startAngle + s.angle),
	                arrPoly = [[0, 0], [p1X, p1Y], [p2X, p2Y], [p3X, p3Y], [p4X, p4Y], [p5X, p5Y]],
	                arrPoint = [x, y];

	              // TODO: perhaps do some mathmatical trickery here with the Y-coordinate to compensate for pie tilt?

	              if (isPointInPoly(arrPoly, arrPoint)) {
	                ctx.restore();
	                return {
	                  datapoint: [s.percent, s.data],
	                  dataIndex: 0,
	                  series: s,
	                  seriesIndex: i
	                };
	              }
	            }
	            ctx.restore();
	          }
	        }
	        return null;
	      }
	      function onMouseMove(e) {
	        triggerClickHoverEvent("plothover", e);
	      }
	      function onClick(e) {
	        triggerClickHoverEvent("plotclick", e);
	      }

	      // trigger click or hover event (they send the same parameters so we share their code)

	      function triggerClickHoverEvent(eventname, e) {
	        var offset = plot.offset();
	        var canvasX = parseInt(e.pageX - offset.left);
	        var canvasY = parseInt(e.pageY - offset.top);
	        var item = findNearbySlice(canvasX, canvasY);
	        if (options.grid.autoHighlight) {
	          // clear auto-highlights

	          for (var i = 0; i < highlights.length; ++i) {
	            var h = highlights[i];
	            if (h.auto == eventname && !(item && h.series == item.series)) {
	              unhighlight(h.series);
	            }
	          }
	        }

	        // highlight the slice

	        if (item) {
	          highlight(item.series, eventname);
	        }

	        // trigger any hover bind events

	        var pos = {
	          pageX: e.pageX,
	          pageY: e.pageY
	        };
	        target.trigger(eventname, [pos, item]);
	      }
	      function highlight(s, auto) {
	        //if (typeof s == "number") {
	        //	s = series[s];
	        //}

	        var i = indexOfHighlight(s);
	        if (i == -1) {
	          highlights.push({
	            series: s,
	            auto: auto
	          });
	          plot.triggerRedrawOverlay();
	        } else if (!auto) {
	          highlights[i].auto = false;
	        }
	      }
	      function unhighlight(s) {
	        if (s == null) {
	          highlights = [];
	          plot.triggerRedrawOverlay();
	        }

	        //if (typeof s == "number") {
	        //	s = series[s];
	        //}

	        var i = indexOfHighlight(s);
	        if (i != -1) {
	          highlights.splice(i, 1);
	          plot.triggerRedrawOverlay();
	        }
	      }
	      function indexOfHighlight(s) {
	        for (var i = 0; i < highlights.length; ++i) {
	          var h = highlights[i];
	          if (h.series == s) return i;
	        }
	        return -1;
	      }
	      function drawOverlay(plot, octx) {
	        var options = plot.getOptions();
	        var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
	        octx.save();
	        octx.translate(centerLeft, centerTop);
	        octx.scale(1, options.series.pie.tilt);
	        for (var i = 0; i < highlights.length; ++i) {
	          drawHighlight(highlights[i].series);
	        }
	        drawDonutHole(octx);
	        octx.restore();
	        function drawHighlight(series) {
	          if (series.angle <= 0 || isNaN(series.angle)) {
	            return;
	          }

	          //octx.fillStyle = parseColor(options.series.pie.highlight.color).scale(null, null, null, options.series.pie.highlight.opacity).toString();
	          octx.fillStyle = "rgba(255, 255, 255, " + options.series.pie.highlight.opacity + ")"; // this is temporary until we have access to parseColor
	          octx.beginPath();
	          if (Math.abs(series.angle - Math.PI * 2) > 0.000000001) {
	            octx.moveTo(0, 0); // Center of the pie
	          }
	          octx.arc(0, 0, radius, series.startAngle, series.startAngle + series.angle / 2, false);
	          octx.arc(0, 0, radius, series.startAngle + series.angle / 2, series.startAngle + series.angle, false);
	          octx.closePath();
	          octx.fill();
	        }
	      }
	    } // end init (plugin body)

	    // define pie specific options and their default values

	    var options = {
	      series: {
	        pie: {
	          show: false,
	          radius: "auto",
	          // actual radius of the visible pie (based on full calculated radius if <=1, or hard pixel value)
	          innerRadius: 0,
	          /* for donut */
	          startAngle: 3 / 2,
	          tilt: 1,
	          shadow: {
	            left: 5,
	            // shadow left offset
	            top: 15,
	            // shadow top offset
	            alpha: 0.02 // shadow alpha
	          },
	          offset: {
	            top: 0,
	            left: "auto"
	          },
	          stroke: {
	            color: "#fff",
	            width: 1
	          },
	          label: {
	            show: "auto",
	            formatter: function (label, slice) {
	              return "<div style='font-size:x-small;text-align:center;padding:2px;color:" + slice.color + ";'>" + label + "<br/>" + Math.round(slice.percent) + "%</div>";
	            },
	            // formatter function
	            radius: 1,
	            // radius at which to place the labels (based on full calculated radius if <=1, or hard pixel value)
	            background: {
	              color: null,
	              opacity: 0
	            },
	            threshold: 0 // percentage at which to hide the label (i.e. the slice is too narrow)
	          },
	          combine: {
	            threshold: -1,
	            // percentage at which to combine little slices into one larger slice
	            color: null,
	            // color to give the new slice (auto-generated if null)
	            label: "Other" // label to give the new slice
	          },
	          highlight: {
	            //color: "#fff",		// will add this functionality once parseColor is available
	            opacity: 0.5
	          }
	        }
	      }
	    };
	    $.plot.plugins.push({
	      init: init,
	      options: options,
	      name: "pie",
	      version: "1.1"
	    });
	  })(jQuery);
	  return jquery_flot_pie;
	}

	requireJquery_flot_pie();

	/* Flot plugin for selecting regions of a plot.

	Copyright (c) 2007-2014 IOLA and Ole Laursen.
	Licensed under the MIT license.

	The plugin supports these options:

	selection: {
		mode: null or "x" or "y" or "xy",
		color: color,
		shape: "round" or "miter" or "bevel",
		minSize: number of pixels
	}

	Selection support is enabled by setting the mode to one of "x", "y" or "xy".
	In "x" mode, the user will only be able to specify the x range, similarly for
	"y" mode. For "xy", the selection becomes a rectangle where both ranges can be
	specified. "color" is color of the selection (if you need to change the color
	later on, you can get to it with plot.getOptions().selection.color). "shape"
	is the shape of the corners of the selection.

	"minSize" is the minimum size a selection can be in pixels. This value can
	be customized to determine the smallest size a selection can be and still
	have the selection rectangle be displayed. When customizing this value, the
	fact that it refers to pixels, not axis units must be taken into account.
	Thus, for example, if there is a bar graph in time mode with BarWidth set to 1
	minute, setting "minSize" to 1 will not make the minimum selection size 1
	minute, but rather 1 pixel. Note also that setting "minSize" to 0 will prevent
	"plotunselected" events from being fired when the user clicks the mouse without
	dragging.

	When selection support is enabled, a "plotselected" event will be emitted on
	the DOM element you passed into the plot function. The event handler gets a
	parameter with the ranges selected on the axes, like this:

		placeholder.bind( "plotselected", function( event, ranges ) {
			alert("You selected " + ranges.xaxis.from + " to " + ranges.xaxis.to)
			// similar for yaxis - with multiple axes, the extra ones are in
			// x2axis, x3axis, ...
		});

	The "plotselected" event is only fired when the user has finished making the
	selection. A "plotselecting" event is fired during the process with the same
	parameters as the "plotselected" event, in case you want to know what's
	happening while it's happening,

	A "plotunselected" event with no arguments is emitted when the user clicks the
	mouse to remove the selection. As stated above, setting "minSize" to 0 will
	destroy this behavior.

	The plugin allso adds the following methods to the plot object:

	- setSelection( ranges, preventEvent )

	  Set the selection rectangle. The passed in ranges is on the same form as
	  returned in the "plotselected" event. If the selection mode is "x", you
	  should put in either an xaxis range, if the mode is "y" you need to put in
	  an yaxis range and both xaxis and yaxis if the selection mode is "xy", like
	  this:

		setSelection({ xaxis: { from: 0, to: 10 }, yaxis: { from: 40, to: 60 } });

	  setSelection will trigger the "plotselected" event when called. If you don't
	  want that to happen, e.g. if you're inside a "plotselected" handler, pass
	  true as the second parameter. If you are using multiple axes, you can
	  specify the ranges on any of those, e.g. as x2axis/x3axis/... instead of
	  xaxis, the plugin picks the first one it sees.

	- clearSelection( preventEvent )

	  Clear the selection rectangle. Pass in true to avoid getting a
	  "plotunselected" event.

	- getSelection()

	  Returns the current selection in the same format as the "plotselected"
	  event. If there's currently no selection, the function returns null.

	*/

	(function ($) {
	  function init(plot) {
	    var selection = {
	      first: {
	        x: -1,
	        y: -1
	      },
	      second: {
	        x: -1,
	        y: -1
	      },
	      show: false,
	      active: false
	    };

	    // FIXME: The drag handling implemented here should be
	    // abstracted out, there's some similar code from a library in
	    // the navigation plugin, this should be massaged a bit to fit
	    // the Flot cases here better and reused. Doing this would
	    // make this plugin much slimmer.
	    var savedhandlers = {};
	    var mouseUpHandler = null;
	    function onMouseMove(e) {
	      if (selection.active) {
	        updateSelection(e);
	        plot.getPlaceholder().trigger("plotselecting", [getSelection()]);
	      }
	    }
	    function onMouseDown(e) {
	      if (e.which != 1)
	        // only accept left-click
	        return;

	      // cancel out any text selections
	      document.body.focus();

	      // prevent text selection and drag in old-school browsers
	      if (document.onselectstart !== undefined && savedhandlers.onselectstart == null) {
	        savedhandlers.onselectstart = document.onselectstart;
	        document.onselectstart = function () {
	          return false;
	        };
	      }
	      if (document.ondrag !== undefined && savedhandlers.ondrag == null) {
	        savedhandlers.ondrag = document.ondrag;
	        document.ondrag = function () {
	          return false;
	        };
	      }
	      setSelectionPos(selection.first, e);
	      selection.active = true;

	      // this is a bit silly, but we have to use a closure to be
	      // able to whack the same handler again
	      mouseUpHandler = function (e) {
	        onMouseUp(e);
	      };
	      $(document).one("mouseup", mouseUpHandler);
	    }
	    function onMouseUp(e) {
	      mouseUpHandler = null;

	      // revert drag stuff for old-school browsers
	      if (document.onselectstart !== undefined) document.onselectstart = savedhandlers.onselectstart;
	      if (document.ondrag !== undefined) document.ondrag = savedhandlers.ondrag;

	      // no more dragging
	      selection.active = false;
	      updateSelection(e);
	      if (selectionIsSane()) triggerSelectedEvent();else {
	        // this counts as a clear
	        plot.getPlaceholder().trigger("plotunselected", []);
	        plot.getPlaceholder().trigger("plotselecting", [null]);
	      }
	      return false;
	    }
	    function getSelection() {
	      if (!selectionIsSane()) return null;
	      if (!selection.show) return null;
	      var r = {},
	        c1 = selection.first,
	        c2 = selection.second;
	      $.each(plot.getAxes(), function (name, axis) {
	        if (axis.used) {
	          var p1 = axis.c2p(c1[axis.direction]),
	            p2 = axis.c2p(c2[axis.direction]);
	          r[name] = {
	            from: Math.min(p1, p2),
	            to: Math.max(p1, p2)
	          };
	        }
	      });
	      return r;
	    }
	    function triggerSelectedEvent() {
	      var r = getSelection();
	      plot.getPlaceholder().trigger("plotselected", [r]);

	      // backwards-compat stuff, to be removed in future
	      if (r.xaxis && r.yaxis) plot.getPlaceholder().trigger("selected", [{
	        x1: r.xaxis.from,
	        y1: r.yaxis.from,
	        x2: r.xaxis.to,
	        y2: r.yaxis.to
	      }]);
	    }
	    function clamp(min, value, max) {
	      return value < min ? min : value > max ? max : value;
	    }
	    function setSelectionPos(pos, e) {
	      var o = plot.getOptions();
	      var offset = plot.getPlaceholder().offset();
	      var plotOffset = plot.getPlotOffset();
	      pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plot.width());
	      pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plot.height());
	      if (o.selection.mode == "y") pos.x = pos == selection.first ? 0 : plot.width();
	      if (o.selection.mode == "x") pos.y = pos == selection.first ? 0 : plot.height();
	    }
	    function updateSelection(pos) {
	      if (pos.pageX == null) return;
	      setSelectionPos(selection.second, pos);
	      if (selectionIsSane()) {
	        selection.show = true;
	        plot.triggerRedrawOverlay();
	      } else clearSelection(true);
	    }
	    function clearSelection(preventEvent) {
	      if (selection.show) {
	        selection.show = false;
	        plot.triggerRedrawOverlay();
	        if (!preventEvent) plot.getPlaceholder().trigger("plotunselected", []);
	      }
	    }

	    // function taken from markings support in Flot
	    function extractRange(ranges, coord) {
	      var axis,
	        from,
	        to,
	        key,
	        axes = plot.getAxes();
	      for (var k in axes) {
	        axis = axes[k];
	        if (axis.direction == coord) {
	          key = coord + axis.n + "axis";
	          if (!ranges[key] && axis.n == 1) key = coord + "axis"; // support x1axis as xaxis
	          if (ranges[key]) {
	            from = ranges[key].from;
	            to = ranges[key].to;
	            break;
	          }
	        }
	      }

	      // backwards-compat stuff - to be removed in future
	      if (!ranges[key]) {
	        axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0];
	        from = ranges[coord + "1"];
	        to = ranges[coord + "2"];
	      }

	      // auto-reverse as an added bonus
	      if (from != null && to != null && from > to) {
	        var tmp = from;
	        from = to;
	        to = tmp;
	      }
	      return {
	        from: from,
	        to: to,
	        axis: axis
	      };
	    }
	    function setSelection(ranges, preventEvent) {
	      var range,
	        o = plot.getOptions();
	      if (o.selection.mode == "y") {
	        selection.first.x = 0;
	        selection.second.x = plot.width();
	      } else {
	        range = extractRange(ranges, "x");
	        selection.first.x = range.axis.p2c(range.from);
	        selection.second.x = range.axis.p2c(range.to);
	      }
	      if (o.selection.mode == "x") {
	        selection.first.y = 0;
	        selection.second.y = plot.height();
	      } else {
	        range = extractRange(ranges, "y");
	        selection.first.y = range.axis.p2c(range.from);
	        selection.second.y = range.axis.p2c(range.to);
	      }
	      selection.show = true;
	      plot.triggerRedrawOverlay();
	      if (!preventEvent && selectionIsSane()) triggerSelectedEvent();
	    }
	    function selectionIsSane() {
	      var minSize = plot.getOptions().selection.minSize;
	      return Math.abs(selection.second.x - selection.first.x) >= minSize && Math.abs(selection.second.y - selection.first.y) >= minSize;
	    }
	    plot.clearSelection = clearSelection;
	    plot.setSelection = setSelection;
	    plot.getSelection = getSelection;
	    plot.hooks.bindEvents.push(function (plot, eventHolder) {
	      var o = plot.getOptions();
	      if (o.selection.mode != null) {
	        eventHolder.mousemove(onMouseMove);
	        eventHolder.mousedown(onMouseDown);
	      }
	    });
	    plot.hooks.drawOverlay.push(function (plot, ctx) {
	      // draw selection
	      if (selection.show && selectionIsSane()) {
	        var plotOffset = plot.getPlotOffset();
	        var o = plot.getOptions();
	        ctx.save();
	        ctx.translate(plotOffset.left, plotOffset.top);
	        var c = $.color.parse(o.selection.color);
	        ctx.strokeStyle = c.scale('a', 0.8).toString();
	        ctx.lineWidth = 1;
	        ctx.lineJoin = o.selection.shape;
	        ctx.fillStyle = c.scale('a', 0.4).toString();
	        var x = Math.min(selection.first.x, selection.second.x) + 0.5,
	          y = Math.min(selection.first.y, selection.second.y) + 0.5,
	          w = Math.abs(selection.second.x - selection.first.x) - 1,
	          h = Math.abs(selection.second.y - selection.first.y) - 1;
	        ctx.fillRect(x, y, w, h);
	        ctx.strokeRect(x, y, w, h);
	        ctx.restore();
	      }
	    });
	    plot.hooks.shutdown.push(function (plot, eventHolder) {
	      eventHolder.unbind("mousemove", onMouseMove);
	      eventHolder.unbind("mousedown", onMouseDown);
	      if (mouseUpHandler) $(document).unbind("mouseup", mouseUpHandler);
	    });
	  }
	  $.plot.plugins.push({
	    init: init,
	    options: {
	      selection: {
	        mode: null,
	        // one of null, "x", "y" or "xy"
	        color: "#e8cfac",
	        shape: "round",
	        // one of "round", "miter", or "bevel"
	        minSize: 5 // minimum number of pixels
	      }
	    },
	    name: 'selection',
	    version: '1.1'
	  });
	})(jQuery);

	var jquery_flot_time = {};

	/* Pretty handling of time axes.

	Copyright (c) 2007-2014 IOLA and Ole Laursen.
	Licensed under the MIT license.

	Set axis.mode to "time" to enable. See the section "Time series data" in
	API.txt for details.

	*/
	var hasRequiredJquery_flot_time;
	function requireJquery_flot_time() {
	  if (hasRequiredJquery_flot_time) return jquery_flot_time;
	  hasRequiredJquery_flot_time = 1;
	  (function ($) {
	    var options = {
	      xaxis: {
	        timezone: null,
	        // "browser" for local to the client or timezone for timezone-js
	        timeformat: null,
	        // format string to use
	        twelveHourClock: false,
	        // 12 or 24 time in time mode
	        monthNames: null // list of names of months
	      }
	    };

	    // round to nearby lower multiple of base

	    function floorInBase(n, base) {
	      return base * Math.floor(n / base);
	    }

	    // Returns a string with the date d formatted according to fmt.
	    // A subset of the Open Group's strftime format is supported.

	    function formatDate(d, fmt, monthNames, dayNames) {
	      if (typeof d.strftime == "function") {
	        return d.strftime(fmt);
	      }
	      var leftPad = function (n, pad) {
	        n = "" + n;
	        pad = "" + (pad == null ? "0" : pad);
	        return n.length == 1 ? pad + n : n;
	      };
	      var r = [];
	      var escape = false;
	      var hours = d.getHours();
	      var isAM = hours < 12;
	      if (monthNames == null) {
	        monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
	      }
	      if (dayNames == null) {
	        dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
	      }
	      var hours12;
	      if (hours > 12) {
	        hours12 = hours - 12;
	      } else if (hours == 0) {
	        hours12 = 12;
	      } else {
	        hours12 = hours;
	      }
	      for (var i = 0; i < fmt.length; ++i) {
	        var c = fmt.charAt(i);
	        if (escape) {
	          switch (c) {
	            case 'a':
	              c = "" + dayNames[d.getDay()];
	              break;
	            case 'b':
	              c = "" + monthNames[d.getMonth()];
	              break;
	            case 'd':
	              c = leftPad(d.getDate());
	              break;
	            case 'e':
	              c = leftPad(d.getDate(), " ");
	              break;
	            case 'h': // For back-compat with 0.7; remove in 1.0
	            case 'H':
	              c = leftPad(hours);
	              break;
	            case 'I':
	              c = leftPad(hours12);
	              break;
	            case 'l':
	              c = leftPad(hours12, " ");
	              break;
	            case 'm':
	              c = leftPad(d.getMonth() + 1);
	              break;
	            case 'M':
	              c = leftPad(d.getMinutes());
	              break;
	            // quarters not in Open Group's strftime specification
	            case 'q':
	              c = "" + (Math.floor(d.getMonth() / 3) + 1);
	              break;
	            case 'S':
	              c = leftPad(d.getSeconds());
	              break;
	            case 'y':
	              c = leftPad(d.getFullYear() % 100);
	              break;
	            case 'Y':
	              c = "" + d.getFullYear();
	              break;
	            case 'p':
	              c = isAM ? "" + "am" : "" + "pm";
	              break;
	            case 'P':
	              c = isAM ? "" + "AM" : "" + "PM";
	              break;
	            case 'w':
	              c = "" + d.getDay();
	              break;
	          }
	          r.push(c);
	          escape = false;
	        } else {
	          if (c == "%") {
	            escape = true;
	          } else {
	            r.push(c);
	          }
	        }
	      }
	      return r.join("");
	    }

	    // To have a consistent view of time-based data independent of which time
	    // zone the client happens to be in we need a date-like object independent
	    // of time zones.  This is done through a wrapper that only calls the UTC
	    // versions of the accessor methods.

	    function makeUtcWrapper(d) {
	      function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) {
	        sourceObj[sourceMethod] = function () {
	          return targetObj[targetMethod].apply(targetObj, arguments);
	        };
	      }
	      var utc = {
	        date: d
	      };

	      // support strftime, if found

	      if (d.strftime != undefined) {
	        addProxyMethod(utc, "strftime", d, "strftime");
	      }
	      addProxyMethod(utc, "getTime", d, "getTime");
	      addProxyMethod(utc, "setTime", d, "setTime");
	      var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"];
	      for (var p = 0; p < props.length; p++) {
	        addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]);
	        addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]);
	      }
	      return utc;
	    }

	    // select time zone strategy.  This returns a date-like object tied to the
	    // desired timezone

	    function dateGenerator(ts, opts) {
	      if (opts.timezone == "browser") {
	        return new Date(ts);
	      } else if (!opts.timezone || opts.timezone == "utc") {
	        return makeUtcWrapper(new Date(ts));
	      } else if (typeof timezoneJS != "undefined" && typeof timezoneJS.Date != "undefined") {
	        var d = new timezoneJS.Date();
	        // timezone-js is fickle, so be sure to set the time zone before
	        // setting the time.
	        d.setTimezone(opts.timezone);
	        d.setTime(ts);
	        return d;
	      } else {
	        return makeUtcWrapper(new Date(ts));
	      }
	    }

	    // map of app. size of time units in milliseconds

	    var timeUnitSize = {
	      "second": 1000,
	      "minute": 60 * 1000,
	      "hour": 60 * 60 * 1000,
	      "day": 24 * 60 * 60 * 1000,
	      "month": 30 * 24 * 60 * 60 * 1000,
	      "quarter": 3 * 30 * 24 * 60 * 60 * 1000,
	      "year": 365.2425 * 24 * 60 * 60 * 1000
	    };

	    // the allowed tick sizes, after 1 year we use
	    // an integer algorithm

	    var baseSpec = [[1, "second"], [2, "second"], [5, "second"], [10, "second"], [30, "second"], [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"], [30, "minute"], [1, "hour"], [2, "hour"], [4, "hour"], [8, "hour"], [12, "hour"], [1, "day"], [2, "day"], [3, "day"], [0.25, "month"], [0.5, "month"], [1, "month"], [2, "month"]];

	    // we don't know which variant(s) we'll need yet, but generating both is
	    // cheap

	    var specMonths = baseSpec.concat([[3, "month"], [6, "month"], [1, "year"]]);
	    var specQuarters = baseSpec.concat([[1, "quarter"], [2, "quarter"], [1, "year"]]);
	    function init(plot) {
	      plot.hooks.processOptions.push(function (plot, options) {
	        $.each(plot.getAxes(), function (axisName, axis) {
	          var opts = axis.options;
	          if (opts.mode == "time") {
	            axis.tickGenerator = function (axis) {
	              var ticks = [];
	              var d = dateGenerator(axis.min, opts);
	              var minSize = 0;

	              // make quarter use a possibility if quarters are
	              // mentioned in either of these options

	              var spec = opts.tickSize && opts.tickSize[1] === "quarter" || opts.minTickSize && opts.minTickSize[1] === "quarter" ? specQuarters : specMonths;
	              if (opts.minTickSize != null) {
	                if (typeof opts.tickSize == "number") {
	                  minSize = opts.tickSize;
	                } else {
	                  minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]];
	                }
	              }
	              for (var i = 0; i < spec.length - 1; ++i) {
	                if (axis.delta < (spec[i][0] * timeUnitSize[spec[i][1]] + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2 && spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) {
	                  break;
	                }
	              }
	              var size = spec[i][0];
	              var unit = spec[i][1];

	              // special-case the possibility of several years

	              if (unit == "year") {
	                // if given a minTickSize in years, just use it,
	                // ensuring that it's an integer

	                if (opts.minTickSize != null && opts.minTickSize[1] == "year") {
	                  size = Math.floor(opts.minTickSize[0]);
	                } else {
	                  var magn = Math.pow(10, Math.floor(Math.log(axis.delta / timeUnitSize.year) / Math.LN10));
	                  var norm = axis.delta / timeUnitSize.year / magn;
	                  if (norm < 1.5) {
	                    size = 1;
	                  } else if (norm < 3) {
	                    size = 2;
	                  } else if (norm < 7.5) {
	                    size = 5;
	                  } else {
	                    size = 10;
	                  }
	                  size *= magn;
	                }

	                // minimum size for years is 1

	                if (size < 1) {
	                  size = 1;
	                }
	              }
	              axis.tickSize = opts.tickSize || [size, unit];
	              var tickSize = axis.tickSize[0];
	              unit = axis.tickSize[1];
	              var step = tickSize * timeUnitSize[unit];
	              if (unit == "second") {
	                d.setSeconds(floorInBase(d.getSeconds(), tickSize));
	              } else if (unit == "minute") {
	                d.setMinutes(floorInBase(d.getMinutes(), tickSize));
	              } else if (unit == "hour") {
	                d.setHours(floorInBase(d.getHours(), tickSize));
	              } else if (unit == "month") {
	                d.setMonth(floorInBase(d.getMonth(), tickSize));
	              } else if (unit == "quarter") {
	                d.setMonth(3 * floorInBase(d.getMonth() / 3, tickSize));
	              } else if (unit == "year") {
	                d.setFullYear(floorInBase(d.getFullYear(), tickSize));
	              }

	              // reset smaller components

	              d.setMilliseconds(0);
	              if (step >= timeUnitSize.minute) {
	                d.setSeconds(0);
	              }
	              if (step >= timeUnitSize.hour) {
	                d.setMinutes(0);
	              }
	              if (step >= timeUnitSize.day) {
	                d.setHours(0);
	              }
	              if (step >= timeUnitSize.day * 4) {
	                d.setDate(1);
	              }
	              if (step >= timeUnitSize.month * 2) {
	                d.setMonth(floorInBase(d.getMonth(), 3));
	              }
	              if (step >= timeUnitSize.quarter * 2) {
	                d.setMonth(floorInBase(d.getMonth(), 6));
	              }
	              if (step >= timeUnitSize.year) {
	                d.setMonth(0);
	              }
	              var carry = 0;
	              var v = Number.NaN;
	              var prev;
	              do {
	                prev = v;
	                v = d.getTime();
	                ticks.push(v);
	                if (unit == "month" || unit == "quarter") {
	                  if (tickSize < 1) {
	                    // a bit complicated - we'll divide the
	                    // month/quarter up but we need to take
	                    // care of fractions so we don't end up in
	                    // the middle of a day

	                    d.setDate(1);
	                    var start = d.getTime();
	                    d.setMonth(d.getMonth() + (unit == "quarter" ? 3 : 1));
	                    var end = d.getTime();
	                    d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize);
	                    carry = d.getHours();
	                    d.setHours(0);
	                  } else {
	                    d.setMonth(d.getMonth() + tickSize * (unit == "quarter" ? 3 : 1));
	                  }
	                } else if (unit == "year") {
	                  d.setFullYear(d.getFullYear() + tickSize);
	                } else {
	                  d.setTime(v + step);
	                }
	              } while (v < axis.max && v != prev);
	              return ticks;
	            };
	            axis.tickFormatter = function (v, axis) {
	              var d = dateGenerator(v, axis.options);

	              // first check global format

	              if (opts.timeformat != null) {
	                return formatDate(d, opts.timeformat, opts.monthNames, opts.dayNames);
	              }

	              // possibly use quarters if quarters are mentioned in
	              // any of these places

	              var useQuarters = axis.options.tickSize && axis.options.tickSize[1] == "quarter" || axis.options.minTickSize && axis.options.minTickSize[1] == "quarter";
	              var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
	              var span = axis.max - axis.min;
	              var suffix = opts.twelveHourClock ? " %p" : "";
	              var hourCode = opts.twelveHourClock ? "%I" : "%H";
	              var fmt;
	              if (t < timeUnitSize.minute) {
	                fmt = hourCode + ":%M:%S" + suffix;
	              } else if (t < timeUnitSize.day) {
	                if (span < 2 * timeUnitSize.day) {
	                  fmt = hourCode + ":%M" + suffix;
	                } else {
	                  fmt = "%b %d " + hourCode + ":%M" + suffix;
	                }
	              } else if (t < timeUnitSize.month) {
	                fmt = "%b %d";
	              } else if (useQuarters && t < timeUnitSize.quarter || !useQuarters && t < timeUnitSize.year) {
	                if (span < timeUnitSize.year) {
	                  fmt = "%b";
	                } else {
	                  fmt = "%b %Y";
	                }
	              } else if (useQuarters && t < timeUnitSize.year) {
	                if (span < timeUnitSize.year) {
	                  fmt = "Q%q";
	                } else {
	                  fmt = "Q%q %Y";
	                }
	              } else {
	                fmt = "%Y";
	              }
	              var rt = formatDate(d, fmt, opts.monthNames, opts.dayNames);
	              return rt;
	            };
	          }
	        });
	      });
	    }
	    $.plot.plugins.push({
	      init: init,
	      options: options,
	      name: 'time',
	      version: '1.0'
	    });

	    // Time-axis support used to be in Flot core, which exposed the
	    // formatDate function on the plot object.  Various plugins depend
	    // on the function, so we need to re-expose it here.

	    $.plot.formatDate = formatDate;
	    $.plot.dateGenerator = dateGenerator;
	  })(jQuery);
	  return jquery_flot_time;
	}

	requireJquery_flot_time();

	var jquery_form_min = {exports: {}};

	/*!
	 * jQuery Form Plugin
	 * version: 4.3.0
	 * Requires jQuery v1.7.2 or later
	 * Project repository: https://github.com/jquery-form/form

	 * Copyright 2017 Kevin Morris
	 * Copyright 2006 M. Alsup

	 * Dual licensed under the LGPL-2.1+ or MIT licenses
	 * https://github.com/jquery-form/form#license

	 * This library is free software; you can redistribute it and/or
	 * modify it under the terms of the GNU Lesser General Public
	 * License as published by the Free Software Foundation; either
	 * version 2.1 of the License, or (at your option) any later version.
	 * This library is distributed in the hope that it will be useful,
	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
	 * Lesser General Public License for more details.
	 */
	var hasRequiredJquery_form_min;
	function requireJquery_form_min() {
	  if (hasRequiredJquery_form_min) return jquery_form_min.exports;
	  hasRequiredJquery_form_min = 1;
	  (function (module) {
	    !function (r) {
	      module.exports ? module.exports = function (e, t) {
	        return void 0 === t && (t = "undefined" != typeof window ? require$$0$1 : require$$0$1(e)), r(t), t;
	      } : r(jQuery);
	    }(function (q) {

	      var m = /\r?\n/g,
	        S = {};
	      S.fileapi = void 0 !== q('<input type="file">').get(0).files, S.formdata = void 0 !== window.FormData;
	      var _ = !!q.fn.prop;
	      function o(e) {
	        var t = e.data;
	        e.isDefaultPrevented() || (e.preventDefault(), q(e.target).closest("form").ajaxSubmit(t));
	      }
	      function i(e) {
	        var t = e.target,
	          r = q(t);
	        if (!r.is("[type=submit],[type=image]")) {
	          var a = r.closest("[type=submit]");
	          if (0 === a.length) return;
	          t = a[0];
	        }
	        var n,
	          o = t.form;
	        "image" === (o.clk = t).type && (void 0 !== e.offsetX ? (o.clk_x = e.offsetX, o.clk_y = e.offsetY) : "function" == typeof q.fn.offset ? (n = r.offset(), o.clk_x = e.pageX - n.left, o.clk_y = e.pageY - n.top) : (o.clk_x = e.pageX - t.offsetLeft, o.clk_y = e.pageY - t.offsetTop)), setTimeout(function () {
	          o.clk = o.clk_x = o.clk_y = null;
	        }, 100);
	      }
	      function N() {
	        var e;
	        q.fn.ajaxSubmit.debug && (e = "[jquery.form] " + Array.prototype.join.call(arguments, ""), window.console && window.console.log ? window.console.log(e) : window.opera && window.opera.postError && window.opera.postError(e));
	      }
	      q.fn.attr2 = function () {
	        if (!_) return this.attr.apply(this, arguments);
	        var e = this.prop.apply(this, arguments);
	        return e && e.jquery || "string" == typeof e ? e : this.attr.apply(this, arguments);
	      }, q.fn.ajaxSubmit = function (M, e, t, r) {
	        if (!this.length) return N("ajaxSubmit: skipping submit process - no element selected"), this;
	        var O,
	          a,
	          n,
	          o,
	          X = this;
	        "function" == typeof M ? M = {
	          success: M
	        } : "string" == typeof M || false === M && 0 < arguments.length ? (M = {
	          url: M,
	          data: e,
	          dataType: t
	        }, "function" == typeof r && (M.success = r)) : void 0 === M && (M = {}), O = M.method || M.type || this.attr2("method"), n = (n = (n = "string" == typeof (a = M.url || this.attr2("action")) ? q.trim(a) : "") || window.location.href || "") && (n.match(/^([^#]+)/) || [])[1], o = /(MSIE|Trident)/.test(navigator.userAgent || "") && /^https/i.test(window.location.href || "") ? "javascript:false" : "about:blank", M = q.extend(true, {
	          url: n,
	          success: q.ajaxSettings.success,
	          type: O || q.ajaxSettings.type,
	          iframeSrc: o
	        }, M);
	        var i = {};
	        if (this.trigger("form-pre-serialize", [this, M, i]), i.veto) return N("ajaxSubmit: submit vetoed via form-pre-serialize trigger"), this;
	        if (M.beforeSerialize && false === M.beforeSerialize(this, M)) return N("ajaxSubmit: submit aborted via beforeSerialize callback"), this;
	        var s = M.traditional;
	        void 0 === s && (s = q.ajaxSettings.traditional);
	        var u,
	          c,
	          C = [],
	          l = this.formToArray(M.semantic, C, M.filtering);
	        if (M.data && (c = q.isFunction(M.data) ? M.data(l) : M.data, M.extraData = c, u = q.param(c, s)), M.beforeSubmit && false === M.beforeSubmit(l, this, M)) return N("ajaxSubmit: submit aborted via beforeSubmit callback"), this;
	        if (this.trigger("form-submit-validate", [l, this, M, i]), i.veto) return N("ajaxSubmit: submit vetoed via form-submit-validate trigger"), this;
	        var f = q.param(l, s);
	        u && (f = f ? f + "&" + u : u), "GET" === M.type.toUpperCase() ? (M.url += (0 <= M.url.indexOf("?") ? "&" : "?") + f, M.data = null) : M.data = f;
	        var d,
	          m,
	          p,
	          h = [];
	        M.resetForm && h.push(function () {
	          X.resetForm();
	        }), M.clearForm && h.push(function () {
	          X.clearForm(M.includeHidden);
	        }), !M.dataType && M.target ? (d = M.success || function () {}, h.push(function (e, t, r) {
	          var a = arguments,
	            n = M.replaceTarget ? "replaceWith" : "html";
	          q(M.target)[n](e).each(function () {
	            d.apply(this, a);
	          });
	        })) : M.success && (q.isArray(M.success) ? q.merge(h, M.success) : h.push(M.success)), M.success = function (e, t, r) {
	          for (var a = M.context || this, n = 0, o = h.length; n < o; n++) h[n].apply(a, [e, t, r || X, X]);
	        }, M.error && (m = M.error, M.error = function (e, t, r) {
	          var a = M.context || this;
	          m.apply(a, [e, t, r, X]);
	        }), M.complete && (p = M.complete, M.complete = function (e, t) {
	          var r = M.context || this;
	          p.apply(r, [e, t, X]);
	        });
	        var v = 0 < q("input[type=file]:enabled", this).filter(function () {
	            return "" !== q(this).val();
	          }).length,
	          g = "multipart/form-data",
	          x = X.attr("enctype") === g || X.attr("encoding") === g,
	          y = S.fileapi && S.formdata;
	        N("fileAPI :" + y);
	        var b,
	          T = (v || x) && !y;
	        false !== M.iframe && (M.iframe || T) ? M.closeKeepAlive ? q.get(M.closeKeepAlive, function () {
	          b = w(l);
	        }) : b = w(l) : b = (v || x) && y ? function (e) {
	          for (var r = new FormData(), t = 0; t < e.length; t++) r.append(e[t].name, e[t].value);
	          if (M.extraData) {
	            var a = function (e) {
	              var t,
	                r,
	                a = q.param(e, M.traditional).split("&"),
	                n = a.length,
	                o = [];
	              for (t = 0; t < n; t++) a[t] = a[t].replace(/\+/g, " "), r = a[t].split("="), o.push([decodeURIComponent(r[0]), decodeURIComponent(r[1])]);
	              return o;
	            }(M.extraData);
	            for (t = 0; t < a.length; t++) a[t] && r.append(a[t][0], a[t][1]);
	          }
	          M.data = null;
	          var n = q.extend(true, {}, q.ajaxSettings, M, {
	            contentType: false,
	            processData: false,
	            cache: false,
	            type: O || "POST"
	          });
	          M.uploadProgress && (n.xhr = function () {
	            var e = q.ajaxSettings.xhr();
	            return e.upload && e.upload.addEventListener("progress", function (e) {
	              var t = 0,
	                r = e.loaded || e.position,
	                a = e.total;
	              e.lengthComputable && (t = Math.ceil(r / a * 100)), M.uploadProgress(e, r, a, t);
	            }, false), e;
	          });
	          n.data = null;
	          var o = n.beforeSend;
	          return n.beforeSend = function (e, t) {
	            M.formData ? t.data = M.formData : t.data = r, o && o.call(this, e, t);
	          }, q.ajax(n);
	        }(l) : q.ajax(M), X.removeData("jqxhr").data("jqxhr", b);
	        for (var j = 0; j < C.length; j++) C[j] = null;
	        return this.trigger("form-submit-notify", [this, M]), this;
	        function w(e) {
	          var t,
	            r,
	            l,
	            f,
	            o,
	            d,
	            m,
	            p,
	            a,
	            n,
	            h,
	            v,
	            i = X[0],
	            g = q.Deferred();
	          if (g.abort = function (e) {
	            p.abort(e);
	          }, e) for (r = 0; r < C.length; r++) t = q(C[r]), _ ? t.prop("disabled", false) : t.removeAttr("disabled");
	          (l = q.extend(true, {}, q.ajaxSettings, M)).context = l.context || l, o = "jqFormIO" + new Date().getTime();
	          var s = i.ownerDocument,
	            u = X.closest("body");
	          if (l.iframeTarget ? (n = (d = q(l.iframeTarget, s)).attr2("name")) ? o = n : d.attr2("name", o) : (d = q('<iframe name="' + o + '" src="' + l.iframeSrc + '" />', s)).css({
	            position: "absolute",
	            top: "-1000px",
	            left: "-1000px"
	          }), m = d[0], p = {
	            aborted: 0,
	            responseText: null,
	            responseXML: null,
	            status: 0,
	            statusText: "n/a",
	            getAllResponseHeaders: function () {},
	            getResponseHeader: function () {},
	            setRequestHeader: function () {},
	            abort: function (e) {
	              var t = "timeout" === e ? "timeout" : "aborted";
	              N("aborting upload... " + t), this.aborted = 1;
	              try {
	                m.contentWindow.document.execCommand && m.contentWindow.document.execCommand("Stop");
	              } catch (e) {}
	              d.attr("src", l.iframeSrc), p.error = t, l.error && l.error.call(l.context, p, t, e), f && q.event.trigger("ajaxError", [p, l, t]), l.complete && l.complete.call(l.context, p, t);
	            }
	          }, (f = l.global) && 0 == q.active++ && q.event.trigger("ajaxStart"), f && q.event.trigger("ajaxSend", [p, l]), l.beforeSend && false === l.beforeSend.call(l.context, p, l)) return l.global && q.active--, g.reject(), g;
	          if (p.aborted) return g.reject(), g;
	          (a = i.clk) && (n = a.name) && !a.disabled && (l.extraData = l.extraData || {}, l.extraData[n] = a.value, "image" === a.type && (l.extraData[n + ".x"] = i.clk_x, l.extraData[n + ".y"] = i.clk_y));
	          var x = 1,
	            y = 2;
	          function b(t) {
	            var r = null;
	            try {
	              t.contentWindow && (r = t.contentWindow.document);
	            } catch (e) {
	              N("cannot get iframe.contentWindow document: " + e);
	            }
	            if (r) return r;
	            try {
	              r = t.contentDocument ? t.contentDocument : t.document;
	            } catch (e) {
	              N("cannot get iframe.contentDocument: " + e), r = t.document;
	            }
	            return r;
	          }
	          var c = q("meta[name=csrf-token]").attr("content"),
	            T = q("meta[name=csrf-param]").attr("content");
	          function j() {
	            var e = X.attr2("target"),
	              t = X.attr2("action"),
	              r = X.attr("enctype") || X.attr("encoding") || "multipart/form-data";
	            i.setAttribute("target", o), O && !/post/i.test(O) || i.setAttribute("method", "POST"), t !== l.url && i.setAttribute("action", l.url), l.skipEncodingOverride || O && !/post/i.test(O) || X.attr({
	              encoding: "multipart/form-data",
	              enctype: "multipart/form-data"
	            }), l.timeout && (v = setTimeout(function () {
	              h = true, A(x);
	            }, l.timeout));
	            var a = [];
	            try {
	              if (l.extraData) for (var n in l.extraData) l.extraData.hasOwnProperty(n) && (q.isPlainObject(l.extraData[n]) && l.extraData[n].hasOwnProperty("name") && l.extraData[n].hasOwnProperty("value") ? a.push(q('<input type="hidden" name="' + l.extraData[n].name + '">', s).val(l.extraData[n].value).appendTo(i)[0]) : a.push(q('<input type="hidden" name="' + n + '">', s).val(l.extraData[n]).appendTo(i)[0]));
	              l.iframeTarget || d.appendTo(u), m.attachEvent ? m.attachEvent("onload", A) : m.addEventListener("load", A, !1), setTimeout(function e() {
	                try {
	                  var t = b(m).readyState;
	                  N("state = " + t), t && "uninitialized" === t.toLowerCase() && setTimeout(e, 50);
	                } catch (e) {
	                  N("Server abort: ", e, " (", e.name, ")"), A(y), v && clearTimeout(v), v = void 0;
	                }
	              }, 15);
	              try {
	                i.submit();
	              } catch (e) {
	                document.createElement("form").submit.apply(i);
	              }
	            } finally {
	              i.setAttribute("action", t), i.setAttribute("enctype", r), e ? i.setAttribute("target", e) : X.removeAttr("target"), q(a).remove();
	            }
	          }
	          T && c && (l.extraData = l.extraData || {}, l.extraData[T] = c), l.forceSync ? j() : setTimeout(j, 10);
	          var w,
	            S,
	            k,
	            D = 50;
	          function A(e) {
	            if (!p.aborted && !k) {
	              if ((S = b(m)) || (N("cannot access response document"), e = y), e === x && p) return p.abort("timeout"), void g.reject(p, "timeout");
	              if (e === y && p) return p.abort("server abort"), void g.reject(p, "error", "server abort");
	              if (S && S.location.href !== l.iframeSrc || h) {
	                m.detachEvent ? m.detachEvent("onload", A) : m.removeEventListener("load", A, false);
	                var t,
	                  r = "success";
	                try {
	                  if (h) throw "timeout";
	                  var a = "xml" === l.dataType || S.XMLDocument || q.isXMLDoc(S);
	                  if (N("isXml=" + a), !a && window.opera && (null === S.body || !S.body.innerHTML) && --D) return N("requeing onLoad callback, DOM not available"), void setTimeout(A, 250);
	                  var n = S.body ? S.body : S.documentElement;
	                  p.responseText = n ? n.innerHTML : null, p.responseXML = S.XMLDocument ? S.XMLDocument : S, a && (l.dataType = "xml"), p.getResponseHeader = function (e) {
	                    return {
	                      "content-type": l.dataType
	                    }[e.toLowerCase()];
	                  }, n && (p.status = Number(n.getAttribute("status")) || p.status, p.statusText = n.getAttribute("statusText") || p.statusText);
	                  var o,
	                    i,
	                    s,
	                    u = (l.dataType || "").toLowerCase(),
	                    c = /(json|script|text)/.test(u);
	                  c || l.textarea ? (o = S.getElementsByTagName("textarea")[0]) ? (p.responseText = o.value, p.status = Number(o.getAttribute("status")) || p.status, p.statusText = o.getAttribute("statusText") || p.statusText) : c && (i = S.getElementsByTagName("pre")[0], s = S.getElementsByTagName("body")[0], i ? p.responseText = i.textContent ? i.textContent : i.innerText : s && (p.responseText = s.textContent ? s.textContent : s.innerText)) : "xml" === u && !p.responseXML && p.responseText && (p.responseXML = F(p.responseText));
	                  try {
	                    w = E(p, u, l);
	                  } catch (e) {
	                    r = "parsererror", p.error = t = e || r;
	                  }
	                } catch (e) {
	                  N("error caught: ", e), r = "error", p.error = t = e || r;
	                }
	                p.aborted && (N("upload aborted"), r = null), p.status && (r = 200 <= p.status && p.status < 300 || 304 === p.status ? "success" : "error"), "success" === r ? (l.success && l.success.call(l.context, w, "success", p), g.resolve(p.responseText, "success", p), f && q.event.trigger("ajaxSuccess", [p, l])) : r && (void 0 === t && (t = p.statusText), l.error && l.error.call(l.context, p, r, t), g.reject(p, "error", t), f && q.event.trigger("ajaxError", [p, l, t])), f && q.event.trigger("ajaxComplete", [p, l]), f && ! --q.active && q.event.trigger("ajaxStop"), l.complete && l.complete.call(l.context, p, r), k = true, l.timeout && clearTimeout(v), setTimeout(function () {
	                  l.iframeTarget ? d.attr("src", l.iframeSrc) : d.remove(), p.responseXML = null;
	                }, 100);
	              }
	            }
	          }
	          var F = q.parseXML || function (e, t) {
	              return window.ActiveXObject ? ((t = new ActiveXObject("Microsoft.XMLDOM")).async = "false", t.loadXML(e)) : t = new DOMParser().parseFromString(e, "text/xml"), t && t.documentElement && "parsererror" !== t.documentElement.nodeName ? t : null;
	            },
	            L = q.parseJSON || function (e) {
	              return window.eval("(" + e + ")");
	            },
	            E = function (e, t, r) {
	              var a = e.getResponseHeader("content-type") || "",
	                n = ("xml" === t || !t) && 0 <= a.indexOf("xml"),
	                o = n ? e.responseXML : e.responseText;
	              return n && "parsererror" === o.documentElement.nodeName && q.error && q.error("parsererror"), r && r.dataFilter && (o = r.dataFilter(o, t)), "string" == typeof o && (("json" === t || !t) && 0 <= a.indexOf("json") ? o = L(o) : ("script" === t || !t) && 0 <= a.indexOf("javascript") && q.globalEval(o)), o;
	            };
	          return g;
	        }
	      }, q.fn.ajaxForm = function (e, t, r, a) {
	        if (("string" == typeof e || false === e && 0 < arguments.length) && (e = {
	          url: e,
	          data: t,
	          dataType: r
	        }, "function" == typeof a && (e.success = a)), (e = e || {}).delegation = e.delegation && q.isFunction(q.fn.on), e.delegation || 0 !== this.length) return e.delegation ? (q(document).off("submit.form-plugin", this.selector, o).off("click.form-plugin", this.selector, i).on("submit.form-plugin", this.selector, e, o).on("click.form-plugin", this.selector, e, i), this) : (e.beforeFormUnbind && e.beforeFormUnbind(this, e), this.ajaxFormUnbind().on("submit.form-plugin", e, o).on("click.form-plugin", e, i));
	        var n = {
	          s: this.selector,
	          c: this.context
	        };
	        return !q.isReady && n.s ? (N("DOM not ready, queuing ajaxForm"), q(function () {
	          q(n.s, n.c).ajaxForm(e);
	        })) : N("terminating; zero elements found by selector" + (q.isReady ? "" : " (DOM not ready)")), this;
	      }, q.fn.ajaxFormUnbind = function () {
	        return this.off("submit.form-plugin click.form-plugin");
	      }, q.fn.formToArray = function (e, t, r) {
	        var a = [];
	        if (0 === this.length) return a;
	        var n,
	          o,
	          i,
	          s,
	          u,
	          c,
	          l,
	          f,
	          d,
	          m,
	          p = this[0],
	          h = this.attr("id"),
	          v = (v = e || void 0 === p.elements ? p.getElementsByTagName("*") : p.elements) && q.makeArray(v);
	        if (h && (e || /(Edge|Trident)\//.test(navigator.userAgent)) && (n = q(':input[form="' + h + '"]').get()).length && (v = (v || []).concat(n)), !v || !v.length) return a;
	        for (q.isFunction(r) && (v = q.map(v, r)), o = 0, c = v.length; o < c; o++) if ((m = (u = v[o]).name) && !u.disabled) if (e && p.clk && "image" === u.type) p.clk === u && (a.push({
	          name: m,
	          value: q(u).val(),
	          type: u.type
	        }), a.push({
	          name: m + ".x",
	          value: p.clk_x
	        }, {
	          name: m + ".y",
	          value: p.clk_y
	        }));else if ((s = q.fieldValue(u, true)) && s.constructor === Array) for (t && t.push(u), i = 0, l = s.length; i < l; i++) a.push({
	          name: m,
	          value: s[i]
	        });else if (S.fileapi && "file" === u.type) {
	          t && t.push(u);
	          var g = u.files;
	          if (g.length) for (i = 0; i < g.length; i++) a.push({
	            name: m,
	            value: g[i],
	            type: u.type
	          });else a.push({
	            name: m,
	            value: "",
	            type: u.type
	          });
	        } else null != s && (t && t.push(u), a.push({
	          name: m,
	          value: s,
	          type: u.type,
	          required: u.required
	        }));
	        return e || !p.clk || (m = (d = (f = q(p.clk))[0]).name) && !d.disabled && "image" === d.type && (a.push({
	          name: m,
	          value: f.val()
	        }), a.push({
	          name: m + ".x",
	          value: p.clk_x
	        }, {
	          name: m + ".y",
	          value: p.clk_y
	        })), a;
	      }, q.fn.formSerialize = function (e) {
	        return q.param(this.formToArray(e));
	      }, q.fn.fieldSerialize = function (n) {
	        var o = [];
	        return this.each(function () {
	          var e = this.name;
	          if (e) {
	            var t = q.fieldValue(this, n);
	            if (t && t.constructor === Array) for (var r = 0, a = t.length; r < a; r++) o.push({
	              name: e,
	              value: t[r]
	            });else null != t && o.push({
	              name: this.name,
	              value: t
	            });
	          }
	        }), q.param(o);
	      }, q.fn.fieldValue = function (e) {
	        for (var t = [], r = 0, a = this.length; r < a; r++) {
	          var n = this[r],
	            o = q.fieldValue(n, e);
	          null == o || o.constructor === Array && !o.length || (o.constructor === Array ? q.merge(t, o) : t.push(o));
	        }
	        return t;
	      }, q.fieldValue = function (e, t) {
	        var r = e.name,
	          a = e.type,
	          n = e.tagName.toLowerCase();
	        if (void 0 === t && (t = true), t && (!r || e.disabled || "reset" === a || "button" === a || ("checkbox" === a || "radio" === a) && !e.checked || ("submit" === a || "image" === a) && e.form && e.form.clk !== e || "select" === n && -1 === e.selectedIndex)) return null;
	        if ("select" !== n) return q(e).val().replace(m, "\r\n");
	        var o = e.selectedIndex;
	        if (o < 0) return null;
	        for (var i = [], s = e.options, u = "select-one" === a, c = u ? o + 1 : s.length, l = u ? o : 0; l < c; l++) {
	          var f = s[l];
	          if (f.selected && !f.disabled) {
	            var d = (d = f.value) || (f.attributes && f.attributes.value && !f.attributes.value.specified ? f.text : f.value);
	            if (u) return d;
	            i.push(d);
	          }
	        }
	        return i;
	      }, q.fn.clearForm = function (e) {
	        return this.each(function () {
	          q("input,select,textarea", this).clearFields(e);
	        });
	      }, q.fn.clearFields = q.fn.clearInputs = function (r) {
	        var a = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i;
	        return this.each(function () {
	          var e = this.type,
	            t = this.tagName.toLowerCase();
	          a.test(e) || "textarea" === t ? this.value = "" : "checkbox" === e || "radio" === e ? this.checked = false : "select" === t ? this.selectedIndex = -1 : "file" === e ? /MSIE/.test(navigator.userAgent) ? q(this).replaceWith(q(this).clone(true)) : q(this).val("") : r && (true === r && /hidden/.test(e) || "string" == typeof r && q(this).is(r)) && (this.value = "");
	        });
	      }, q.fn.resetForm = function () {
	        return this.each(function () {
	          var t = q(this),
	            e = this.tagName.toLowerCase();
	          switch (e) {
	            case "input":
	              this.checked = this.defaultChecked;
	            case "textarea":
	              return this.value = this.defaultValue, true;
	            case "option":
	            case "optgroup":
	              var r = t.parents("select");
	              return r.length && r[0].multiple ? "option" === e ? this.selected = this.defaultSelected : t.find("option").resetForm() : r.resetForm(), true;
	            case "select":
	              return t.find("option").each(function (e) {
	                if (this.selected = this.defaultSelected, this.defaultSelected && !t[0].multiple) return t[0].selectedIndex = e, false;
	              }), true;
	            case "label":
	              var a = q(t.attr("for")),
	                n = t.find("input,select,textarea");
	              return a[0] && n.unshift(a[0]), n.resetForm(), true;
	            case "form":
	              return "function" != typeof this.reset && ("object" != typeof this.reset || this.reset.nodeType) || this.reset(), true;
	            default:
	              return t.find("form,input,label,select,textarea").resetForm(), true;
	          }
	        });
	      }, q.fn.enable = function (e) {
	        return void 0 === e && (e = true), this.each(function () {
	          this.disabled = !e;
	        });
	      }, q.fn.selected = function (r) {
	        return void 0 === r && (r = true), this.each(function () {
	          var e,
	            t = this.type;
	          "checkbox" === t || "radio" === t ? this.checked = r : "option" === this.tagName.toLowerCase() && (e = q(this).parent("select"), r && e[0] && "select-one" === e[0].type && e.find("option").selected(false), this.selected = r);
	        });
	      }, q.fn.ajaxSubmit.debug = false;
	    });
	  })(jquery_form_min);
	  return jquery_form_min.exports;
	}

	var jquery_form_minExports = requireJquery_form_min();
	const setupJQueryForm = /*@__PURE__*/getDefaultExportFromCjs(jquery_form_minExports);

	var jquery_cookie = {};

	/*!
	 * jQuery Cookie Plugin v1.4.1
	 * https://github.com/carhartl/jquery-cookie
	 *
	 * Copyright 2013 Klaus Hartl
	 * Released under the MIT license
	 */
	var hasRequiredJquery_cookie;
	function requireJquery_cookie() {
	  if (hasRequiredJquery_cookie) return jquery_cookie;
	  hasRequiredJquery_cookie = 1;
	  (function (exports) {
	    (function (factory) {
	      {
	        // CommonJS
	        factory(require$$0$1);
	      }
	    })(function ($) {
	      var pluses = /\+/g;
	      function encode(s) {
	        return config.raw ? s : encodeURIComponent(s);
	      }
	      function decode(s) {
	        return config.raw ? s : decodeURIComponent(s);
	      }
	      function stringifyCookieValue(value) {
	        return encode(config.json ? JSON.stringify(value) : String(value));
	      }
	      function parseCookieValue(s) {
	        if (s.indexOf('"') === 0) {
	          // This is a quoted cookie as according to RFC2068, unescape...
	          s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
	        }
	        try {
	          // Replace server-side written pluses with spaces.
	          // If we can't decode the cookie, ignore it, it's unusable.
	          // If we can't parse the cookie, ignore it, it's unusable.
	          s = decodeURIComponent(s.replace(pluses, ' '));
	          return config.json ? JSON.parse(s) : s;
	        } catch (e) {}
	      }
	      function read(s, converter) {
	        var value = config.raw ? s : parseCookieValue(s);
	        return $.isFunction(converter) ? converter(value) : value;
	      }
	      var config = $.cookie = function (key, value, options) {
	        // Write

	        if (value !== undefined && !$.isFunction(value)) {
	          options = $.extend({}, config.defaults, options);
	          if (typeof options.expires === 'number') {
	            var days = options.expires,
	              t = options.expires = new Date();
	            t.setTime(+t + days * 864e+5);
	          }
	          return document.cookie = [encode(key), '=', stringifyCookieValue(value), options.expires ? '; expires=' + options.expires.toUTCString() : '',
	          // use expires attribute, max-age is not supported by IE
	          options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : ''].join('');
	        }

	        // Read

	        var result = key ? undefined : {};

	        // To prevent the for loop in the first place assign an empty array
	        // in case there are no cookies at all. Also prevents odd result when
	        // calling $.cookie().
	        var cookies = document.cookie ? document.cookie.split('; ') : [];
	        for (var i = 0, l = cookies.length; i < l; i++) {
	          var parts = cookies[i].split('=');
	          var name = decode(parts.shift());
	          var cookie = parts.join('=');
	          if (key && key === name) {
	            // If second argument (value) is a function it's a converter...
	            result = read(cookie, value);
	            break;
	          }

	          // Prevent storing a cookie that we couldn't decode.
	          if (!key && (cookie = read(cookie)) !== undefined) {
	            result[name] = cookie;
	          }
	        }
	        return result;
	      };
	      config.defaults = {};
	      $.removeCookie = function (key, options) {
	        if ($.cookie(key) === undefined) {
	          return false;
	        }

	        // Must not alter options, thus extending a fresh object...
	        $.cookie(key, '', $.extend({}, options, {
	          expires: -1
	        }));
	        return !$.cookie(key);
	      };
	    });
	  })();
	  return jquery_cookie;
	}

	requireJquery_cookie();

	/**
	 * timesince is a live-updating implementation of Django's timesince filter
	 * in jQuery.
	 *
	 * This will automatically keep the timestamps updated as the page
	 * is opened, instead of showing the time as it was when the page was rendered.
	 * This is a better user experience, and also helps with caching (both
	 * browser and server-side).
	 *
	 * This is based both on Django's timesince filter
	 * (http://www.djangoproject.com/), and parts of Ryan McGeary's timeago
	 * jQuery plugin (http://timeago.yarp.com/).
	 *
	 * See https://github.com/chipx86/jquery-timesince for the latest.
	 *
	 * @name timesince
	 * @version 0.1
	 * @requires jQuery v1.2.3+
	 * @author Christian Hammond
	 * @license MIT License - http://www.opensource.org/licenses/mit-license.php
	 *
	 * Copyright (c) 2012, Christian Hammond (chipx86@chipx86.com)
	 */
	(function ($) {
	  $.timesince = function (timestamp) {
	    if (timestamp instanceof Date) {
	      return timeSince(timestamp);
	    } else if (typeof timestamp === 'string') {
	      return timeSince($.timesince.parse(timestamp));
	    } else if (typeof timestamp === 'number') {
	      return timeSince(new Date(timestamp));
	    } else {
	      // It's an element.
	      return timeSince($.timesince.datetime($(timestamp)));
	    }
	  };
	  $.extend($.timesince, {
	    options: {
	      refreshMs: 60 * 1000,
	      // 1 minute
	      strings: {
	        prefixAgo: null,
	        prefixFromNow: null,
	        suffixAgo: "ago",
	        suffixFromNow: "from now",
	        minute: "minute",
	        minutes: "minutes",
	        hour: "hour",
	        hours: "hours",
	        day: "day",
	        days: "days",
	        week: "week",
	        weeks: "weeks",
	        month: "month",
	        months: "months",
	        year: "year",
	        years: "years"
	      }
	    },
	    chunks: [[60 * 60 * 24 * 365, "year", "years"], [60 * 60 * 24 * 30, "month", "months"], [60 * 60 * 24 * 7, "week", "weeks"], [60 * 60 * 24, "day", "days"], [60 * 60, "hour", "hours"], [60, "minute", "minutes"]],
	    timeSince: function (deltaMs) {
	      var strings = this.options.strings,
	        seconds = Math.abs(deltaMs) / 1000,
	        prefix,
	        suffix,
	        i;
	      if (deltaMs < 0) {
	        prefix = strings.prefixFromNow;
	        suffix = strings.suffixFromNow;
	      } else {
	        prefix = strings.prefixAgo;
	        suffix = strings.suffixAgo;
	      }
	      prefix = prefix ? prefix + " " : "";
	      suffix = suffix ? " " + suffix : "";
	      if (seconds < 60) {
	        return prefix + "0 " + strings.minutes + suffix;
	      }
	      for (i = 0; i < this.chunks.length; i++) {
	        var chunk = this.chunks[i],
	          chunkSecs = chunk[0],
	          count = Math.floor(seconds / chunkSecs);
	        if (count != 0) {
	          var s = prefix + this.getChunkText(chunk, count);
	          if (i + 1 < this.chunks.length) {
	            // Get the second item.
	            var chunk2 = this.chunks[i + 1],
	              count2 = Math.floor((seconds - chunkSecs * count) / chunk2[0]);
	            if (count2 != 0) {
	              s += ", " + this.getChunkText(chunk2, count2);
	            }
	          }
	          return s + suffix;
	        }
	      }

	      // We shouldn't have reached here.
	      return '';
	    },
	    getChunkText: function (chunk, n) {
	      var type = n === 1 ? chunk[1] : chunk[2];
	      return n + " " + this.options.strings[type];
	    },
	    parse: function (iso8601) {
	      var s = $.trim(iso8601);
	      s = s.replace(/\.\d\d\d+/, ""); // remove milliseconds
	      s = s.replace(/-/, "/").replace(/-/, "/");
	      s = s.replace(/T/, " ").replace(/Z/, " UTC");
	      s = s.replace(/([\+\-]\d\d)\:?(\d\d)/, " $1$2"); // -04:00 -> -0400
	      return new Date(s);
	    },
	    datetime: function (el) {
	      var iso8601 = this.isTime(el) ? el.attr("datetime") : el.attr("title");
	      return this.parse(iso8601);
	    },
	    isTime: function (el) {
	      // jQuery's `is()` doesn't play well with HTML5 in IE
	      return el[0].tagName.toLowerCase() === "time";
	    }
	  });
	  $.fn.timesince = function (options) {
	    var self = this,
	      timerCnx,
	      refreshMs;
	    options = $.extend(options, $.timesince.options);
	    refreshMs = options.refreshMs;
	    if (refreshMs > 0) {
	      timerCnx = setInterval(function () {
	        self.each(function () {
	          refresh($(this), timerCnx);
	        });
	      }, refreshMs);
	    }
	    return this.each(function () {
	      var el = $(this),
	        text = $.trim(el.text());
	      el.data('timesince', {
	        datetime: $.timesince.datetime(el)
	      });
	      if (text.length > 0 && (!$.timesince.isTime(el) || !el.attr("title"))) {
	        el.attr("title", text);
	      }
	      refresh(el);
	    });
	  };
	  function refresh(el, timerCnx) {
	    var data = el.data('timesince');
	    if (data) {
	      el.text($.timesince.timeSince(new Date().getTime() - data.datetime.getTime()));
	    } else {
	      clearInterval(timerCnx);
	    }
	    return el;
	  }

	  // IE6 doesn't understand the <time> tag, so create it.
	  document.createElement("time");
	})(jQuery);

	/*
	 * jQuery UI Autocomplete @VERSION
	 *
	 * Copyright (c) 2007, 2008 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer
	 * Dual licensed under the MIT (MIT-LICENSE.txt)
	 * and GPL (GPL-LICENSE.txt) licenses.
	 * 
	 * http://docs.jquery.com/UI/Autocomplete
	 *
	 * Depends:
	 *    ui.core.js
	 */
	(function ($) {
	  $.widget("ui.rbautocomplete", {
	    options: {
	      inputClass: "ui-autocomplete-input",
	      resultsClass: "ui-autocomplete-results",
	      loadingClass: "ui-autocomplete-loading",
	      resultsParentEl: document.body,
	      minChars: 1,
	      ajaxDelay: 400,
	      localDelay: 10,
	      matchCase: false,
	      matchSubset: true,
	      matchContains: false,
	      cacheLength: 10,
	      scrollMax: 150,
	      noScrollMax: 10,
	      mustMatch: false,
	      extraParams: {},
	      selectFirst: true,
	      formatItem: function (row) {
	        return row[0];
	      },
	      formatMatch: null,
	      autoFill: false,
	      width: 0,
	      multiple: false,
	      multipleSeparator: ", ",
	      highlight: function (value, term) {
	        return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
	      },
	      scroll: true,
	      clickToURL: false,
	      enterToURL: false,
	      scrollHeight: 180
	    },
	    _init: function () {
	      $.extend(this.options, {
	        delay: this.options.delay != undefined ? this.options.delay : this.options.url ? this.options.ajaxDelay : this.options.localDelay,
	        max: this.options.max != undefined ? this.options.max : this.options.scroll ? this.options.scrollMax : this.options.noScrollMax,
	        highlight: this.options.highlight || function (value) {
	          return value;
	        },
	        // if highlight is set to false, replace it with a do-nothing function
	        formatMatch: this.options.formatMatch || this.options.formatItem // if the formatMatch option is not specified, then use formatItem for backwards compatibility
	      });
	      var input = this.element[0],
	        options = this.options,
	        // Create $ object for input element
	        $input = $(input).attr("autocomplete", "off").addClass(options.inputClass),
	        KEY = $.ui.keyCode,
	        previousValue = "",
	        cache = $.ui.rbautocomplete.cache(options),
	        hasFocus = 0,
	        config = {
	          mouseDownOnSelect: false
	        },
	        timeout,
	        lastKeyPressCode,
	        select = $.ui.rbautocomplete.select(options, input, selectCurrent, config);
	      if (options.result) {
	        $input.bind('result.rbautocomplete', options.result);
	      }
	      $input.bind('keydown.rbautocomplete', function (event) {
	        // track last key pressed
	        lastKeyPressCode = event.keyCode;
	        switch (event.keyCode) {
	          case KEY.UP:
	            event.preventDefault();
	            if (select.visible()) {
	              select.prev();
	            } else {
	              onChange(0, true);
	            }
	            break;
	          case KEY.DOWN:
	            event.preventDefault();
	            if (select.visible()) {
	              select.next();
	            } else {
	              onChange(0, true);
	            }
	            break;
	          case KEY.PAGE_UP:
	            event.preventDefault();
	            if (select.visible()) {
	              select.pageUp();
	            } else {
	              onChange(0, true);
	            }
	            break;
	          case KEY.PAGE_DOWN:
	            event.preventDefault();
	            if (select.visible()) {
	              select.pageDown();
	            } else {
	              onChange(0, true);
	            }
	            break;

	          // matches also semicolon
	          case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
	          case KEY.TAB:
	          case KEY.ENTER:
	            if (options.enterToURL && select.current()) {
	              select.current().click();
	            }
	            if (selectCurrent()) {
	              // stop default to prevent a form submit, Opera needs special handling
	              event.preventDefault();
	              return false;
	            }
	            break;
	          case KEY.ESCAPE:
	            select.hide();
	            break;
	          default:
	            clearTimeout(timeout);
	            timeout = setTimeout(onChange, options.delay);
	            break;
	        }
	      }).focus(function () {
	        // track whether the field has focus, we shouldn't process any
	        // results if the field no longer has focus
	        hasFocus++;
	      }).blur(function () {
	        hasFocus = 0;
	        if (!config.mouseDownOnSelect) {
	          hideResults();
	        }
	      }).click(function () {
	        // show select when clicking in a focused field
	        if (hasFocus++ > 1 && !select.visible()) {
	          onChange(0, true);
	        }
	      }).bind("search", function () {
	        // TODO why not just specifying both arguments?
	        var fn = arguments.length > 1 ? arguments[1] : null;
	        function findValueCallback(q, data) {
	          var result;
	          if (data && data.length) {
	            for (var i = 0; i < data.length; i++) {
	              if (data[i].result.toLowerCase() == q.toLowerCase()) {
	                result = data[i];
	                break;
	              }
	            }
	          }
	          if (typeof fn == "function") fn(result);else $input.trigger("result", result && [result.data, result.value]);
	        }
	        $.each(trimWords($input.val()), function (i, value) {
	          request(value, findValueCallback, findValueCallback);
	        });
	      }).bind("flushCache", function () {
	        cache.flush();
	      }).bind("setOptions", function () {
	        $.extend(options, arguments[1]);
	        // if we've updated the data, repopulate
	        if ("data" in arguments[1]) cache.populate();
	      }).bind("unautocomplete", function () {
	        select.unbind();
	        $input.unbind();
	        $(input.form).unbind(".rbautocomplete");
	      });

	      // Private methods
	      function selectCurrent() {
	        var selected = select.selected();
	        if (!selected || !matchCurrent(selected)) return false;
	        var v = selected.result;
	        previousValue = v;
	        if (options.multiple) {
	          var words = trimWords($input.val());
	          if (words.length > 1) {
	            v = words.slice(0, words.length - 1).join(options.multipleSeparator) + options.multipleSeparator + v;
	          }
	          v += options.multipleSeparator;
	        }
	        $input.val(v);
	        hideResultsNow();
	        $input.trigger("result", [selected.data, selected.value]);
	        return true;
	      }

	      // Check if the current user input matches the currently selected item.
	      function matchCurrent(selected) {
	        var toMatch = [selected.result];
	        if (selected.data.display_name) toMatch.push(selected.data.display_name);else if (selected.data.fullname) toMatch = toMatch.concat([selected.data.first_name, selected.data.last_name]);
	        var currentValue = lastWord($input.val());
	        var matched = false;
	        for (let i = 0; i < toMatch.length && !matched; i++) {
	          var match = toMatch[i];
	          if (!options.matchCase) {
	            match = match.toLowerCase();
	            currentValue = currentValue.toLowerCase();
	          }
	          if (options.matchContains) matched = match.indexOf(currentValue) >= 0;else
	            // check if prefix
	            matched = match.indexOf(currentValue) === 0;
	        }
	        return matched;
	      }
	      function onChange(crap, skipPrevCheck) {
	        var currentValue = $input.val();
	        if (!skipPrevCheck && currentValue == previousValue) return;
	        previousValue = currentValue;
	        currentValue = lastWord(currentValue);
	        if (currentValue.length >= options.minChars) {
	          $input.addClass(options.loadingClass);
	          if (!options.matchCase) currentValue = currentValue.toLowerCase();
	          request(currentValue, receiveData, hideResultsNow);
	        } else {
	          stopLoading();
	          select.hide();
	        }
	      }
	      function trimWords(value) {
	        if (!value) {
	          return [""];
	        }
	        if (!options.multiple) {
	          return [value];
	        }
	        var words = value.split(options.multipleSeparator);
	        var result = [];
	        $.each(words, function (i, value) {
	          result[i] = $.trim(value);
	        });
	        return result;
	      }
	      function lastWord(value) {
	        var words = trimWords(value);
	        return words[words.length - 1];
	      }

	      // fills in the input box w/the first match (assumed to be the best match)
	      // q: the term entered
	      // sValue: the first matching result
	      function autoFill(q, sValue) {
	        // autofill in the complete box w/the first match as long as the user hasn't entered in more data
	        // if the last user key pressed was backspace, don't autofill
	        if (options.autoFill && lastWord($input.val()).toLowerCase() == q.toLowerCase() && lastKeyPressCode != $.ui.keyCode.BACKSPACE) {
	          // fill in the value (keep the case the user has typed)
	          $input.val($input.val() + sValue.substring(lastWord(previousValue).length));
	          // select the portion of the value not typed by the user (so the next character will erase)
	          $.ui.rbautocomplete.selection(input, previousValue.length, previousValue.length + sValue.length);
	        }
	      }
	      function hideResults() {
	        clearTimeout(timeout);
	        timeout = setTimeout(hideResultsNow, 200);
	      }
	      function hideResultsNow() {
	        var wasVisible = select.visible();
	        select.hide();
	        clearTimeout(timeout);
	        stopLoading();
	        if (options.mustMatch) {
	          // call search and run callback
	          $input.rbautocomplete("search", function (result) {
	            // if no value found, clear the input box
	            if (!result) {
	              if (options.multiple) {
	                var words = trimWords($input.val()).slice(0, -1);
	                $input.val(words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : ""));
	              } else $input.val("");
	            }
	          });
	        }
	        if (wasVisible)
	          // position cursor at end of input field
	          $.ui.rbautocomplete.selection(input, input.value.length, input.value.length);
	      }
	      function receiveData(q, data) {
	        if (data && data.length && hasFocus) {
	          stopLoading();
	          select.display(data, q);
	          autoFill(q, data[0].value);
	          select.show();
	        } else {
	          hideResultsNow();
	        }
	      }
	      function request(term, success, failure) {
	        if (!options.matchCase) term = term.toLowerCase();
	        var data = cache.load(term);
	        // recieve the cached data
	        if (data && data.length) {
	          success(term, data);
	          // if an AJAX url has been supplied, try loading the data now
	        } else if (typeof options.url == "string" && options.url.length > 0) {
	          var extraParams = {
	            timestamp: +new Date()
	          };
	          $.each(options.extraParams, function (key, param) {
	            extraParams[key] = typeof param == "function" ? param(term) : param;
	          });
	          $.ajax({
	            // try to leverage ajaxQueue plugin to abort previous requests
	            mode: "abort",
	            // limit abortion to this input
	            port: "autocomplete" + input.name,
	            dataType: options.dataType,
	            url: options.url,
	            data: $.extend({
	              q: lastWord(term),
	              limit: options.max
	            }, extraParams),
	            success: function (data) {
	              var parsed = options.parse && options.parse(data) || parse(data);
	              cache.add(term, parsed);
	              success(term, parsed);
	            },
	            error: function (xhr, textStatus, errorThrown) {
	              if (options.error) {
	                options.error(xhr, textStatus, errorThrown);
	              }
	            }
	          });
	        } else if (options.source && typeof options.source == 'function') {
	          var resultData = options.source(term);
	          var parsed = options.parse ? options.parse(resultData) : resultData;
	          cache.add(term, parsed);
	          success(term, parsed);
	        } else {
	          // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
	          select.emptyList();
	          failure(term);
	        }
	      }
	      function parse(data) {
	        var parsed = [];
	        var rows = data.split("\n");
	        for (var i = 0; i < rows.length; i++) {
	          var row = $.trim(rows[i]);
	          if (row) {
	            row = row.split("|");
	            parsed[parsed.length] = {
	              data: row,
	              value: row[0],
	              result: options.formatResult && options.formatResult(row, row[0]) || row[0]
	            };
	          }
	        }
	        return parsed;
	      }
	      function stopLoading() {
	        $input.removeClass(options.loadingClass);
	      }
	    },
	    _propagate: function (n, event) {
	      $.ui.plugin.call(this, n, [event, this.ui()]);
	      return this.element.triggerHandler(n == 'autocomplete' ? n : 'autocomplete' + n, [event, this.ui()], this.options[n]);
	    },
	    // Public methods
	    ui: function (event) {
	      return {
	        options: this.options,
	        element: this.element
	      };
	    },
	    result: function (handler) {
	      return this.element.bind("result", handler);
	    },
	    search: function (handler) {
	      return this.element.trigger("search", [handler]);
	    },
	    flushCache: function () {
	      return this.element.trigger("flushCache");
	    },
	    setData: function (key, value) {
	      return this.element.trigger("setOptions", [{
	        key: value
	      }]);
	    },
	    destroy: function () {
	      this.element.removeAttr('disabled').removeClass('ui-autocomplete-input');
	      return this.element.trigger("unautocomplete");
	    },
	    enable: function () {
	      this.element.removeAttr('disabled').removeClass('ui-autocomplete-disabled');
	      this.disabled = false;
	    },
	    disable: function () {
	      this.element.attr('disabled', true).addClass('ui-autocomplete-disabled');
	      this.disabled = true;
	    }
	  });
	  $.ui.rbautocomplete.cache = function (options) {
	    var data = {};
	    var length = 0;
	    function matchSubset(s, sub) {
	      if (!options.matchCase) s = s.toLowerCase();
	      var i = s.indexOf(sub);
	      if (i == -1) return false;
	      return i == 0 || options.matchContains;
	    }
	    function add(q, value) {
	      if (length > options.cacheLength) {
	        flush();
	      }
	      if (!data[q]) {
	        length++;
	      }
	      data[q] = value;
	    }
	    function populate() {
	      if (!options.data) return false;
	      // track the matches
	      var stMatchSets = {},
	        nullData = 0;

	      // no url was specified, we need to adjust the cache length to make sure it fits the local data store
	      if (!options.url) options.cacheLength = 1;

	      // track all options for minChars = 0
	      stMatchSets[""] = [];

	      // loop through the array and create a lookup structure
	      for (var i = 0, ol = options.data.length; i < ol; i++) {
	        var rawValue = options.data[i];
	        // if rawValue is a string, make an array otherwise just reference the array
	        rawValue = typeof rawValue == "string" ? [rawValue] : rawValue;
	        var value = options.formatMatch(rawValue, i + 1, options.data.length);
	        if (value === false) continue;
	        var firstChar = value.charAt(0).toLowerCase();
	        // if no lookup array for this character exists, look it up now
	        if (!stMatchSets[firstChar]) stMatchSets[firstChar] = [];

	        // if the match is a string
	        var row = {
	          value: value,
	          data: rawValue,
	          result: options.formatResult && options.formatResult(rawValue) || value
	        };

	        // push the current match into the set list
	        stMatchSets[firstChar].push(row);

	        // keep track of minChars zero items
	        if (nullData++ < options.max) {
	          stMatchSets[""].push(row);
	        }
	      }

	      // add the data items to the cache
	      $.each(stMatchSets, function (i, value) {
	        // increase the cache size
	        options.cacheLength++;
	        // add to the cache
	        add(i, value);
	      });
	    }

	    // populate any existing data
	    setTimeout(populate, 25);
	    function flush() {
	      data = {};
	      length = 0;
	    }
	    return {
	      flush: flush,
	      add: add,
	      populate: populate,
	      load: function (q) {
	        if (!options.cacheLength || !length) return null;
	        /* 
	         * if dealing w/local data and matchContains than we must make sure
	         * to loop through all the data collections looking for matches
	         */
	        if (!options.url && options.matchContains) {
	          // track all matches
	          var csub = [];
	          // loop through all the data grids for matches
	          for (var k in data) {
	            // don't search through the stMatchSets[""] (minChars: 0) cache
	            // this prevents duplicates
	            if (k.length > 0) {
	              var c = data[k];
	              $.each(c, function (i, x) {
	                // if we've got a match, add it to the array
	                if (matchSubset(x.value, q)) {
	                  csub.push(x);
	                }
	              });
	            }
	          }
	          return csub;
	        } else
	          // if the exact item exists, use it
	          if (data[q]) {
	            return data[q];
	          } else if (options.matchSubset) {
	            for (var i = q.length - 1; i >= options.minChars; i--) {
	              var c = data[q.substr(0, i)];
	              if (c) {
	                var csub = [];
	                $.each(c, function (i, x) {
	                  if (matchSubset(x.value, q)) {
	                    csub[csub.length] = x;
	                  }
	                });
	                return csub;
	              }
	            }
	          }
	        return null;
	      }
	    };
	  };
	  $.ui.rbautocomplete.select = function (options, input, select, config) {
	    var CLASSES = {
	      ACTIVE: "ui-autocomplete-over"
	    };
	    var listItems,
	      active = -1,
	      data,
	      term = "",
	      needsInit = true,
	      element,
	      list;

	    // Create results
	    function init() {
	      if (!needsInit) return;
	      element = $("<div/>").hide().addClass(options.resultsClass).css("position", "absolute").appendTo(options.resultsParentEl);
	      list = $("<ul/>").appendTo(element).mouseover(function (event) {
	        if (target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
	          active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
	          $(target(event)).addClass(CLASSES.ACTIVE);
	        }
	      }).click(function (event) {
	        $(target(event)).addClass(CLASSES.ACTIVE);
	        select();
	        // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
	        input.focus();
	        return false;
	      }).mousedown(function () {
	        config.mouseDownOnSelect = true;
	      }).mouseup(function () {
	        config.mouseDownOnSelect = false;
	      });
	      if (options.width > 0) element.css("width", options.width);
	      needsInit = false;
	    }
	    function target(event) {
	      var element = event.target;
	      while (element && element.tagName != "LI") element = element.parentNode;
	      // more fun with IE, sometimes event.target is empty, just ignore it then
	      if (!element) return [];
	      return element;
	    }
	    function moveSelect(step) {
	      listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
	      movePosition(step);
	      var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
	      if (options.scroll) {
	        var offset = 0;
	        listItems.slice(0, active).each(function () {
	          offset += this.offsetHeight;
	        });
	        if (offset + activeItem[0].offsetHeight - list.scrollTop() > list[0].clientHeight) {
	          list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
	        } else if (offset < list.scrollTop()) {
	          list.scrollTop(offset);
	        }
	      }
	    }
	    function movePosition(step) {
	      active += step;
	      if (active < 0) {
	        active = listItems.size() - 1;
	      } else if (active >= listItems.size()) {
	        active = 0;
	      }
	    }
	    function limitNumberOfItems(available) {
	      return options.max && options.max < available ? options.max : available;
	    }
	    function makeItem(data) {
	      if (options.clickToURL === false) {
	        return $("<li/>");
	      } else {
	        // For Quick Search
	        return $("<li/>").click(function () {
	          window.open(data["url"]);
	        });
	      }
	    }
	    function fillList() {
	      if (options.cmp !== undefined) {
	        data.sort(function (a, b) {
	          return options.cmp(term, a, b);
	        });
	      }
	      list.empty();
	      var max = limitNumberOfItems(data.length);
	      for (var i = 0; i < max; i++) {
	        if (!data[i]) continue;
	        var formatted = options.formatItem(data[i].data, i + 1, max, data[i].value, term);
	        if (formatted === false) continue;
	        var li = makeItem(data[i].data).html(options.highlight(formatted, term)).addClass(i % 2 == 0 ? "ui-autocomplete-even" : "ui-autocomplete-odd").appendTo(list)[0];
	        $.data(li, "ui-autocomplete-data", data[i]);
	      }
	      listItems = list.find("li");
	      if (options.selectFirst) {
	        listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
	        active = 0;
	      }
	      // apply bgiframe if available
	      if ($.fn.bgiframe) list.bgiframe();
	    }
	    return {
	      display: function (d, q) {
	        init();
	        data = d;
	        term = q;
	        fillList();
	      },
	      next: function () {
	        moveSelect(1);
	      },
	      prev: function () {
	        moveSelect(-1);
	      },
	      pageUp: function () {
	        if (active != 0 && active - 8 < 0) {
	          moveSelect(-active);
	        } else {
	          moveSelect(-8);
	        }
	      },
	      pageDown: function () {
	        if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
	          moveSelect(listItems.size() - 1 - active);
	        } else {
	          moveSelect(8);
	        }
	      },
	      hide: function () {
	        element && element.hide();
	        listItems && listItems.removeClass(CLASSES.ACTIVE);
	        active = -1;
	        $(input).triggerHandler("autocompletehide", [{}, {
	          options: options
	        }], options["hide"]);
	      },
	      visible: function () {
	        return element && element.is(":visible");
	      },
	      current: function () {
	        return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
	      },
	      show: function () {
	        var $input = $(input),
	          $window = $(window),
	          $document = $(document),
	          offset = $input.offset(),
	          inputWidth = input.offsetWidth,
	          inputHeight = input.offsetHeight,
	          windowRight,
	          windowBottom,
	          width,
	          height;
	        if (options.scroll) {
	          list.scrollTop(0);
	          list.css({
	            maxHeight: options.scrollHeight,
	            overflow: 'auto'
	          });
	        }
	        $(input).triggerHandler("autocompleteshow", [{}, {
	          options: options
	        }], options["show"]);
	        width = typeof options.width === "string" || options.width > 0 ? options.width : inputWidth;
	        height = element.outerHeight(true);
	        windowBottom = $window.height() + $document.scrollTop();
	        windowRight = $window.width() + $document.scrollLeft();
	        element.css({
	          width: width,
	          top: offset.top + inputHeight + height > windowBottom ? offset.top - height : offset.top + inputHeight,
	          left: offset.left + width > windowRight ? offset.left + inputWidth - width : offset.left
	        }).show();
	      },
	      selected: function () {
	        var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
	        return selected && selected.length && $.data(selected[0], "ui-autocomplete-data");
	      },
	      emptyList: function () {
	        list && list.empty();
	      },
	      unbind: function () {
	        element && element.remove();
	      }
	    };
	  };
	  $.ui.rbautocomplete.selection = function (field, start, end) {
	    if (field.createTextRange) {
	      var selRange = field.createTextRange();
	      selRange.collapse(true);
	      selRange.moveStart("character", start);
	      selRange.moveEnd("character", end);
	      selRange.select();
	    } else if (field.setSelectionRange) {
	      field.setSelectionRange(start, end);
	    } else {
	      if (field.selectionStart) {
	        field.selectionStart = start;
	        field.selectionEnd = end;
	      }
	    }
	    field.focus();
	  };
	})(jQuery);

	function commonjsRequire(path) {
		throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
	}

	var moment$2 = {exports: {}};

	var moment$1 = moment$2.exports;
	var hasRequiredMoment;
	function requireMoment() {
	  if (hasRequiredMoment) return moment$2.exports;
	  hasRequiredMoment = 1;
	  (function (module, exports) {
	    (function (global, factory) {
	      module.exports = factory() ;
	    })(moment$1, function () {

	      var hookCallback;
	      function hooks() {
	        return hookCallback.apply(null, arguments);
	      }

	      // This is done to register the method called with moment()
	      // without creating circular dependencies.
	      function setHookCallback(callback) {
	        hookCallback = callback;
	      }
	      function isArray(input) {
	        return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
	      }
	      function isObject(input) {
	        // IE8 will treat undefined and null as object if it wasn't for
	        // input != null
	        return input != null && Object.prototype.toString.call(input) === '[object Object]';
	      }
	      function hasOwnProp(a, b) {
	        return Object.prototype.hasOwnProperty.call(a, b);
	      }
	      function isObjectEmpty(obj) {
	        if (Object.getOwnPropertyNames) {
	          return Object.getOwnPropertyNames(obj).length === 0;
	        } else {
	          var k;
	          for (k in obj) {
	            if (hasOwnProp(obj, k)) {
	              return false;
	            }
	          }
	          return true;
	        }
	      }
	      function isUndefined(input) {
	        return input === void 0;
	      }
	      function isNumber(input) {
	        return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
	      }
	      function isDate(input) {
	        return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
	      }
	      function map(arr, fn) {
	        var res = [],
	          i,
	          arrLen = arr.length;
	        for (i = 0; i < arrLen; ++i) {
	          res.push(fn(arr[i], i));
	        }
	        return res;
	      }
	      function extend(a, b) {
	        for (var i in b) {
	          if (hasOwnProp(b, i)) {
	            a[i] = b[i];
	          }
	        }
	        if (hasOwnProp(b, 'toString')) {
	          a.toString = b.toString;
	        }
	        if (hasOwnProp(b, 'valueOf')) {
	          a.valueOf = b.valueOf;
	        }
	        return a;
	      }
	      function createUTC(input, format, locale, strict) {
	        return createLocalOrUTC(input, format, locale, strict, true).utc();
	      }
	      function defaultParsingFlags() {
	        // We need to deep clone this object.
	        return {
	          empty: false,
	          unusedTokens: [],
	          unusedInput: [],
	          overflow: -2,
	          charsLeftOver: 0,
	          nullInput: false,
	          invalidEra: null,
	          invalidMonth: null,
	          invalidFormat: false,
	          userInvalidated: false,
	          iso: false,
	          parsedDateParts: [],
	          era: null,
	          meridiem: null,
	          rfc2822: false,
	          weekdayMismatch: false
	        };
	      }
	      function getParsingFlags(m) {
	        if (m._pf == null) {
	          m._pf = defaultParsingFlags();
	        }
	        return m._pf;
	      }
	      var some;
	      if (Array.prototype.some) {
	        some = Array.prototype.some;
	      } else {
	        some = function (fun) {
	          var t = Object(this),
	            len = t.length >>> 0,
	            i;
	          for (i = 0; i < len; i++) {
	            if (i in t && fun.call(this, t[i], i, t)) {
	              return true;
	            }
	          }
	          return false;
	        };
	      }
	      function isValid(m) {
	        var flags = null,
	          parsedParts = false,
	          isNowValid = m._d && !isNaN(m._d.getTime());
	        if (isNowValid) {
	          flags = getParsingFlags(m);
	          parsedParts = some.call(flags.parsedDateParts, function (i) {
	            return i != null;
	          });
	          isNowValid = flags.overflow < 0 && !flags.empty && !flags.invalidEra && !flags.invalidMonth && !flags.invalidWeekday && !flags.weekdayMismatch && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || flags.meridiem && parsedParts);
	          if (m._strict) {
	            isNowValid = isNowValid && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0 && flags.bigHour === undefined;
	          }
	        }
	        if (Object.isFrozen == null || !Object.isFrozen(m)) {
	          m._isValid = isNowValid;
	        } else {
	          return isNowValid;
	        }
	        return m._isValid;
	      }
	      function createInvalid(flags) {
	        var m = createUTC(NaN);
	        if (flags != null) {
	          extend(getParsingFlags(m), flags);
	        } else {
	          getParsingFlags(m).userInvalidated = true;
	        }
	        return m;
	      }

	      // Plugins that add properties should also add the key here (null value),
	      // so we can properly clone ourselves.
	      var momentProperties = hooks.momentProperties = [],
	        updateInProgress = false;
	      function copyConfig(to, from) {
	        var i,
	          prop,
	          val,
	          momentPropertiesLen = momentProperties.length;
	        if (!isUndefined(from._isAMomentObject)) {
	          to._isAMomentObject = from._isAMomentObject;
	        }
	        if (!isUndefined(from._i)) {
	          to._i = from._i;
	        }
	        if (!isUndefined(from._f)) {
	          to._f = from._f;
	        }
	        if (!isUndefined(from._l)) {
	          to._l = from._l;
	        }
	        if (!isUndefined(from._strict)) {
	          to._strict = from._strict;
	        }
	        if (!isUndefined(from._tzm)) {
	          to._tzm = from._tzm;
	        }
	        if (!isUndefined(from._isUTC)) {
	          to._isUTC = from._isUTC;
	        }
	        if (!isUndefined(from._offset)) {
	          to._offset = from._offset;
	        }
	        if (!isUndefined(from._pf)) {
	          to._pf = getParsingFlags(from);
	        }
	        if (!isUndefined(from._locale)) {
	          to._locale = from._locale;
	        }
	        if (momentPropertiesLen > 0) {
	          for (i = 0; i < momentPropertiesLen; i++) {
	            prop = momentProperties[i];
	            val = from[prop];
	            if (!isUndefined(val)) {
	              to[prop] = val;
	            }
	          }
	        }
	        return to;
	      }

	      // Moment prototype object
	      function Moment(config) {
	        copyConfig(this, config);
	        this._d = new Date(config._d != null ? config._d.getTime() : NaN);
	        if (!this.isValid()) {
	          this._d = new Date(NaN);
	        }
	        // Prevent infinite loop in case updateOffset creates new moment
	        // objects.
	        if (updateInProgress === false) {
	          updateInProgress = true;
	          hooks.updateOffset(this);
	          updateInProgress = false;
	        }
	      }
	      function isMoment(obj) {
	        return obj instanceof Moment || obj != null && obj._isAMomentObject != null;
	      }
	      function warn(msg) {
	        if (hooks.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) {
	          console.warn('Deprecation warning: ' + msg);
	        }
	      }
	      function deprecate(msg, fn) {
	        var firstTime = true;
	        return extend(function () {
	          if (hooks.deprecationHandler != null) {
	            hooks.deprecationHandler(null, msg);
	          }
	          if (firstTime) {
	            var args = [],
	              arg,
	              i,
	              key,
	              argLen = arguments.length;
	            for (i = 0; i < argLen; i++) {
	              arg = '';
	              if (typeof arguments[i] === 'object') {
	                arg += '\n[' + i + '] ';
	                for (key in arguments[0]) {
	                  if (hasOwnProp(arguments[0], key)) {
	                    arg += key + ': ' + arguments[0][key] + ', ';
	                  }
	                }
	                arg = arg.slice(0, -2); // Remove trailing comma and space
	              } else {
	                arg = arguments[i];
	              }
	              args.push(arg);
	            }
	            warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + new Error().stack);
	            firstTime = false;
	          }
	          return fn.apply(this, arguments);
	        }, fn);
	      }
	      var deprecations = {};
	      function deprecateSimple(name, msg) {
	        if (hooks.deprecationHandler != null) {
	          hooks.deprecationHandler(name, msg);
	        }
	        if (!deprecations[name]) {
	          warn(msg);
	          deprecations[name] = true;
	        }
	      }
	      hooks.suppressDeprecationWarnings = false;
	      hooks.deprecationHandler = null;
	      function isFunction(input) {
	        return typeof Function !== 'undefined' && input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
	      }
	      function set(config) {
	        var prop, i;
	        for (i in config) {
	          if (hasOwnProp(config, i)) {
	            prop = config[i];
	            if (isFunction(prop)) {
	              this[i] = prop;
	            } else {
	              this['_' + i] = prop;
	            }
	          }
	        }
	        this._config = config;
	        // Lenient ordinal parsing accepts just a number in addition to
	        // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
	        // TODO: Remove "ordinalParse" fallback in next major release.
	        this._dayOfMonthOrdinalParseLenient = new RegExp((this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + '|' + /\d{1,2}/.source);
	      }
	      function mergeConfigs(parentConfig, childConfig) {
	        var res = extend({}, parentConfig),
	          prop;
	        for (prop in childConfig) {
	          if (hasOwnProp(childConfig, prop)) {
	            if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
	              res[prop] = {};
	              extend(res[prop], parentConfig[prop]);
	              extend(res[prop], childConfig[prop]);
	            } else if (childConfig[prop] != null) {
	              res[prop] = childConfig[prop];
	            } else {
	              delete res[prop];
	            }
	          }
	        }
	        for (prop in parentConfig) {
	          if (hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject(parentConfig[prop])) {
	            // make sure changes to properties don't modify parent config
	            res[prop] = extend({}, res[prop]);
	          }
	        }
	        return res;
	      }
	      function Locale(config) {
	        if (config != null) {
	          this.set(config);
	        }
	      }
	      var keys;
	      if (Object.keys) {
	        keys = Object.keys;
	      } else {
	        keys = function (obj) {
	          var i,
	            res = [];
	          for (i in obj) {
	            if (hasOwnProp(obj, i)) {
	              res.push(i);
	            }
	          }
	          return res;
	        };
	      }
	      var defaultCalendar = {
	        sameDay: '[Today at] LT',
	        nextDay: '[Tomorrow at] LT',
	        nextWeek: 'dddd [at] LT',
	        lastDay: '[Yesterday at] LT',
	        lastWeek: '[Last] dddd [at] LT',
	        sameElse: 'L'
	      };
	      function calendar(key, mom, now) {
	        var output = this._calendar[key] || this._calendar['sameElse'];
	        return isFunction(output) ? output.call(mom, now) : output;
	      }
	      function zeroFill(number, targetLength, forceSign) {
	        var absNumber = '' + Math.abs(number),
	          zerosToFill = targetLength - absNumber.length,
	          sign = number >= 0;
	        return (sign ? forceSign ? '+' : '' : '-') + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
	      }
	      var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,
	        localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,
	        formatFunctions = {},
	        formatTokenFunctions = {};

	      // token:    'M'
	      // padded:   ['MM', 2]
	      // ordinal:  'Mo'
	      // callback: function () { this.month() + 1 }
	      function addFormatToken(token, padded, ordinal, callback) {
	        var func = callback;
	        if (typeof callback === 'string') {
	          func = function () {
	            return this[callback]();
	          };
	        }
	        if (token) {
	          formatTokenFunctions[token] = func;
	        }
	        if (padded) {
	          formatTokenFunctions[padded[0]] = function () {
	            return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
	          };
	        }
	        if (ordinal) {
	          formatTokenFunctions[ordinal] = function () {
	            return this.localeData().ordinal(func.apply(this, arguments), token);
	          };
	        }
	      }
	      function removeFormattingTokens(input) {
	        if (input.match(/\[[\s\S]/)) {
	          return input.replace(/^\[|\]$/g, '');
	        }
	        return input.replace(/\\/g, '');
	      }
	      function makeFormatFunction(format) {
	        var array = format.match(formattingTokens),
	          i,
	          length;
	        for (i = 0, length = array.length; i < length; i++) {
	          if (formatTokenFunctions[array[i]]) {
	            array[i] = formatTokenFunctions[array[i]];
	          } else {
	            array[i] = removeFormattingTokens(array[i]);
	          }
	        }
	        return function (mom) {
	          var output = '',
	            i;
	          for (i = 0; i < length; i++) {
	            output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
	          }
	          return output;
	        };
	      }

	      // format date using native date object
	      function formatMoment(m, format) {
	        if (!m.isValid()) {
	          return m.localeData().invalidDate();
	        }
	        format = expandFormat(format, m.localeData());
	        formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
	        return formatFunctions[format](m);
	      }
	      function expandFormat(format, locale) {
	        var i = 5;
	        function replaceLongDateFormatTokens(input) {
	          return locale.longDateFormat(input) || input;
	        }
	        localFormattingTokens.lastIndex = 0;
	        while (i >= 0 && localFormattingTokens.test(format)) {
	          format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
	          localFormattingTokens.lastIndex = 0;
	          i -= 1;
	        }
	        return format;
	      }
	      var defaultLongDateFormat = {
	        LTS: 'h:mm:ss A',
	        LT: 'h:mm A',
	        L: 'MM/DD/YYYY',
	        LL: 'MMMM D, YYYY',
	        LLL: 'MMMM D, YYYY h:mm A',
	        LLLL: 'dddd, MMMM D, YYYY h:mm A'
	      };
	      function longDateFormat(key) {
	        var format = this._longDateFormat[key],
	          formatUpper = this._longDateFormat[key.toUpperCase()];
	        if (format || !formatUpper) {
	          return format;
	        }
	        this._longDateFormat[key] = formatUpper.match(formattingTokens).map(function (tok) {
	          if (tok === 'MMMM' || tok === 'MM' || tok === 'DD' || tok === 'dddd') {
	            return tok.slice(1);
	          }
	          return tok;
	        }).join('');
	        return this._longDateFormat[key];
	      }
	      var defaultInvalidDate = 'Invalid date';
	      function invalidDate() {
	        return this._invalidDate;
	      }
	      var defaultOrdinal = '%d',
	        defaultDayOfMonthOrdinalParse = /\d{1,2}/;
	      function ordinal(number) {
	        return this._ordinal.replace('%d', number);
	      }
	      var defaultRelativeTime = {
	        future: 'in %s',
	        past: '%s ago',
	        s: 'a few seconds',
	        ss: '%d seconds',
	        m: 'a minute',
	        mm: '%d minutes',
	        h: 'an hour',
	        hh: '%d hours',
	        d: 'a day',
	        dd: '%d days',
	        w: 'a week',
	        ww: '%d weeks',
	        M: 'a month',
	        MM: '%d months',
	        y: 'a year',
	        yy: '%d years'
	      };
	      function relativeTime(number, withoutSuffix, string, isFuture) {
	        var output = this._relativeTime[string];
	        return isFunction(output) ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number);
	      }
	      function pastFuture(diff, output) {
	        var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
	        return isFunction(format) ? format(output) : format.replace(/%s/i, output);
	      }
	      var aliases = {
	        D: 'date',
	        dates: 'date',
	        date: 'date',
	        d: 'day',
	        days: 'day',
	        day: 'day',
	        e: 'weekday',
	        weekdays: 'weekday',
	        weekday: 'weekday',
	        E: 'isoWeekday',
	        isoweekdays: 'isoWeekday',
	        isoweekday: 'isoWeekday',
	        DDD: 'dayOfYear',
	        dayofyears: 'dayOfYear',
	        dayofyear: 'dayOfYear',
	        h: 'hour',
	        hours: 'hour',
	        hour: 'hour',
	        ms: 'millisecond',
	        milliseconds: 'millisecond',
	        millisecond: 'millisecond',
	        m: 'minute',
	        minutes: 'minute',
	        minute: 'minute',
	        M: 'month',
	        months: 'month',
	        month: 'month',
	        Q: 'quarter',
	        quarters: 'quarter',
	        quarter: 'quarter',
	        s: 'second',
	        seconds: 'second',
	        second: 'second',
	        gg: 'weekYear',
	        weekyears: 'weekYear',
	        weekyear: 'weekYear',
	        GG: 'isoWeekYear',
	        isoweekyears: 'isoWeekYear',
	        isoweekyear: 'isoWeekYear',
	        w: 'week',
	        weeks: 'week',
	        week: 'week',
	        W: 'isoWeek',
	        isoweeks: 'isoWeek',
	        isoweek: 'isoWeek',
	        y: 'year',
	        years: 'year',
	        year: 'year'
	      };
	      function normalizeUnits(units) {
	        return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
	      }
	      function normalizeObjectUnits(inputObject) {
	        var normalizedInput = {},
	          normalizedProp,
	          prop;
	        for (prop in inputObject) {
	          if (hasOwnProp(inputObject, prop)) {
	            normalizedProp = normalizeUnits(prop);
	            if (normalizedProp) {
	              normalizedInput[normalizedProp] = inputObject[prop];
	            }
	          }
	        }
	        return normalizedInput;
	      }
	      var priorities = {
	        date: 9,
	        day: 11,
	        weekday: 11,
	        isoWeekday: 11,
	        dayOfYear: 4,
	        hour: 13,
	        millisecond: 16,
	        minute: 14,
	        month: 8,
	        quarter: 7,
	        second: 15,
	        weekYear: 1,
	        isoWeekYear: 1,
	        week: 5,
	        isoWeek: 5,
	        year: 1
	      };
	      function getPrioritizedUnits(unitsObj) {
	        var units = [],
	          u;
	        for (u in unitsObj) {
	          if (hasOwnProp(unitsObj, u)) {
	            units.push({
	              unit: u,
	              priority: priorities[u]
	            });
	          }
	        }
	        units.sort(function (a, b) {
	          return a.priority - b.priority;
	        });
	        return units;
	      }
	      var match1 = /\d/,
	        //       0 - 9
	        match2 = /\d\d/,
	        //      00 - 99
	        match3 = /\d{3}/,
	        //     000 - 999
	        match4 = /\d{4}/,
	        //    0000 - 9999
	        match6 = /[+-]?\d{6}/,
	        // -999999 - 999999
	        match1to2 = /\d\d?/,
	        //       0 - 99
	        match3to4 = /\d\d\d\d?/,
	        //     999 - 9999
	        match5to6 = /\d\d\d\d\d\d?/,
	        //   99999 - 999999
	        match1to3 = /\d{1,3}/,
	        //       0 - 999
	        match1to4 = /\d{1,4}/,
	        //       0 - 9999
	        match1to6 = /[+-]?\d{1,6}/,
	        // -999999 - 999999
	        matchUnsigned = /\d+/,
	        //       0 - inf
	        matchSigned = /[+-]?\d+/,
	        //    -inf - inf
	        matchOffset = /Z|[+-]\d\d:?\d\d/gi,
	        // +00:00 -00:00 +0000 -0000 or Z
	        matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi,
	        // +00 -00 +00:00 -00:00 +0000 -0000 or Z
	        matchTimestamp = /[+-]?\d+(\.\d{1,3})?/,
	        // 123456789 123456789.123
	        // any word (or two) characters or numbers including two/three word month in arabic.
	        // includes scottish gaelic two word and hyphenated months
	        matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,
	        match1to2NoLeadingZero = /^[1-9]\d?/,
	        //         1-99
	        match1to2HasZero = /^([1-9]\d|\d)/,
	        //           0-99
	        regexes;
	      regexes = {};
	      function addRegexToken(token, regex, strictRegex) {
	        regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
	          return isStrict && strictRegex ? strictRegex : regex;
	        };
	      }
	      function getParseRegexForToken(token, config) {
	        if (!hasOwnProp(regexes, token)) {
	          return new RegExp(unescapeFormat(token));
	        }
	        return regexes[token](config._strict, config._locale);
	      }

	      // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
	      function unescapeFormat(s) {
	        return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
	          return p1 || p2 || p3 || p4;
	        }));
	      }
	      function regexEscape(s) {
	        return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
	      }
	      function absFloor(number) {
	        if (number < 0) {
	          // -0 -> 0
	          return Math.ceil(number) || 0;
	        } else {
	          return Math.floor(number);
	        }
	      }
	      function toInt(argumentForCoercion) {
	        var coercedNumber = +argumentForCoercion,
	          value = 0;
	        if (coercedNumber !== 0 && isFinite(coercedNumber)) {
	          value = absFloor(coercedNumber);
	        }
	        return value;
	      }
	      var tokens = {};
	      function addParseToken(token, callback) {
	        var i,
	          func = callback,
	          tokenLen;
	        if (typeof token === 'string') {
	          token = [token];
	        }
	        if (isNumber(callback)) {
	          func = function (input, array) {
	            array[callback] = toInt(input);
	          };
	        }
	        tokenLen = token.length;
	        for (i = 0; i < tokenLen; i++) {
	          tokens[token[i]] = func;
	        }
	      }
	      function addWeekParseToken(token, callback) {
	        addParseToken(token, function (input, array, config, token) {
	          config._w = config._w || {};
	          callback(input, config._w, config, token);
	        });
	      }
	      function addTimeToArrayFromToken(token, input, config) {
	        if (input != null && hasOwnProp(tokens, token)) {
	          tokens[token](input, config._a, config, token);
	        }
	      }
	      function isLeapYear(year) {
	        return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
	      }
	      var YEAR = 0,
	        MONTH = 1,
	        DATE = 2,
	        HOUR = 3,
	        MINUTE = 4,
	        SECOND = 5,
	        MILLISECOND = 6,
	        WEEK = 7,
	        WEEKDAY = 8;

	      // FORMATTING

	      addFormatToken('Y', 0, 0, function () {
	        var y = this.year();
	        return y <= 9999 ? zeroFill(y, 4) : '+' + y;
	      });
	      addFormatToken(0, ['YY', 2], 0, function () {
	        return this.year() % 100;
	      });
	      addFormatToken(0, ['YYYY', 4], 0, 'year');
	      addFormatToken(0, ['YYYYY', 5], 0, 'year');
	      addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');

	      // PARSING

	      addRegexToken('Y', matchSigned);
	      addRegexToken('YY', match1to2, match2);
	      addRegexToken('YYYY', match1to4, match4);
	      addRegexToken('YYYYY', match1to6, match6);
	      addRegexToken('YYYYYY', match1to6, match6);
	      addParseToken(['YYYYY', 'YYYYYY'], YEAR);
	      addParseToken('YYYY', function (input, array) {
	        array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
	      });
	      addParseToken('YY', function (input, array) {
	        array[YEAR] = hooks.parseTwoDigitYear(input);
	      });
	      addParseToken('Y', function (input, array) {
	        array[YEAR] = parseInt(input, 10);
	      });

	      // HELPERS

	      function daysInYear(year) {
	        return isLeapYear(year) ? 366 : 365;
	      }

	      // HOOKS

	      hooks.parseTwoDigitYear = function (input) {
	        return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
	      };

	      // MOMENTS

	      var getSetYear = makeGetSet('FullYear', true);
	      function getIsLeapYear() {
	        return isLeapYear(this.year());
	      }
	      function makeGetSet(unit, keepTime) {
	        return function (value) {
	          if (value != null) {
	            set$1(this, unit, value);
	            hooks.updateOffset(this, keepTime);
	            return this;
	          } else {
	            return get(this, unit);
	          }
	        };
	      }
	      function get(mom, unit) {
	        if (!mom.isValid()) {
	          return NaN;
	        }
	        var d = mom._d,
	          isUTC = mom._isUTC;
	        switch (unit) {
	          case 'Milliseconds':
	            return isUTC ? d.getUTCMilliseconds() : d.getMilliseconds();
	          case 'Seconds':
	            return isUTC ? d.getUTCSeconds() : d.getSeconds();
	          case 'Minutes':
	            return isUTC ? d.getUTCMinutes() : d.getMinutes();
	          case 'Hours':
	            return isUTC ? d.getUTCHours() : d.getHours();
	          case 'Date':
	            return isUTC ? d.getUTCDate() : d.getDate();
	          case 'Day':
	            return isUTC ? d.getUTCDay() : d.getDay();
	          case 'Month':
	            return isUTC ? d.getUTCMonth() : d.getMonth();
	          case 'FullYear':
	            return isUTC ? d.getUTCFullYear() : d.getFullYear();
	          default:
	            return NaN;
	          // Just in case
	        }
	      }
	      function set$1(mom, unit, value) {
	        var d, isUTC, year, month, date;
	        if (!mom.isValid() || isNaN(value)) {
	          return;
	        }
	        d = mom._d;
	        isUTC = mom._isUTC;
	        switch (unit) {
	          case 'Milliseconds':
	            return void (isUTC ? d.setUTCMilliseconds(value) : d.setMilliseconds(value));
	          case 'Seconds':
	            return void (isUTC ? d.setUTCSeconds(value) : d.setSeconds(value));
	          case 'Minutes':
	            return void (isUTC ? d.setUTCMinutes(value) : d.setMinutes(value));
	          case 'Hours':
	            return void (isUTC ? d.setUTCHours(value) : d.setHours(value));
	          case 'Date':
	            return void (isUTC ? d.setUTCDate(value) : d.setDate(value));
	          // case 'Day': // Not real
	          //    return void (isUTC ? d.setUTCDay(value) : d.setDay(value));
	          // case 'Month': // Not used because we need to pass two variables
	          //     return void (isUTC ? d.setUTCMonth(value) : d.setMonth(value));
	          case 'FullYear':
	            break;
	          // See below ...
	          default:
	            return;
	          // Just in case
	        }
	        year = value;
	        month = mom.month();
	        date = mom.date();
	        date = date === 29 && month === 1 && !isLeapYear(year) ? 28 : date;
	        void (isUTC ? d.setUTCFullYear(year, month, date) : d.setFullYear(year, month, date));
	      }

	      // MOMENTS

	      function stringGet(units) {
	        units = normalizeUnits(units);
	        if (isFunction(this[units])) {
	          return this[units]();
	        }
	        return this;
	      }
	      function stringSet(units, value) {
	        if (typeof units === 'object') {
	          units = normalizeObjectUnits(units);
	          var prioritized = getPrioritizedUnits(units),
	            i,
	            prioritizedLen = prioritized.length;
	          for (i = 0; i < prioritizedLen; i++) {
	            this[prioritized[i].unit](units[prioritized[i].unit]);
	          }
	        } else {
	          units = normalizeUnits(units);
	          if (isFunction(this[units])) {
	            return this[units](value);
	          }
	        }
	        return this;
	      }
	      function mod(n, x) {
	        return (n % x + x) % x;
	      }
	      var indexOf;
	      if (Array.prototype.indexOf) {
	        indexOf = Array.prototype.indexOf;
	      } else {
	        indexOf = function (o) {
	          // I know
	          var i;
	          for (i = 0; i < this.length; ++i) {
	            if (this[i] === o) {
	              return i;
	            }
	          }
	          return -1;
	        };
	      }
	      function daysInMonth(year, month) {
	        if (isNaN(year) || isNaN(month)) {
	          return NaN;
	        }
	        var modMonth = mod(month, 12);
	        year += (month - modMonth) / 12;
	        return modMonth === 1 ? isLeapYear(year) ? 29 : 28 : 31 - modMonth % 7 % 2;
	      }

	      // FORMATTING

	      addFormatToken('M', ['MM', 2], 'Mo', function () {
	        return this.month() + 1;
	      });
	      addFormatToken('MMM', 0, 0, function (format) {
	        return this.localeData().monthsShort(this, format);
	      });
	      addFormatToken('MMMM', 0, 0, function (format) {
	        return this.localeData().months(this, format);
	      });

	      // PARSING

	      addRegexToken('M', match1to2, match1to2NoLeadingZero);
	      addRegexToken('MM', match1to2, match2);
	      addRegexToken('MMM', function (isStrict, locale) {
	        return locale.monthsShortRegex(isStrict);
	      });
	      addRegexToken('MMMM', function (isStrict, locale) {
	        return locale.monthsRegex(isStrict);
	      });
	      addParseToken(['M', 'MM'], function (input, array) {
	        array[MONTH] = toInt(input) - 1;
	      });
	      addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
	        var month = config._locale.monthsParse(input, token, config._strict);
	        // if we didn't find a month name, mark the date as invalid.
	        if (month != null) {
	          array[MONTH] = month;
	        } else {
	          getParsingFlags(config).invalidMonth = input;
	        }
	      });

	      // LOCALES

	      var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
	        defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
	        MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,
	        defaultMonthsShortRegex = matchWord,
	        defaultMonthsRegex = matchWord;
	      function localeMonths(m, format) {
	        if (!m) {
	          return isArray(this._months) ? this._months : this._months['standalone'];
	        }
	        return isArray(this._months) ? this._months[m.month()] : this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
	      }
	      function localeMonthsShort(m, format) {
	        if (!m) {
	          return isArray(this._monthsShort) ? this._monthsShort : this._monthsShort['standalone'];
	        }
	        return isArray(this._monthsShort) ? this._monthsShort[m.month()] : this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
	      }
	      function handleStrictParse(monthName, format, strict) {
	        var i,
	          ii,
	          mom,
	          llc = monthName.toLocaleLowerCase();
	        if (!this._monthsParse) {
	          // this is not used
	          this._monthsParse = [];
	          this._longMonthsParse = [];
	          this._shortMonthsParse = [];
	          for (i = 0; i < 12; ++i) {
	            mom = createUTC([2000, i]);
	            this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
	            this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
	          }
	        }
	        if (strict) {
	          if (format === 'MMM') {
	            ii = indexOf.call(this._shortMonthsParse, llc);
	            return ii !== -1 ? ii : null;
	          } else {
	            ii = indexOf.call(this._longMonthsParse, llc);
	            return ii !== -1 ? ii : null;
	          }
	        } else {
	          if (format === 'MMM') {
	            ii = indexOf.call(this._shortMonthsParse, llc);
	            if (ii !== -1) {
	              return ii;
	            }
	            ii = indexOf.call(this._longMonthsParse, llc);
	            return ii !== -1 ? ii : null;
	          } else {
	            ii = indexOf.call(this._longMonthsParse, llc);
	            if (ii !== -1) {
	              return ii;
	            }
	            ii = indexOf.call(this._shortMonthsParse, llc);
	            return ii !== -1 ? ii : null;
	          }
	        }
	      }
	      function localeMonthsParse(monthName, format, strict) {
	        var i, mom, regex;
	        if (this._monthsParseExact) {
	          return handleStrictParse.call(this, monthName, format, strict);
	        }
	        if (!this._monthsParse) {
	          this._monthsParse = [];
	          this._longMonthsParse = [];
	          this._shortMonthsParse = [];
	        }

	        // TODO: add sorting
	        // Sorting makes sure if one month (or abbr) is a prefix of another
	        // see sorting in computeMonthsParse
	        for (i = 0; i < 12; i++) {
	          // make the regex if we don't have it already
	          mom = createUTC([2000, i]);
	          if (strict && !this._longMonthsParse[i]) {
	            this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
	            this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
	          }
	          if (!strict && !this._monthsParse[i]) {
	            regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
	            this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
	          }
	          // test the regex
	          if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
	            return i;
	          } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
	            return i;
	          } else if (!strict && this._monthsParse[i].test(monthName)) {
	            return i;
	          }
	        }
	      }

	      // MOMENTS

	      function setMonth(mom, value) {
	        if (!mom.isValid()) {
	          // No op
	          return mom;
	        }
	        if (typeof value === 'string') {
	          if (/^\d+$/.test(value)) {
	            value = toInt(value);
	          } else {
	            value = mom.localeData().monthsParse(value);
	            // TODO: Another silent failure?
	            if (!isNumber(value)) {
	              return mom;
	            }
	          }
	        }
	        var month = value,
	          date = mom.date();
	        date = date < 29 ? date : Math.min(date, daysInMonth(mom.year(), month));
	        void (mom._isUTC ? mom._d.setUTCMonth(month, date) : mom._d.setMonth(month, date));
	        return mom;
	      }
	      function getSetMonth(value) {
	        if (value != null) {
	          setMonth(this, value);
	          hooks.updateOffset(this, true);
	          return this;
	        } else {
	          return get(this, 'Month');
	        }
	      }
	      function getDaysInMonth() {
	        return daysInMonth(this.year(), this.month());
	      }
	      function monthsShortRegex(isStrict) {
	        if (this._monthsParseExact) {
	          if (!hasOwnProp(this, '_monthsRegex')) {
	            computeMonthsParse.call(this);
	          }
	          if (isStrict) {
	            return this._monthsShortStrictRegex;
	          } else {
	            return this._monthsShortRegex;
	          }
	        } else {
	          if (!hasOwnProp(this, '_monthsShortRegex')) {
	            this._monthsShortRegex = defaultMonthsShortRegex;
	          }
	          return this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex;
	        }
	      }
	      function monthsRegex(isStrict) {
	        if (this._monthsParseExact) {
	          if (!hasOwnProp(this, '_monthsRegex')) {
	            computeMonthsParse.call(this);
	          }
	          if (isStrict) {
	            return this._monthsStrictRegex;
	          } else {
	            return this._monthsRegex;
	          }
	        } else {
	          if (!hasOwnProp(this, '_monthsRegex')) {
	            this._monthsRegex = defaultMonthsRegex;
	          }
	          return this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex;
	        }
	      }
	      function computeMonthsParse() {
	        function cmpLenRev(a, b) {
	          return b.length - a.length;
	        }
	        var shortPieces = [],
	          longPieces = [],
	          mixedPieces = [],
	          i,
	          mom,
	          shortP,
	          longP;
	        for (i = 0; i < 12; i++) {
	          // make the regex if we don't have it already
	          mom = createUTC([2000, i]);
	          shortP = regexEscape(this.monthsShort(mom, ''));
	          longP = regexEscape(this.months(mom, ''));
	          shortPieces.push(shortP);
	          longPieces.push(longP);
	          mixedPieces.push(longP);
	          mixedPieces.push(shortP);
	        }
	        // Sorting makes sure if one month (or abbr) is a prefix of another it
	        // will match the longer piece.
	        shortPieces.sort(cmpLenRev);
	        longPieces.sort(cmpLenRev);
	        mixedPieces.sort(cmpLenRev);
	        this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
	        this._monthsShortRegex = this._monthsRegex;
	        this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
	        this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
	      }
	      function createDate(y, m, d, h, M, s, ms) {
	        // can't just apply() to create a date:
	        // https://stackoverflow.com/q/181348
	        var date;
	        // the date constructor remaps years 0-99 to 1900-1999
	        if (y < 100 && y >= 0) {
	          // preserve leap years using a full 400 year cycle, then reset
	          date = new Date(y + 400, m, d, h, M, s, ms);
	          if (isFinite(date.getFullYear())) {
	            date.setFullYear(y);
	          }
	        } else {
	          date = new Date(y, m, d, h, M, s, ms);
	        }
	        return date;
	      }
	      function createUTCDate(y) {
	        var date, args;
	        // the Date.UTC function remaps years 0-99 to 1900-1999
	        if (y < 100 && y >= 0) {
	          args = Array.prototype.slice.call(arguments);
	          // preserve leap years using a full 400 year cycle, then reset
	          args[0] = y + 400;
	          date = new Date(Date.UTC.apply(null, args));
	          if (isFinite(date.getUTCFullYear())) {
	            date.setUTCFullYear(y);
	          }
	        } else {
	          date = new Date(Date.UTC.apply(null, arguments));
	        }
	        return date;
	      }

	      // start-of-first-week - start-of-year
	      function firstWeekOffset(year, dow, doy) {
	        var
	          // first-week day -- which january is always in the first week (4 for iso, 1 for other)
	          fwd = 7 + dow - doy,
	          // first-week day local weekday -- which local weekday is fwd
	          fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
	        return -fwdlw + fwd - 1;
	      }

	      // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
	      function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
	        var localWeekday = (7 + weekday - dow) % 7,
	          weekOffset = firstWeekOffset(year, dow, doy),
	          dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
	          resYear,
	          resDayOfYear;
	        if (dayOfYear <= 0) {
	          resYear = year - 1;
	          resDayOfYear = daysInYear(resYear) + dayOfYear;
	        } else if (dayOfYear > daysInYear(year)) {
	          resYear = year + 1;
	          resDayOfYear = dayOfYear - daysInYear(year);
	        } else {
	          resYear = year;
	          resDayOfYear = dayOfYear;
	        }
	        return {
	          year: resYear,
	          dayOfYear: resDayOfYear
	        };
	      }
	      function weekOfYear(mom, dow, doy) {
	        var weekOffset = firstWeekOffset(mom.year(), dow, doy),
	          week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
	          resWeek,
	          resYear;
	        if (week < 1) {
	          resYear = mom.year() - 1;
	          resWeek = week + weeksInYear(resYear, dow, doy);
	        } else if (week > weeksInYear(mom.year(), dow, doy)) {
	          resWeek = week - weeksInYear(mom.year(), dow, doy);
	          resYear = mom.year() + 1;
	        } else {
	          resYear = mom.year();
	          resWeek = week;
	        }
	        return {
	          week: resWeek,
	          year: resYear
	        };
	      }
	      function weeksInYear(year, dow, doy) {
	        var weekOffset = firstWeekOffset(year, dow, doy),
	          weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
	        return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
	      }

	      // FORMATTING

	      addFormatToken('w', ['ww', 2], 'wo', 'week');
	      addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');

	      // PARSING

	      addRegexToken('w', match1to2, match1to2NoLeadingZero);
	      addRegexToken('ww', match1to2, match2);
	      addRegexToken('W', match1to2, match1to2NoLeadingZero);
	      addRegexToken('WW', match1to2, match2);
	      addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
	        week[token.substr(0, 1)] = toInt(input);
	      });

	      // HELPERS

	      // LOCALES

	      function localeWeek(mom) {
	        return weekOfYear(mom, this._week.dow, this._week.doy).week;
	      }
	      var defaultLocaleWeek = {
	        dow: 0,
	        // Sunday is the first day of the week.
	        doy: 6 // The week that contains Jan 6th is the first week of the year.
	      };
	      function localeFirstDayOfWeek() {
	        return this._week.dow;
	      }
	      function localeFirstDayOfYear() {
	        return this._week.doy;
	      }

	      // MOMENTS

	      function getSetWeek(input) {
	        var week = this.localeData().week(this);
	        return input == null ? week : this.add((input - week) * 7, 'd');
	      }
	      function getSetISOWeek(input) {
	        var week = weekOfYear(this, 1, 4).week;
	        return input == null ? week : this.add((input - week) * 7, 'd');
	      }

	      // FORMATTING

	      addFormatToken('d', 0, 'do', 'day');
	      addFormatToken('dd', 0, 0, function (format) {
	        return this.localeData().weekdaysMin(this, format);
	      });
	      addFormatToken('ddd', 0, 0, function (format) {
	        return this.localeData().weekdaysShort(this, format);
	      });
	      addFormatToken('dddd', 0, 0, function (format) {
	        return this.localeData().weekdays(this, format);
	      });
	      addFormatToken('e', 0, 0, 'weekday');
	      addFormatToken('E', 0, 0, 'isoWeekday');

	      // PARSING

	      addRegexToken('d', match1to2);
	      addRegexToken('e', match1to2);
	      addRegexToken('E', match1to2);
	      addRegexToken('dd', function (isStrict, locale) {
	        return locale.weekdaysMinRegex(isStrict);
	      });
	      addRegexToken('ddd', function (isStrict, locale) {
	        return locale.weekdaysShortRegex(isStrict);
	      });
	      addRegexToken('dddd', function (isStrict, locale) {
	        return locale.weekdaysRegex(isStrict);
	      });
	      addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
	        var weekday = config._locale.weekdaysParse(input, token, config._strict);
	        // if we didn't get a weekday name, mark the date as invalid
	        if (weekday != null) {
	          week.d = weekday;
	        } else {
	          getParsingFlags(config).invalidWeekday = input;
	        }
	      });
	      addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
	        week[token] = toInt(input);
	      });

	      // HELPERS

	      function parseWeekday(input, locale) {
	        if (typeof input !== 'string') {
	          return input;
	        }
	        if (!isNaN(input)) {
	          return parseInt(input, 10);
	        }
	        input = locale.weekdaysParse(input);
	        if (typeof input === 'number') {
	          return input;
	        }
	        return null;
	      }
	      function parseIsoWeekday(input, locale) {
	        if (typeof input === 'string') {
	          return locale.weekdaysParse(input) % 7 || 7;
	        }
	        return isNaN(input) ? null : input;
	      }

	      // LOCALES
	      function shiftWeekdays(ws, n) {
	        return ws.slice(n, 7).concat(ws.slice(0, n));
	      }
	      var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
	        defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
	        defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
	        defaultWeekdaysRegex = matchWord,
	        defaultWeekdaysShortRegex = matchWord,
	        defaultWeekdaysMinRegex = matchWord;
	      function localeWeekdays(m, format) {
	        var weekdays = isArray(this._weekdays) ? this._weekdays : this._weekdays[m && m !== true && this._weekdays.isFormat.test(format) ? 'format' : 'standalone'];
	        return m === true ? shiftWeekdays(weekdays, this._week.dow) : m ? weekdays[m.day()] : weekdays;
	      }
	      function localeWeekdaysShort(m) {
	        return m === true ? shiftWeekdays(this._weekdaysShort, this._week.dow) : m ? this._weekdaysShort[m.day()] : this._weekdaysShort;
	      }
	      function localeWeekdaysMin(m) {
	        return m === true ? shiftWeekdays(this._weekdaysMin, this._week.dow) : m ? this._weekdaysMin[m.day()] : this._weekdaysMin;
	      }
	      function handleStrictParse$1(weekdayName, format, strict) {
	        var i,
	          ii,
	          mom,
	          llc = weekdayName.toLocaleLowerCase();
	        if (!this._weekdaysParse) {
	          this._weekdaysParse = [];
	          this._shortWeekdaysParse = [];
	          this._minWeekdaysParse = [];
	          for (i = 0; i < 7; ++i) {
	            mom = createUTC([2000, 1]).day(i);
	            this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
	            this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
	            this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
	          }
	        }
	        if (strict) {
	          if (format === 'dddd') {
	            ii = indexOf.call(this._weekdaysParse, llc);
	            return ii !== -1 ? ii : null;
	          } else if (format === 'ddd') {
	            ii = indexOf.call(this._shortWeekdaysParse, llc);
	            return ii !== -1 ? ii : null;
	          } else {
	            ii = indexOf.call(this._minWeekdaysParse, llc);
	            return ii !== -1 ? ii : null;
	          }
	        } else {
	          if (format === 'dddd') {
	            ii = indexOf.call(this._weekdaysParse, llc);
	            if (ii !== -1) {
	              return ii;
	            }
	            ii = indexOf.call(this._shortWeekdaysParse, llc);
	            if (ii !== -1) {
	              return ii;
	            }
	            ii = indexOf.call(this._minWeekdaysParse, llc);
	            return ii !== -1 ? ii : null;
	          } else if (format === 'ddd') {
	            ii = indexOf.call(this._shortWeekdaysParse, llc);
	            if (ii !== -1) {
	              return ii;
	            }
	            ii = indexOf.call(this._weekdaysParse, llc);
	            if (ii !== -1) {
	              return ii;
	            }
	            ii = indexOf.call(this._minWeekdaysParse, llc);
	            return ii !== -1 ? ii : null;
	          } else {
	            ii = indexOf.call(this._minWeekdaysParse, llc);
	            if (ii !== -1) {
	              return ii;
	            }
	            ii = indexOf.call(this._weekdaysParse, llc);
	            if (ii !== -1) {
	              return ii;
	            }
	            ii = indexOf.call(this._shortWeekdaysParse, llc);
	            return ii !== -1 ? ii : null;
	          }
	        }
	      }
	      function localeWeekdaysParse(weekdayName, format, strict) {
	        var i, mom, regex;
	        if (this._weekdaysParseExact) {
	          return handleStrictParse$1.call(this, weekdayName, format, strict);
	        }
	        if (!this._weekdaysParse) {
	          this._weekdaysParse = [];
	          this._minWeekdaysParse = [];
	          this._shortWeekdaysParse = [];
	          this._fullWeekdaysParse = [];
	        }
	        for (i = 0; i < 7; i++) {
	          // make the regex if we don't have it already

	          mom = createUTC([2000, 1]).day(i);
	          if (strict && !this._fullWeekdaysParse[i]) {
	            this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i');
	            this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i');
	            this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i');
	          }
	          if (!this._weekdaysParse[i]) {
	            regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
	            this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
	          }
	          // test the regex
	          if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
	            return i;
	          } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
	            return i;
	          } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
	            return i;
	          } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
	            return i;
	          }
	        }
	      }

	      // MOMENTS

	      function getSetDayOfWeek(input) {
	        if (!this.isValid()) {
	          return input != null ? this : NaN;
	        }
	        var day = get(this, 'Day');
	        if (input != null) {
	          input = parseWeekday(input, this.localeData());
	          return this.add(input - day, 'd');
	        } else {
	          return day;
	        }
	      }
	      function getSetLocaleDayOfWeek(input) {
	        if (!this.isValid()) {
	          return input != null ? this : NaN;
	        }
	        var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
	        return input == null ? weekday : this.add(input - weekday, 'd');
	      }
	      function getSetISODayOfWeek(input) {
	        if (!this.isValid()) {
	          return input != null ? this : NaN;
	        }

	        // behaves the same as moment#day except
	        // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
	        // as a setter, sunday should belong to the previous week.

	        if (input != null) {
	          var weekday = parseIsoWeekday(input, this.localeData());
	          return this.day(this.day() % 7 ? weekday : weekday - 7);
	        } else {
	          return this.day() || 7;
	        }
	      }
	      function weekdaysRegex(isStrict) {
	        if (this._weekdaysParseExact) {
	          if (!hasOwnProp(this, '_weekdaysRegex')) {
	            computeWeekdaysParse.call(this);
	          }
	          if (isStrict) {
	            return this._weekdaysStrictRegex;
	          } else {
	            return this._weekdaysRegex;
	          }
	        } else {
	          if (!hasOwnProp(this, '_weekdaysRegex')) {
	            this._weekdaysRegex = defaultWeekdaysRegex;
	          }
	          return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex;
	        }
	      }
	      function weekdaysShortRegex(isStrict) {
	        if (this._weekdaysParseExact) {
	          if (!hasOwnProp(this, '_weekdaysRegex')) {
	            computeWeekdaysParse.call(this);
	          }
	          if (isStrict) {
	            return this._weekdaysShortStrictRegex;
	          } else {
	            return this._weekdaysShortRegex;
	          }
	        } else {
	          if (!hasOwnProp(this, '_weekdaysShortRegex')) {
	            this._weekdaysShortRegex = defaultWeekdaysShortRegex;
	          }
	          return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
	        }
	      }
	      function weekdaysMinRegex(isStrict) {
	        if (this._weekdaysParseExact) {
	          if (!hasOwnProp(this, '_weekdaysRegex')) {
	            computeWeekdaysParse.call(this);
	          }
	          if (isStrict) {
	            return this._weekdaysMinStrictRegex;
	          } else {
	            return this._weekdaysMinRegex;
	          }
	        } else {
	          if (!hasOwnProp(this, '_weekdaysMinRegex')) {
	            this._weekdaysMinRegex = defaultWeekdaysMinRegex;
	          }
	          return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
	        }
	      }
	      function computeWeekdaysParse() {
	        function cmpLenRev(a, b) {
	          return b.length - a.length;
	        }
	        var minPieces = [],
	          shortPieces = [],
	          longPieces = [],
	          mixedPieces = [],
	          i,
	          mom,
	          minp,
	          shortp,
	          longp;
	        for (i = 0; i < 7; i++) {
	          // make the regex if we don't have it already
	          mom = createUTC([2000, 1]).day(i);
	          minp = regexEscape(this.weekdaysMin(mom, ''));
	          shortp = regexEscape(this.weekdaysShort(mom, ''));
	          longp = regexEscape(this.weekdays(mom, ''));
	          minPieces.push(minp);
	          shortPieces.push(shortp);
	          longPieces.push(longp);
	          mixedPieces.push(minp);
	          mixedPieces.push(shortp);
	          mixedPieces.push(longp);
	        }
	        // Sorting makes sure if one weekday (or abbr) is a prefix of another it
	        // will match the longer piece.
	        minPieces.sort(cmpLenRev);
	        shortPieces.sort(cmpLenRev);
	        longPieces.sort(cmpLenRev);
	        mixedPieces.sort(cmpLenRev);
	        this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
	        this._weekdaysShortRegex = this._weekdaysRegex;
	        this._weekdaysMinRegex = this._weekdaysRegex;
	        this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
	        this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
	        this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
	      }

	      // FORMATTING

	      function hFormat() {
	        return this.hours() % 12 || 12;
	      }
	      function kFormat() {
	        return this.hours() || 24;
	      }
	      addFormatToken('H', ['HH', 2], 0, 'hour');
	      addFormatToken('h', ['hh', 2], 0, hFormat);
	      addFormatToken('k', ['kk', 2], 0, kFormat);
	      addFormatToken('hmm', 0, 0, function () {
	        return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
	      });
	      addFormatToken('hmmss', 0, 0, function () {
	        return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
	      });
	      addFormatToken('Hmm', 0, 0, function () {
	        return '' + this.hours() + zeroFill(this.minutes(), 2);
	      });
	      addFormatToken('Hmmss', 0, 0, function () {
	        return '' + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
	      });
	      function meridiem(token, lowercase) {
	        addFormatToken(token, 0, 0, function () {
	          return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
	        });
	      }
	      meridiem('a', true);
	      meridiem('A', false);

	      // PARSING

	      function matchMeridiem(isStrict, locale) {
	        return locale._meridiemParse;
	      }
	      addRegexToken('a', matchMeridiem);
	      addRegexToken('A', matchMeridiem);
	      addRegexToken('H', match1to2, match1to2HasZero);
	      addRegexToken('h', match1to2, match1to2NoLeadingZero);
	      addRegexToken('k', match1to2, match1to2NoLeadingZero);
	      addRegexToken('HH', match1to2, match2);
	      addRegexToken('hh', match1to2, match2);
	      addRegexToken('kk', match1to2, match2);
	      addRegexToken('hmm', match3to4);
	      addRegexToken('hmmss', match5to6);
	      addRegexToken('Hmm', match3to4);
	      addRegexToken('Hmmss', match5to6);
	      addParseToken(['H', 'HH'], HOUR);
	      addParseToken(['k', 'kk'], function (input, array, config) {
	        var kInput = toInt(input);
	        array[HOUR] = kInput === 24 ? 0 : kInput;
	      });
	      addParseToken(['a', 'A'], function (input, array, config) {
	        config._isPm = config._locale.isPM(input);
	        config._meridiem = input;
	      });
	      addParseToken(['h', 'hh'], function (input, array, config) {
	        array[HOUR] = toInt(input);
	        getParsingFlags(config).bigHour = true;
	      });
	      addParseToken('hmm', function (input, array, config) {
	        var pos = input.length - 2;
	        array[HOUR] = toInt(input.substr(0, pos));
	        array[MINUTE] = toInt(input.substr(pos));
	        getParsingFlags(config).bigHour = true;
	      });
	      addParseToken('hmmss', function (input, array, config) {
	        var pos1 = input.length - 4,
	          pos2 = input.length - 2;
	        array[HOUR] = toInt(input.substr(0, pos1));
	        array[MINUTE] = toInt(input.substr(pos1, 2));
	        array[SECOND] = toInt(input.substr(pos2));
	        getParsingFlags(config).bigHour = true;
	      });
	      addParseToken('Hmm', function (input, array, config) {
	        var pos = input.length - 2;
	        array[HOUR] = toInt(input.substr(0, pos));
	        array[MINUTE] = toInt(input.substr(pos));
	      });
	      addParseToken('Hmmss', function (input, array, config) {
	        var pos1 = input.length - 4,
	          pos2 = input.length - 2;
	        array[HOUR] = toInt(input.substr(0, pos1));
	        array[MINUTE] = toInt(input.substr(pos1, 2));
	        array[SECOND] = toInt(input.substr(pos2));
	      });

	      // LOCALES

	      function localeIsPM(input) {
	        // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
	        // Using charAt should be more compatible.
	        return (input + '').toLowerCase().charAt(0) === 'p';
	      }
	      var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i,
	        // Setting the hour should keep the time, because the user explicitly
	        // specified which hour they want. So trying to maintain the same hour (in
	        // a new timezone) makes sense. Adding/subtracting hours does not follow
	        // this rule.
	        getSetHour = makeGetSet('Hours', true);
	      function localeMeridiem(hours, minutes, isLower) {
	        if (hours > 11) {
	          return isLower ? 'pm' : 'PM';
	        } else {
	          return isLower ? 'am' : 'AM';
	        }
	      }
	      var baseConfig = {
	        calendar: defaultCalendar,
	        longDateFormat: defaultLongDateFormat,
	        invalidDate: defaultInvalidDate,
	        ordinal: defaultOrdinal,
	        dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
	        relativeTime: defaultRelativeTime,
	        months: defaultLocaleMonths,
	        monthsShort: defaultLocaleMonthsShort,
	        week: defaultLocaleWeek,
	        weekdays: defaultLocaleWeekdays,
	        weekdaysMin: defaultLocaleWeekdaysMin,
	        weekdaysShort: defaultLocaleWeekdaysShort,
	        meridiemParse: defaultLocaleMeridiemParse
	      };

	      // internal storage for locale config files
	      var locales = {},
	        localeFamilies = {},
	        globalLocale;
	      function commonPrefix(arr1, arr2) {
	        var i,
	          minl = Math.min(arr1.length, arr2.length);
	        for (i = 0; i < minl; i += 1) {
	          if (arr1[i] !== arr2[i]) {
	            return i;
	          }
	        }
	        return minl;
	      }
	      function normalizeLocale(key) {
	        return key ? key.toLowerCase().replace('_', '-') : key;
	      }

	      // pick the locale from the array
	      // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
	      // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
	      function chooseLocale(names) {
	        var i = 0,
	          j,
	          next,
	          locale,
	          split;
	        while (i < names.length) {
	          split = normalizeLocale(names[i]).split('-');
	          j = split.length;
	          next = normalizeLocale(names[i + 1]);
	          next = next ? next.split('-') : null;
	          while (j > 0) {
	            locale = loadLocale(split.slice(0, j).join('-'));
	            if (locale) {
	              return locale;
	            }
	            if (next && next.length >= j && commonPrefix(split, next) >= j - 1) {
	              //the next array item is better than a shallower substring of this one
	              break;
	            }
	            j--;
	          }
	          i++;
	        }
	        return globalLocale;
	      }
	      function isLocaleNameSane(name) {
	        // Prevent names that look like filesystem paths, i.e contain '/' or '\'
	        // Ensure name is available and function returns boolean
	        return !!(name && name.match('^[^/\\\\]*$'));
	      }
	      function loadLocale(name) {
	        var oldLocale = null,
	          aliasedRequire;
	        // TODO: Find a better way to register and load all the locales in Node
	        if (locales[name] === undefined && 'object' !== 'undefined' && module && module.exports && isLocaleNameSane(name)) {
	          try {
	            oldLocale = globalLocale._abbr;
	            aliasedRequire = commonjsRequire;
	            aliasedRequire('./locale/' + name);
	            getSetGlobalLocale(oldLocale);
	          } catch (e) {
	            // mark as not found to avoid repeating expensive file require call causing high CPU
	            // when trying to find en-US, en_US, en-us for every format call
	            locales[name] = null; // null means not found
	          }
	        }
	        return locales[name];
	      }

	      // This function will load locale and then set the global locale.  If
	      // no arguments are passed in, it will simply return the current global
	      // locale key.
	      function getSetGlobalLocale(key, values) {
	        var data;
	        if (key) {
	          if (isUndefined(values)) {
	            data = getLocale(key);
	          } else {
	            data = defineLocale(key, values);
	          }
	          if (data) {
	            // moment.duration._locale = moment._locale = data;
	            globalLocale = data;
	          } else {
	            if (typeof console !== 'undefined' && console.warn) {
	              //warn user if arguments are passed but the locale could not be set
	              console.warn('Locale ' + key + ' not found. Did you forget to load it?');
	            }
	          }
	        }
	        return globalLocale._abbr;
	      }
	      function defineLocale(name, config) {
	        if (config !== null) {
	          var locale,
	            parentConfig = baseConfig;
	          config.abbr = name;
	          if (locales[name] != null) {
	            deprecateSimple('defineLocaleOverride', 'use moment.updateLocale(localeName, config) to change ' + 'an existing locale. moment.defineLocale(localeName, ' + 'config) should only be used for creating a new locale ' + 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
	            parentConfig = locales[name]._config;
	          } else if (config.parentLocale != null) {
	            if (locales[config.parentLocale] != null) {
	              parentConfig = locales[config.parentLocale]._config;
	            } else {
	              locale = loadLocale(config.parentLocale);
	              if (locale != null) {
	                parentConfig = locale._config;
	              } else {
	                if (!localeFamilies[config.parentLocale]) {
	                  localeFamilies[config.parentLocale] = [];
	                }
	                localeFamilies[config.parentLocale].push({
	                  name: name,
	                  config: config
	                });
	                return null;
	              }
	            }
	          }
	          locales[name] = new Locale(mergeConfigs(parentConfig, config));
	          if (localeFamilies[name]) {
	            localeFamilies[name].forEach(function (x) {
	              defineLocale(x.name, x.config);
	            });
	          }

	          // backwards compat for now: also set the locale
	          // make sure we set the locale AFTER all child locales have been
	          // created, so we won't end up with the child locale set.
	          getSetGlobalLocale(name);
	          return locales[name];
	        } else {
	          // useful for testing
	          delete locales[name];
	          return null;
	        }
	      }
	      function updateLocale(name, config) {
	        if (config != null) {
	          var locale,
	            tmpLocale,
	            parentConfig = baseConfig;
	          if (locales[name] != null && locales[name].parentLocale != null) {
	            // Update existing child locale in-place to avoid memory-leaks
	            locales[name].set(mergeConfigs(locales[name]._config, config));
	          } else {
	            // MERGE
	            tmpLocale = loadLocale(name);
	            if (tmpLocale != null) {
	              parentConfig = tmpLocale._config;
	            }
	            config = mergeConfigs(parentConfig, config);
	            if (tmpLocale == null) {
	              // updateLocale is called for creating a new locale
	              // Set abbr so it will have a name (getters return
	              // undefined otherwise).
	              config.abbr = name;
	            }
	            locale = new Locale(config);
	            locale.parentLocale = locales[name];
	            locales[name] = locale;
	          }

	          // backwards compat for now: also set the locale
	          getSetGlobalLocale(name);
	        } else {
	          // pass null for config to unupdate, useful for tests
	          if (locales[name] != null) {
	            if (locales[name].parentLocale != null) {
	              locales[name] = locales[name].parentLocale;
	              if (name === getSetGlobalLocale()) {
	                getSetGlobalLocale(name);
	              }
	            } else if (locales[name] != null) {
	              delete locales[name];
	            }
	          }
	        }
	        return locales[name];
	      }

	      // returns locale data
	      function getLocale(key) {
	        var locale;
	        if (key && key._locale && key._locale._abbr) {
	          key = key._locale._abbr;
	        }
	        if (!key) {
	          return globalLocale;
	        }
	        if (!isArray(key)) {
	          //short-circuit everything else
	          locale = loadLocale(key);
	          if (locale) {
	            return locale;
	          }
	          key = [key];
	        }
	        return chooseLocale(key);
	      }
	      function listLocales() {
	        return keys(locales);
	      }
	      function checkOverflow(m) {
	        var overflow,
	          a = m._a;
	        if (a && getParsingFlags(m).overflow === -2) {
	          overflow = a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : a[HOUR] < 0 || a[HOUR] > 24 || a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0) ? HOUR : a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : -1;
	          if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
	            overflow = DATE;
	          }
	          if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
	            overflow = WEEK;
	          }
	          if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
	            overflow = WEEKDAY;
	          }
	          getParsingFlags(m).overflow = overflow;
	        }
	        return m;
	      }

	      // iso 8601 regex
	      // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
	      var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
	        basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
	        tzRegex = /Z|[+-]\d\d(?::?\d\d)?/,
	        isoDates = [['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], ['GGGG-[W]WW', /\d{4}-W\d\d/, false], ['YYYY-DDD', /\d{4}-\d{3}/], ['YYYY-MM', /\d{4}-\d\d/, false], ['YYYYYYMMDD', /[+-]\d{10}/], ['YYYYMMDD', /\d{8}/], ['GGGG[W]WWE', /\d{4}W\d{3}/], ['GGGG[W]WW', /\d{4}W\d{2}/, false], ['YYYYDDD', /\d{7}/], ['YYYYMM', /\d{6}/, false], ['YYYY', /\d{4}/, false]],
	        // iso time formats and regexes
	        isoTimes = [['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], ['HH:mm:ss', /\d\d:\d\d:\d\d/], ['HH:mm', /\d\d:\d\d/], ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], ['HHmmss', /\d\d\d\d\d\d/], ['HHmm', /\d\d\d\d/], ['HH', /\d\d/]],
	        aspNetJsonRegex = /^\/?Date\((-?\d+)/i,
	        // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
	        rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,
	        obsOffsets = {
	          UT: 0,
	          GMT: 0,
	          EDT: -4 * 60,
	          EST: -5 * 60,
	          CDT: -5 * 60,
	          CST: -6 * 60,
	          MDT: -6 * 60,
	          MST: -7 * 60,
	          PDT: -7 * 60,
	          PST: -8 * 60
	        };

	      // date from iso format
	      function configFromISO(config) {
	        var i,
	          l,
	          string = config._i,
	          match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
	          allowTime,
	          dateFormat,
	          timeFormat,
	          tzFormat,
	          isoDatesLen = isoDates.length,
	          isoTimesLen = isoTimes.length;
	        if (match) {
	          getParsingFlags(config).iso = true;
	          for (i = 0, l = isoDatesLen; i < l; i++) {
	            if (isoDates[i][1].exec(match[1])) {
	              dateFormat = isoDates[i][0];
	              allowTime = isoDates[i][2] !== false;
	              break;
	            }
	          }
	          if (dateFormat == null) {
	            config._isValid = false;
	            return;
	          }
	          if (match[3]) {
	            for (i = 0, l = isoTimesLen; i < l; i++) {
	              if (isoTimes[i][1].exec(match[3])) {
	                // match[2] should be 'T' or space
	                timeFormat = (match[2] || ' ') + isoTimes[i][0];
	                break;
	              }
	            }
	            if (timeFormat == null) {
	              config._isValid = false;
	              return;
	            }
	          }
	          if (!allowTime && timeFormat != null) {
	            config._isValid = false;
	            return;
	          }
	          if (match[4]) {
	            if (tzRegex.exec(match[4])) {
	              tzFormat = 'Z';
	            } else {
	              config._isValid = false;
	              return;
	            }
	          }
	          config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
	          configFromStringAndFormat(config);
	        } else {
	          config._isValid = false;
	        }
	      }
	      function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
	        var result = [untruncateYear(yearStr), defaultLocaleMonthsShort.indexOf(monthStr), parseInt(dayStr, 10), parseInt(hourStr, 10), parseInt(minuteStr, 10)];
	        if (secondStr) {
	          result.push(parseInt(secondStr, 10));
	        }
	        return result;
	      }
	      function untruncateYear(yearStr) {
	        var year = parseInt(yearStr, 10);
	        if (year <= 49) {
	          return 2000 + year;
	        } else if (year <= 999) {
	          return 1900 + year;
	        }
	        return year;
	      }
	      function preprocessRFC2822(s) {
	        // Remove comments and folding whitespace and replace multiple-spaces with a single space
	        return s.replace(/\([^()]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, '');
	      }
	      function checkWeekday(weekdayStr, parsedInput, config) {
	        if (weekdayStr) {
	          // TODO: Replace the vanilla JS Date object with an independent day-of-week check.
	          var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
	            weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay();
	          if (weekdayProvided !== weekdayActual) {
	            getParsingFlags(config).weekdayMismatch = true;
	            config._isValid = false;
	            return false;
	          }
	        }
	        return true;
	      }
	      function calculateOffset(obsOffset, militaryOffset, numOffset) {
	        if (obsOffset) {
	          return obsOffsets[obsOffset];
	        } else if (militaryOffset) {
	          // the only allowed military tz is Z
	          return 0;
	        } else {
	          var hm = parseInt(numOffset, 10),
	            m = hm % 100,
	            h = (hm - m) / 100;
	          return h * 60 + m;
	        }
	      }

	      // date and time from ref 2822 format
	      function configFromRFC2822(config) {
	        var match = rfc2822.exec(preprocessRFC2822(config._i)),
	          parsedArray;
	        if (match) {
	          parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]);
	          if (!checkWeekday(match[1], parsedArray, config)) {
	            return;
	          }
	          config._a = parsedArray;
	          config._tzm = calculateOffset(match[8], match[9], match[10]);
	          config._d = createUTCDate.apply(null, config._a);
	          config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
	          getParsingFlags(config).rfc2822 = true;
	        } else {
	          config._isValid = false;
	        }
	      }

	      // date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict
	      function configFromString(config) {
	        var matched = aspNetJsonRegex.exec(config._i);
	        if (matched !== null) {
	          config._d = new Date(+matched[1]);
	          return;
	        }
	        configFromISO(config);
	        if (config._isValid === false) {
	          delete config._isValid;
	        } else {
	          return;
	        }
	        configFromRFC2822(config);
	        if (config._isValid === false) {
	          delete config._isValid;
	        } else {
	          return;
	        }
	        if (config._strict) {
	          config._isValid = false;
	        } else {
	          // Final attempt, use Input Fallback
	          hooks.createFromInputFallback(config);
	        }
	      }
	      hooks.createFromInputFallback = deprecate('value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' + 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' + 'discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.', function (config) {
	        config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
	      });

	      // Pick the first defined of two or three arguments.
	      function defaults(a, b, c) {
	        if (a != null) {
	          return a;
	        }
	        if (b != null) {
	          return b;
	        }
	        return c;
	      }
	      function currentDateArray(config) {
	        // hooks is actually the exported moment object
	        var nowValue = new Date(hooks.now());
	        if (config._useUTC) {
	          return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
	        }
	        return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
	      }

	      // convert an array to a date.
	      // the array should mirror the parameters below
	      // note: all values past the year are optional and will default to the lowest possible value.
	      // [year, month, day , hour, minute, second, millisecond]
	      function configFromArray(config) {
	        var i,
	          date,
	          input = [],
	          currentDate,
	          expectedWeekday,
	          yearToUse;
	        if (config._d) {
	          return;
	        }
	        currentDate = currentDateArray(config);

	        //compute day of the year from weeks and weekdays
	        if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
	          dayOfYearFromWeekInfo(config);
	        }

	        //if the day of the year is set, figure out what it is
	        if (config._dayOfYear != null) {
	          yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
	          if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) {
	            getParsingFlags(config)._overflowDayOfYear = true;
	          }
	          date = createUTCDate(yearToUse, 0, config._dayOfYear);
	          config._a[MONTH] = date.getUTCMonth();
	          config._a[DATE] = date.getUTCDate();
	        }

	        // Default to current date.
	        // * if no year, month, day of month are given, default to today
	        // * if day of month is given, default month and year
	        // * if month is given, default only year
	        // * if year is given, don't default anything
	        for (i = 0; i < 3 && config._a[i] == null; ++i) {
	          config._a[i] = input[i] = currentDate[i];
	        }

	        // Zero out whatever was not defaulted, including time
	        for (; i < 7; i++) {
	          config._a[i] = input[i] = config._a[i] == null ? i === 2 ? 1 : 0 : config._a[i];
	        }

	        // Check for 24:00:00.000
	        if (config._a[HOUR] === 24 && config._a[MINUTE] === 0 && config._a[SECOND] === 0 && config._a[MILLISECOND] === 0) {
	          config._nextDay = true;
	          config._a[HOUR] = 0;
	        }
	        config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
	        expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay();

	        // Apply timezone offset from input. The actual utcOffset can be changed
	        // with parseZone.
	        if (config._tzm != null) {
	          config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
	        }
	        if (config._nextDay) {
	          config._a[HOUR] = 24;
	        }

	        // check for mismatching day of week
	        if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) {
	          getParsingFlags(config).weekdayMismatch = true;
	        }
	      }
	      function dayOfYearFromWeekInfo(config) {
	        var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek;
	        w = config._w;
	        if (w.GG != null || w.W != null || w.E != null) {
	          dow = 1;
	          doy = 4;

	          // TODO: We need to take the current isoWeekYear, but that depends on
	          // how we interpret now (local, utc, fixed offset). So create
	          // a now version of current config (take local/utc/offset flags, and
	          // create now).
	          weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
	          week = defaults(w.W, 1);
	          weekday = defaults(w.E, 1);
	          if (weekday < 1 || weekday > 7) {
	            weekdayOverflow = true;
	          }
	        } else {
	          dow = config._locale._week.dow;
	          doy = config._locale._week.doy;
	          curWeek = weekOfYear(createLocal(), dow, doy);
	          weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);

	          // Default to current week.
	          week = defaults(w.w, curWeek.week);
	          if (w.d != null) {
	            // weekday -- low day numbers are considered next week
	            weekday = w.d;
	            if (weekday < 0 || weekday > 6) {
	              weekdayOverflow = true;
	            }
	          } else if (w.e != null) {
	            // local weekday -- counting starts from beginning of week
	            weekday = w.e + dow;
	            if (w.e < 0 || w.e > 6) {
	              weekdayOverflow = true;
	            }
	          } else {
	            // default to beginning of week
	            weekday = dow;
	          }
	        }
	        if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
	          getParsingFlags(config)._overflowWeeks = true;
	        } else if (weekdayOverflow != null) {
	          getParsingFlags(config)._overflowWeekday = true;
	        } else {
	          temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
	          config._a[YEAR] = temp.year;
	          config._dayOfYear = temp.dayOfYear;
	        }
	      }

	      // constant that refers to the ISO standard
	      hooks.ISO_8601 = function () {};

	      // constant that refers to the RFC 2822 form
	      hooks.RFC_2822 = function () {};

	      // date from string and format string
	      function configFromStringAndFormat(config) {
	        // TODO: Move this to another part of the creation flow to prevent circular deps
	        if (config._f === hooks.ISO_8601) {
	          configFromISO(config);
	          return;
	        }
	        if (config._f === hooks.RFC_2822) {
	          configFromRFC2822(config);
	          return;
	        }
	        config._a = [];
	        getParsingFlags(config).empty = true;

	        // This array is used to make a Date, either with `new Date` or `Date.UTC`
	        var string = '' + config._i,
	          i,
	          parsedInput,
	          tokens,
	          token,
	          skipped,
	          stringLength = string.length,
	          totalParsedInputLength = 0,
	          era,
	          tokenLen;
	        tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
	        tokenLen = tokens.length;
	        for (i = 0; i < tokenLen; i++) {
	          token = tokens[i];
	          parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
	          if (parsedInput) {
	            skipped = string.substr(0, string.indexOf(parsedInput));
	            if (skipped.length > 0) {
	              getParsingFlags(config).unusedInput.push(skipped);
	            }
	            string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
	            totalParsedInputLength += parsedInput.length;
	          }
	          // don't parse if it's not a known token
	          if (formatTokenFunctions[token]) {
	            if (parsedInput) {
	              getParsingFlags(config).empty = false;
	            } else {
	              getParsingFlags(config).unusedTokens.push(token);
	            }
	            addTimeToArrayFromToken(token, parsedInput, config);
	          } else if (config._strict && !parsedInput) {
	            getParsingFlags(config).unusedTokens.push(token);
	          }
	        }

	        // add remaining unparsed input length to the string
	        getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
	        if (string.length > 0) {
	          getParsingFlags(config).unusedInput.push(string);
	        }

	        // clear _12h flag if hour is <= 12
	        if (config._a[HOUR] <= 12 && getParsingFlags(config).bigHour === true && config._a[HOUR] > 0) {
	          getParsingFlags(config).bigHour = undefined;
	        }
	        getParsingFlags(config).parsedDateParts = config._a.slice(0);
	        getParsingFlags(config).meridiem = config._meridiem;
	        // handle meridiem
	        config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);

	        // handle era
	        era = getParsingFlags(config).era;
	        if (era !== null) {
	          config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]);
	        }
	        configFromArray(config);
	        checkOverflow(config);
	      }
	      function meridiemFixWrap(locale, hour, meridiem) {
	        var isPm;
	        if (meridiem == null) {
	          // nothing to do
	          return hour;
	        }
	        if (locale.meridiemHour != null) {
	          return locale.meridiemHour(hour, meridiem);
	        } else if (locale.isPM != null) {
	          // Fallback
	          isPm = locale.isPM(meridiem);
	          if (isPm && hour < 12) {
	            hour += 12;
	          }
	          if (!isPm && hour === 12) {
	            hour = 0;
	          }
	          return hour;
	        } else {
	          // this is not supposed to happen
	          return hour;
	        }
	      }

	      // date from string and array of format strings
	      function configFromStringAndArray(config) {
	        var tempConfig,
	          bestMoment,
	          scoreToBeat,
	          i,
	          currentScore,
	          validFormatFound,
	          bestFormatIsValid = false,
	          configfLen = config._f.length;
	        if (configfLen === 0) {
	          getParsingFlags(config).invalidFormat = true;
	          config._d = new Date(NaN);
	          return;
	        }
	        for (i = 0; i < configfLen; i++) {
	          currentScore = 0;
	          validFormatFound = false;
	          tempConfig = copyConfig({}, config);
	          if (config._useUTC != null) {
	            tempConfig._useUTC = config._useUTC;
	          }
	          tempConfig._f = config._f[i];
	          configFromStringAndFormat(tempConfig);
	          if (isValid(tempConfig)) {
	            validFormatFound = true;
	          }

	          // if there is any input that was not parsed add a penalty for that format
	          currentScore += getParsingFlags(tempConfig).charsLeftOver;

	          //or tokens
	          currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
	          getParsingFlags(tempConfig).score = currentScore;
	          if (!bestFormatIsValid) {
	            if (scoreToBeat == null || currentScore < scoreToBeat || validFormatFound) {
	              scoreToBeat = currentScore;
	              bestMoment = tempConfig;
	              if (validFormatFound) {
	                bestFormatIsValid = true;
	              }
	            }
	          } else {
	            if (currentScore < scoreToBeat) {
	              scoreToBeat = currentScore;
	              bestMoment = tempConfig;
	            }
	          }
	        }
	        extend(config, bestMoment || tempConfig);
	      }
	      function configFromObject(config) {
	        if (config._d) {
	          return;
	        }
	        var i = normalizeObjectUnits(config._i),
	          dayOrDate = i.day === undefined ? i.date : i.day;
	        config._a = map([i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond], function (obj) {
	          return obj && parseInt(obj, 10);
	        });
	        configFromArray(config);
	      }
	      function createFromConfig(config) {
	        var res = new Moment(checkOverflow(prepareConfig(config)));
	        if (res._nextDay) {
	          // Adding is smart enough around DST
	          res.add(1, 'd');
	          res._nextDay = undefined;
	        }
	        return res;
	      }
	      function prepareConfig(config) {
	        var input = config._i,
	          format = config._f;
	        config._locale = config._locale || getLocale(config._l);
	        if (input === null || format === undefined && input === '') {
	          return createInvalid({
	            nullInput: true
	          });
	        }
	        if (typeof input === 'string') {
	          config._i = input = config._locale.preparse(input);
	        }
	        if (isMoment(input)) {
	          return new Moment(checkOverflow(input));
	        } else if (isDate(input)) {
	          config._d = input;
	        } else if (isArray(format)) {
	          configFromStringAndArray(config);
	        } else if (format) {
	          configFromStringAndFormat(config);
	        } else {
	          configFromInput(config);
	        }
	        if (!isValid(config)) {
	          config._d = null;
	        }
	        return config;
	      }
	      function configFromInput(config) {
	        var input = config._i;
	        if (isUndefined(input)) {
	          config._d = new Date(hooks.now());
	        } else if (isDate(input)) {
	          config._d = new Date(input.valueOf());
	        } else if (typeof input === 'string') {
	          configFromString(config);
	        } else if (isArray(input)) {
	          config._a = map(input.slice(0), function (obj) {
	            return parseInt(obj, 10);
	          });
	          configFromArray(config);
	        } else if (isObject(input)) {
	          configFromObject(config);
	        } else if (isNumber(input)) {
	          // from milliseconds
	          config._d = new Date(input);
	        } else {
	          hooks.createFromInputFallback(config);
	        }
	      }
	      function createLocalOrUTC(input, format, locale, strict, isUTC) {
	        var c = {};
	        if (format === true || format === false) {
	          strict = format;
	          format = undefined;
	        }
	        if (locale === true || locale === false) {
	          strict = locale;
	          locale = undefined;
	        }
	        if (isObject(input) && isObjectEmpty(input) || isArray(input) && input.length === 0) {
	          input = undefined;
	        }
	        // object construction must be done this way.
	        // https://github.com/moment/moment/issues/1423
	        c._isAMomentObject = true;
	        c._useUTC = c._isUTC = isUTC;
	        c._l = locale;
	        c._i = input;
	        c._f = format;
	        c._strict = strict;
	        return createFromConfig(c);
	      }
	      function createLocal(input, format, locale, strict) {
	        return createLocalOrUTC(input, format, locale, strict, false);
	      }
	      var prototypeMin = deprecate('moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', function () {
	          var other = createLocal.apply(null, arguments);
	          if (this.isValid() && other.isValid()) {
	            return other < this ? this : other;
	          } else {
	            return createInvalid();
	          }
	        }),
	        prototypeMax = deprecate('moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', function () {
	          var other = createLocal.apply(null, arguments);
	          if (this.isValid() && other.isValid()) {
	            return other > this ? this : other;
	          } else {
	            return createInvalid();
	          }
	        });

	      // Pick a moment m from moments so that m[fn](other) is true for all
	      // other. This relies on the function fn to be transitive.
	      //
	      // moments should either be an array of moment objects or an array, whose
	      // first element is an array of moment objects.
	      function pickBy(fn, moments) {
	        var res, i;
	        if (moments.length === 1 && isArray(moments[0])) {
	          moments = moments[0];
	        }
	        if (!moments.length) {
	          return createLocal();
	        }
	        res = moments[0];
	        for (i = 1; i < moments.length; ++i) {
	          if (!moments[i].isValid() || moments[i][fn](res)) {
	            res = moments[i];
	          }
	        }
	        return res;
	      }

	      // TODO: Use [].sort instead?
	      function min() {
	        var args = [].slice.call(arguments, 0);
	        return pickBy('isBefore', args);
	      }
	      function max() {
	        var args = [].slice.call(arguments, 0);
	        return pickBy('isAfter', args);
	      }
	      var now = function () {
	        return Date.now ? Date.now() : +new Date();
	      };
	      var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];
	      function isDurationValid(m) {
	        var key,
	          unitHasDecimal = false,
	          i,
	          orderLen = ordering.length;
	        for (key in m) {
	          if (hasOwnProp(m, key) && !(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
	            return false;
	          }
	        }
	        for (i = 0; i < orderLen; ++i) {
	          if (m[ordering[i]]) {
	            if (unitHasDecimal) {
	              return false; // only allow non-integers for smallest unit
	            }
	            if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
	              unitHasDecimal = true;
	            }
	          }
	        }
	        return true;
	      }
	      function isValid$1() {
	        return this._isValid;
	      }
	      function createInvalid$1() {
	        return createDuration(NaN);
	      }
	      function Duration(duration) {
	        var normalizedInput = normalizeObjectUnits(duration),
	          years = normalizedInput.year || 0,
	          quarters = normalizedInput.quarter || 0,
	          months = normalizedInput.month || 0,
	          weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
	          days = normalizedInput.day || 0,
	          hours = normalizedInput.hour || 0,
	          minutes = normalizedInput.minute || 0,
	          seconds = normalizedInput.second || 0,
	          milliseconds = normalizedInput.millisecond || 0;
	        this._isValid = isDurationValid(normalizedInput);

	        // representation for dateAddRemove
	        this._milliseconds = +milliseconds + seconds * 1e3 +
	        // 1000
	        minutes * 6e4 +
	        // 1000 * 60
	        hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
	        // Because of dateAddRemove treats 24 hours as different from a
	        // day when working around DST, we need to store them separately
	        this._days = +days + weeks * 7;
	        // It is impossible to translate months into days without knowing
	        // which months you are are talking about, so we have to store
	        // it separately.
	        this._months = +months + quarters * 3 + years * 12;
	        this._data = {};
	        this._locale = getLocale();
	        this._bubble();
	      }
	      function isDuration(obj) {
	        return obj instanceof Duration;
	      }
	      function absRound(number) {
	        if (number < 0) {
	          return Math.round(-1 * number) * -1;
	        } else {
	          return Math.round(number);
	        }
	      }

	      // compare two arrays, return the number of differences
	      function compareArrays(array1, array2, dontConvert) {
	        var len = Math.min(array1.length, array2.length),
	          lengthDiff = Math.abs(array1.length - array2.length),
	          diffs = 0,
	          i;
	        for (i = 0; i < len; i++) {
	          if (toInt(array1[i]) !== toInt(array2[i])) {
	            diffs++;
	          }
	        }
	        return diffs + lengthDiff;
	      }

	      // FORMATTING

	      function offset(token, separator) {
	        addFormatToken(token, 0, 0, function () {
	          var offset = this.utcOffset(),
	            sign = '+';
	          if (offset < 0) {
	            offset = -offset;
	            sign = '-';
	          }
	          return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~offset % 60, 2);
	        });
	      }
	      offset('Z', ':');
	      offset('ZZ', '');

	      // PARSING

	      addRegexToken('Z', matchShortOffset);
	      addRegexToken('ZZ', matchShortOffset);
	      addParseToken(['Z', 'ZZ'], function (input, array, config) {
	        config._useUTC = true;
	        config._tzm = offsetFromString(matchShortOffset, input);
	      });

	      // HELPERS

	      // timezone chunker
	      // '+10:00' > ['10',  '00']
	      // '-1530'  > ['-15', '30']
	      var chunkOffset = /([\+\-]|\d\d)/gi;
	      function offsetFromString(matcher, string) {
	        var matches = (string || '').match(matcher),
	          chunk,
	          parts,
	          minutes;
	        if (matches === null) {
	          return null;
	        }
	        chunk = matches[matches.length - 1] || [];
	        parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
	        minutes = +(parts[1] * 60) + toInt(parts[2]);
	        return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes;
	      }

	      // Return a moment from input, that is local/utc/zone equivalent to model.
	      function cloneWithOffset(input, model) {
	        var res, diff;
	        if (model._isUTC) {
	          res = model.clone();
	          diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
	          // Use low-level api, because this fn is low-level api.
	          res._d.setTime(res._d.valueOf() + diff);
	          hooks.updateOffset(res, false);
	          return res;
	        } else {
	          return createLocal(input).local();
	        }
	      }
	      function getDateOffset(m) {
	        // On Firefox.24 Date#getTimezoneOffset returns a floating point.
	        // https://github.com/moment/moment/pull/1871
	        return -Math.round(m._d.getTimezoneOffset());
	      }

	      // HOOKS

	      // This function will be called whenever a moment is mutated.
	      // It is intended to keep the offset in sync with the timezone.
	      hooks.updateOffset = function () {};

	      // MOMENTS

	      // keepLocalTime = true means only change the timezone, without
	      // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
	      // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
	      // +0200, so we adjust the time as needed, to be valid.
	      //
	      // Keeping the time actually adds/subtracts (one hour)
	      // from the actual represented time. That is why we call updateOffset
	      // a second time. In case it wants us to change the offset again
	      // _changeInProgress == true case, then we have to adjust, because
	      // there is no such time in the given timezone.
	      function getSetOffset(input, keepLocalTime, keepMinutes) {
	        var offset = this._offset || 0,
	          localAdjust;
	        if (!this.isValid()) {
	          return input != null ? this : NaN;
	        }
	        if (input != null) {
	          if (typeof input === 'string') {
	            input = offsetFromString(matchShortOffset, input);
	            if (input === null) {
	              return this;
	            }
	          } else if (Math.abs(input) < 16 && !keepMinutes) {
	            input = input * 60;
	          }
	          if (!this._isUTC && keepLocalTime) {
	            localAdjust = getDateOffset(this);
	          }
	          this._offset = input;
	          this._isUTC = true;
	          if (localAdjust != null) {
	            this.add(localAdjust, 'm');
	          }
	          if (offset !== input) {
	            if (!keepLocalTime || this._changeInProgress) {
	              addSubtract(this, createDuration(input - offset, 'm'), 1, false);
	            } else if (!this._changeInProgress) {
	              this._changeInProgress = true;
	              hooks.updateOffset(this, true);
	              this._changeInProgress = null;
	            }
	          }
	          return this;
	        } else {
	          return this._isUTC ? offset : getDateOffset(this);
	        }
	      }
	      function getSetZone(input, keepLocalTime) {
	        if (input != null) {
	          if (typeof input !== 'string') {
	            input = -input;
	          }
	          this.utcOffset(input, keepLocalTime);
	          return this;
	        } else {
	          return -this.utcOffset();
	        }
	      }
	      function setOffsetToUTC(keepLocalTime) {
	        return this.utcOffset(0, keepLocalTime);
	      }
	      function setOffsetToLocal(keepLocalTime) {
	        if (this._isUTC) {
	          this.utcOffset(0, keepLocalTime);
	          this._isUTC = false;
	          if (keepLocalTime) {
	            this.subtract(getDateOffset(this), 'm');
	          }
	        }
	        return this;
	      }
	      function setOffsetToParsedOffset() {
	        if (this._tzm != null) {
	          this.utcOffset(this._tzm, false, true);
	        } else if (typeof this._i === 'string') {
	          var tZone = offsetFromString(matchOffset, this._i);
	          if (tZone != null) {
	            this.utcOffset(tZone);
	          } else {
	            this.utcOffset(0, true);
	          }
	        }
	        return this;
	      }
	      function hasAlignedHourOffset(input) {
	        if (!this.isValid()) {
	          return false;
	        }
	        input = input ? createLocal(input).utcOffset() : 0;
	        return (this.utcOffset() - input) % 60 === 0;
	      }
	      function isDaylightSavingTime() {
	        return this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset();
	      }
	      function isDaylightSavingTimeShifted() {
	        if (!isUndefined(this._isDSTShifted)) {
	          return this._isDSTShifted;
	        }
	        var c = {},
	          other;
	        copyConfig(c, this);
	        c = prepareConfig(c);
	        if (c._a) {
	          other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
	          this._isDSTShifted = this.isValid() && compareArrays(c._a, other.toArray()) > 0;
	        } else {
	          this._isDSTShifted = false;
	        }
	        return this._isDSTShifted;
	      }
	      function isLocal() {
	        return this.isValid() ? !this._isUTC : false;
	      }
	      function isUtcOffset() {
	        return this.isValid() ? this._isUTC : false;
	      }
	      function isUtc() {
	        return this.isValid() ? this._isUTC && this._offset === 0 : false;
	      }

	      // ASP.NET json date format regex
	      var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,
	        // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
	        // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
	        // and further modified to allow for strings containing both week and day
	        isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
	      function createDuration(input, key) {
	        var duration = input,
	          // matching against regexp is expensive, do it on demand
	          match = null,
	          sign,
	          ret,
	          diffRes;
	        if (isDuration(input)) {
	          duration = {
	            ms: input._milliseconds,
	            d: input._days,
	            M: input._months
	          };
	        } else if (isNumber(input) || !isNaN(+input)) {
	          duration = {};
	          if (key) {
	            duration[key] = +input;
	          } else {
	            duration.milliseconds = +input;
	          }
	        } else if (match = aspNetRegex.exec(input)) {
	          sign = match[1] === '-' ? -1 : 1;
	          duration = {
	            y: 0,
	            d: toInt(match[DATE]) * sign,
	            h: toInt(match[HOUR]) * sign,
	            m: toInt(match[MINUTE]) * sign,
	            s: toInt(match[SECOND]) * sign,
	            ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
	          };
	        } else if (match = isoRegex.exec(input)) {
	          sign = match[1] === '-' ? -1 : 1;
	          duration = {
	            y: parseIso(match[2], sign),
	            M: parseIso(match[3], sign),
	            w: parseIso(match[4], sign),
	            d: parseIso(match[5], sign),
	            h: parseIso(match[6], sign),
	            m: parseIso(match[7], sign),
	            s: parseIso(match[8], sign)
	          };
	        } else if (duration == null) {
	          // checks for null or undefined
	          duration = {};
	        } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
	          diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
	          duration = {};
	          duration.ms = diffRes.milliseconds;
	          duration.M = diffRes.months;
	        }
	        ret = new Duration(duration);
	        if (isDuration(input) && hasOwnProp(input, '_locale')) {
	          ret._locale = input._locale;
	        }
	        if (isDuration(input) && hasOwnProp(input, '_isValid')) {
	          ret._isValid = input._isValid;
	        }
	        return ret;
	      }
	      createDuration.fn = Duration.prototype;
	      createDuration.invalid = createInvalid$1;
	      function parseIso(inp, sign) {
	        // We'd normally use ~~inp for this, but unfortunately it also
	        // converts floats to ints.
	        // inp may be undefined, so careful calling replace on it.
	        var res = inp && parseFloat(inp.replace(',', '.'));
	        // apply sign while we're at it
	        return (isNaN(res) ? 0 : res) * sign;
	      }
	      function positiveMomentsDifference(base, other) {
	        var res = {};
	        res.months = other.month() - base.month() + (other.year() - base.year()) * 12;
	        if (base.clone().add(res.months, 'M').isAfter(other)) {
	          --res.months;
	        }
	        res.milliseconds = +other - +base.clone().add(res.months, 'M');
	        return res;
	      }
	      function momentsDifference(base, other) {
	        var res;
	        if (!(base.isValid() && other.isValid())) {
	          return {
	            milliseconds: 0,
	            months: 0
	          };
	        }
	        other = cloneWithOffset(other, base);
	        if (base.isBefore(other)) {
	          res = positiveMomentsDifference(base, other);
	        } else {
	          res = positiveMomentsDifference(other, base);
	          res.milliseconds = -res.milliseconds;
	          res.months = -res.months;
	        }
	        return res;
	      }

	      // TODO: remove 'name' arg after deprecation is removed
	      function createAdder(direction, name) {
	        return function (val, period) {
	          var dur, tmp;
	          //invert the arguments, but complain about it
	          if (period !== null && !isNaN(+period)) {
	            deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
	            tmp = val;
	            val = period;
	            period = tmp;
	          }
	          dur = createDuration(val, period);
	          addSubtract(this, dur, direction);
	          return this;
	        };
	      }
	      function addSubtract(mom, duration, isAdding, updateOffset) {
	        var milliseconds = duration._milliseconds,
	          days = absRound(duration._days),
	          months = absRound(duration._months);
	        if (!mom.isValid()) {
	          // No op
	          return;
	        }
	        updateOffset = updateOffset == null ? true : updateOffset;
	        if (months) {
	          setMonth(mom, get(mom, 'Month') + months * isAdding);
	        }
	        if (days) {
	          set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
	        }
	        if (milliseconds) {
	          mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
	        }
	        if (updateOffset) {
	          hooks.updateOffset(mom, days || months);
	        }
	      }
	      var add = createAdder(1, 'add'),
	        subtract = createAdder(-1, 'subtract');
	      function isString(input) {
	        return typeof input === 'string' || input instanceof String;
	      }

	      // type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined
	      function isMomentInput(input) {
	        return isMoment(input) || isDate(input) || isString(input) || isNumber(input) || isNumberOrStringArray(input) || isMomentInputObject(input) || input === null || input === undefined;
	      }
	      function isMomentInputObject(input) {
	        var objectTest = isObject(input) && !isObjectEmpty(input),
	          propertyTest = false,
	          properties = ['years', 'year', 'y', 'months', 'month', 'M', 'days', 'day', 'd', 'dates', 'date', 'D', 'hours', 'hour', 'h', 'minutes', 'minute', 'm', 'seconds', 'second', 's', 'milliseconds', 'millisecond', 'ms'],
	          i,
	          property,
	          propertyLen = properties.length;
	        for (i = 0; i < propertyLen; i += 1) {
	          property = properties[i];
	          propertyTest = propertyTest || hasOwnProp(input, property);
	        }
	        return objectTest && propertyTest;
	      }
	      function isNumberOrStringArray(input) {
	        var arrayTest = isArray(input),
	          dataTypeTest = false;
	        if (arrayTest) {
	          dataTypeTest = input.filter(function (item) {
	            return !isNumber(item) && isString(input);
	          }).length === 0;
	        }
	        return arrayTest && dataTypeTest;
	      }
	      function isCalendarSpec(input) {
	        var objectTest = isObject(input) && !isObjectEmpty(input),
	          propertyTest = false,
	          properties = ['sameDay', 'nextDay', 'lastDay', 'nextWeek', 'lastWeek', 'sameElse'],
	          i,
	          property;
	        for (i = 0; i < properties.length; i += 1) {
	          property = properties[i];
	          propertyTest = propertyTest || hasOwnProp(input, property);
	        }
	        return objectTest && propertyTest;
	      }
	      function getCalendarFormat(myMoment, now) {
	        var diff = myMoment.diff(now, 'days', true);
	        return diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse';
	      }
	      function calendar$1(time, formats) {
	        // Support for single parameter, formats only overload to the calendar function
	        if (arguments.length === 1) {
	          if (!arguments[0]) {
	            time = undefined;
	            formats = undefined;
	          } else if (isMomentInput(arguments[0])) {
	            time = arguments[0];
	            formats = undefined;
	          } else if (isCalendarSpec(arguments[0])) {
	            formats = arguments[0];
	            time = undefined;
	          }
	        }
	        // We want to compare the start of today, vs this.
	        // Getting start-of-today depends on whether we're local/utc/offset or not.
	        var now = time || createLocal(),
	          sod = cloneWithOffset(now, this).startOf('day'),
	          format = hooks.calendarFormat(this, sod) || 'sameElse',
	          output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
	        return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
	      }
	      function clone() {
	        return new Moment(this);
	      }
	      function isAfter(input, units) {
	        var localInput = isMoment(input) ? input : createLocal(input);
	        if (!(this.isValid() && localInput.isValid())) {
	          return false;
	        }
	        units = normalizeUnits(units) || 'millisecond';
	        if (units === 'millisecond') {
	          return this.valueOf() > localInput.valueOf();
	        } else {
	          return localInput.valueOf() < this.clone().startOf(units).valueOf();
	        }
	      }
	      function isBefore(input, units) {
	        var localInput = isMoment(input) ? input : createLocal(input);
	        if (!(this.isValid() && localInput.isValid())) {
	          return false;
	        }
	        units = normalizeUnits(units) || 'millisecond';
	        if (units === 'millisecond') {
	          return this.valueOf() < localInput.valueOf();
	        } else {
	          return this.clone().endOf(units).valueOf() < localInput.valueOf();
	        }
	      }
	      function isBetween(from, to, units, inclusivity) {
	        var localFrom = isMoment(from) ? from : createLocal(from),
	          localTo = isMoment(to) ? to : createLocal(to);
	        if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
	          return false;
	        }
	        inclusivity = inclusivity || '()';
	        return (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && (inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, units));
	      }
	      function isSame(input, units) {
	        var localInput = isMoment(input) ? input : createLocal(input),
	          inputMs;
	        if (!(this.isValid() && localInput.isValid())) {
	          return false;
	        }
	        units = normalizeUnits(units) || 'millisecond';
	        if (units === 'millisecond') {
	          return this.valueOf() === localInput.valueOf();
	        } else {
	          inputMs = localInput.valueOf();
	          return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
	        }
	      }
	      function isSameOrAfter(input, units) {
	        return this.isSame(input, units) || this.isAfter(input, units);
	      }
	      function isSameOrBefore(input, units) {
	        return this.isSame(input, units) || this.isBefore(input, units);
	      }
	      function diff(input, units, asFloat) {
	        var that, zoneDelta, output;
	        if (!this.isValid()) {
	          return NaN;
	        }
	        that = cloneWithOffset(input, this);
	        if (!that.isValid()) {
	          return NaN;
	        }
	        zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
	        units = normalizeUnits(units);
	        switch (units) {
	          case 'year':
	            output = monthDiff(this, that) / 12;
	            break;
	          case 'month':
	            output = monthDiff(this, that);
	            break;
	          case 'quarter':
	            output = monthDiff(this, that) / 3;
	            break;
	          case 'second':
	            output = (this - that) / 1e3;
	            break;
	          // 1000
	          case 'minute':
	            output = (this - that) / 6e4;
	            break;
	          // 1000 * 60
	          case 'hour':
	            output = (this - that) / 36e5;
	            break;
	          // 1000 * 60 * 60
	          case 'day':
	            output = (this - that - zoneDelta) / 864e5;
	            break;
	          // 1000 * 60 * 60 * 24, negate dst
	          case 'week':
	            output = (this - that - zoneDelta) / 6048e5;
	            break;
	          // 1000 * 60 * 60 * 24 * 7, negate dst
	          default:
	            output = this - that;
	        }
	        return asFloat ? output : absFloor(output);
	      }
	      function monthDiff(a, b) {
	        if (a.date() < b.date()) {
	          // end-of-month calculations work correct when the start month has more
	          // days than the end month.
	          return -monthDiff(b, a);
	        }
	        // difference in months
	        var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),
	          // b is in (anchor - 1 month, anchor + 1 month)
	          anchor = a.clone().add(wholeMonthDiff, 'months'),
	          anchor2,
	          adjust;
	        if (b - anchor < 0) {
	          anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
	          // linear across the month
	          adjust = (b - anchor) / (anchor - anchor2);
	        } else {
	          anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
	          // linear across the month
	          adjust = (b - anchor) / (anchor2 - anchor);
	        }

	        //check for negative zero, return zero if negative zero
	        return -(wholeMonthDiff + adjust) || 0;
	      }
	      hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
	      hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
	      function toString() {
	        return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
	      }
	      function toISOString(keepOffset) {
	        if (!this.isValid()) {
	          return null;
	        }
	        var utc = keepOffset !== true,
	          m = utc ? this.clone().utc() : this;
	        if (m.year() < 0 || m.year() > 9999) {
	          return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ');
	        }
	        if (isFunction(Date.prototype.toISOString)) {
	          // native implementation is ~50x faster, use it when we can
	          if (utc) {
	            return this.toDate().toISOString();
	          } else {
	            return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z'));
	          }
	        }
	        return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ');
	      }

	      /**
	       * Return a human readable representation of a moment that can
	       * also be evaluated to get a new moment which is the same
	       *
	       * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
	       */
	      function inspect() {
	        if (!this.isValid()) {
	          return 'moment.invalid(/* ' + this._i + ' */)';
	        }
	        var func = 'moment',
	          zone = '',
	          prefix,
	          year,
	          datetime,
	          suffix;
	        if (!this.isLocal()) {
	          func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
	          zone = 'Z';
	        }
	        prefix = '[' + func + '("]';
	        year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY';
	        datetime = '-MM-DD[T]HH:mm:ss.SSS';
	        suffix = zone + '[")]';
	        return this.format(prefix + year + datetime + suffix);
	      }
	      function format(inputString) {
	        if (!inputString) {
	          inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
	        }
	        var output = formatMoment(this, inputString);
	        return this.localeData().postformat(output);
	      }
	      function from(time, withoutSuffix) {
	        if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) {
	          return createDuration({
	            to: this,
	            from: time
	          }).locale(this.locale()).humanize(!withoutSuffix);
	        } else {
	          return this.localeData().invalidDate();
	        }
	      }
	      function fromNow(withoutSuffix) {
	        return this.from(createLocal(), withoutSuffix);
	      }
	      function to(time, withoutSuffix) {
	        if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) {
	          return createDuration({
	            from: this,
	            to: time
	          }).locale(this.locale()).humanize(!withoutSuffix);
	        } else {
	          return this.localeData().invalidDate();
	        }
	      }
	      function toNow(withoutSuffix) {
	        return this.to(createLocal(), withoutSuffix);
	      }

	      // If passed a locale key, it will set the locale for this
	      // instance.  Otherwise, it will return the locale configuration
	      // variables for this instance.
	      function locale(key) {
	        var newLocaleData;
	        if (key === undefined) {
	          return this._locale._abbr;
	        } else {
	          newLocaleData = getLocale(key);
	          if (newLocaleData != null) {
	            this._locale = newLocaleData;
	          }
	          return this;
	        }
	      }
	      var lang = deprecate('moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', function (key) {
	        if (key === undefined) {
	          return this.localeData();
	        } else {
	          return this.locale(key);
	        }
	      });
	      function localeData() {
	        return this._locale;
	      }
	      var MS_PER_SECOND = 1000,
	        MS_PER_MINUTE = 60 * MS_PER_SECOND,
	        MS_PER_HOUR = 60 * MS_PER_MINUTE,
	        MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;

	      // actual modulo - handles negative numbers (for dates before 1970):
	      function mod$1(dividend, divisor) {
	        return (dividend % divisor + divisor) % divisor;
	      }
	      function localStartOfDate(y, m, d) {
	        // the date constructor remaps years 0-99 to 1900-1999
	        if (y < 100 && y >= 0) {
	          // preserve leap years using a full 400 year cycle, then reset
	          return new Date(y + 400, m, d) - MS_PER_400_YEARS;
	        } else {
	          return new Date(y, m, d).valueOf();
	        }
	      }
	      function utcStartOfDate(y, m, d) {
	        // Date.UTC remaps years 0-99 to 1900-1999
	        if (y < 100 && y >= 0) {
	          // preserve leap years using a full 400 year cycle, then reset
	          return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
	        } else {
	          return Date.UTC(y, m, d);
	        }
	      }
	      function startOf(units) {
	        var time, startOfDate;
	        units = normalizeUnits(units);
	        if (units === undefined || units === 'millisecond' || !this.isValid()) {
	          return this;
	        }
	        startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
	        switch (units) {
	          case 'year':
	            time = startOfDate(this.year(), 0, 1);
	            break;
	          case 'quarter':
	            time = startOfDate(this.year(), this.month() - this.month() % 3, 1);
	            break;
	          case 'month':
	            time = startOfDate(this.year(), this.month(), 1);
	            break;
	          case 'week':
	            time = startOfDate(this.year(), this.month(), this.date() - this.weekday());
	            break;
	          case 'isoWeek':
	            time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1));
	            break;
	          case 'day':
	          case 'date':
	            time = startOfDate(this.year(), this.month(), this.date());
	            break;
	          case 'hour':
	            time = this._d.valueOf();
	            time -= mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR);
	            break;
	          case 'minute':
	            time = this._d.valueOf();
	            time -= mod$1(time, MS_PER_MINUTE);
	            break;
	          case 'second':
	            time = this._d.valueOf();
	            time -= mod$1(time, MS_PER_SECOND);
	            break;
	        }
	        this._d.setTime(time);
	        hooks.updateOffset(this, true);
	        return this;
	      }
	      function endOf(units) {
	        var time, startOfDate;
	        units = normalizeUnits(units);
	        if (units === undefined || units === 'millisecond' || !this.isValid()) {
	          return this;
	        }
	        startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
	        switch (units) {
	          case 'year':
	            time = startOfDate(this.year() + 1, 0, 1) - 1;
	            break;
	          case 'quarter':
	            time = startOfDate(this.year(), this.month() - this.month() % 3 + 3, 1) - 1;
	            break;
	          case 'month':
	            time = startOfDate(this.year(), this.month() + 1, 1) - 1;
	            break;
	          case 'week':
	            time = startOfDate(this.year(), this.month(), this.date() - this.weekday() + 7) - 1;
	            break;
	          case 'isoWeek':
	            time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1;
	            break;
	          case 'day':
	          case 'date':
	            time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
	            break;
	          case 'hour':
	            time = this._d.valueOf();
	            time += MS_PER_HOUR - mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR) - 1;
	            break;
	          case 'minute':
	            time = this._d.valueOf();
	            time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
	            break;
	          case 'second':
	            time = this._d.valueOf();
	            time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
	            break;
	        }
	        this._d.setTime(time);
	        hooks.updateOffset(this, true);
	        return this;
	      }
	      function valueOf() {
	        return this._d.valueOf() - (this._offset || 0) * 60000;
	      }
	      function unix() {
	        return Math.floor(this.valueOf() / 1000);
	      }
	      function toDate() {
	        return new Date(this.valueOf());
	      }
	      function toArray() {
	        var m = this;
	        return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
	      }
	      function toObject() {
	        var m = this;
	        return {
	          years: m.year(),
	          months: m.month(),
	          date: m.date(),
	          hours: m.hours(),
	          minutes: m.minutes(),
	          seconds: m.seconds(),
	          milliseconds: m.milliseconds()
	        };
	      }
	      function toJSON() {
	        // new Date(NaN).toJSON() === null
	        return this.isValid() ? this.toISOString() : null;
	      }
	      function isValid$2() {
	        return isValid(this);
	      }
	      function parsingFlags() {
	        return extend({}, getParsingFlags(this));
	      }
	      function invalidAt() {
	        return getParsingFlags(this).overflow;
	      }
	      function creationData() {
	        return {
	          input: this._i,
	          format: this._f,
	          locale: this._locale,
	          isUTC: this._isUTC,
	          strict: this._strict
	        };
	      }
	      addFormatToken('N', 0, 0, 'eraAbbr');
	      addFormatToken('NN', 0, 0, 'eraAbbr');
	      addFormatToken('NNN', 0, 0, 'eraAbbr');
	      addFormatToken('NNNN', 0, 0, 'eraName');
	      addFormatToken('NNNNN', 0, 0, 'eraNarrow');
	      addFormatToken('y', ['y', 1], 'yo', 'eraYear');
	      addFormatToken('y', ['yy', 2], 0, 'eraYear');
	      addFormatToken('y', ['yyy', 3], 0, 'eraYear');
	      addFormatToken('y', ['yyyy', 4], 0, 'eraYear');
	      addRegexToken('N', matchEraAbbr);
	      addRegexToken('NN', matchEraAbbr);
	      addRegexToken('NNN', matchEraAbbr);
	      addRegexToken('NNNN', matchEraName);
	      addRegexToken('NNNNN', matchEraNarrow);
	      addParseToken(['N', 'NN', 'NNN', 'NNNN', 'NNNNN'], function (input, array, config, token) {
	        var era = config._locale.erasParse(input, token, config._strict);
	        if (era) {
	          getParsingFlags(config).era = era;
	        } else {
	          getParsingFlags(config).invalidEra = input;
	        }
	      });
	      addRegexToken('y', matchUnsigned);
	      addRegexToken('yy', matchUnsigned);
	      addRegexToken('yyy', matchUnsigned);
	      addRegexToken('yyyy', matchUnsigned);
	      addRegexToken('yo', matchEraYearOrdinal);
	      addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR);
	      addParseToken(['yo'], function (input, array, config, token) {
	        var match;
	        if (config._locale._eraYearOrdinalRegex) {
	          match = input.match(config._locale._eraYearOrdinalRegex);
	        }
	        if (config._locale.eraYearOrdinalParse) {
	          array[YEAR] = config._locale.eraYearOrdinalParse(input, match);
	        } else {
	          array[YEAR] = parseInt(input, 10);
	        }
	      });
	      function localeEras(m, format) {
	        var i,
	          l,
	          date,
	          eras = this._eras || getLocale('en')._eras;
	        for (i = 0, l = eras.length; i < l; ++i) {
	          switch (typeof eras[i].since) {
	            case 'string':
	              // truncate time
	              date = hooks(eras[i].since).startOf('day');
	              eras[i].since = date.valueOf();
	              break;
	          }
	          switch (typeof eras[i].until) {
	            case 'undefined':
	              eras[i].until = +Infinity;
	              break;
	            case 'string':
	              // truncate time
	              date = hooks(eras[i].until).startOf('day').valueOf();
	              eras[i].until = date.valueOf();
	              break;
	          }
	        }
	        return eras;
	      }
	      function localeErasParse(eraName, format, strict) {
	        var i,
	          l,
	          eras = this.eras(),
	          name,
	          abbr,
	          narrow;
	        eraName = eraName.toUpperCase();
	        for (i = 0, l = eras.length; i < l; ++i) {
	          name = eras[i].name.toUpperCase();
	          abbr = eras[i].abbr.toUpperCase();
	          narrow = eras[i].narrow.toUpperCase();
	          if (strict) {
	            switch (format) {
	              case 'N':
	              case 'NN':
	              case 'NNN':
	                if (abbr === eraName) {
	                  return eras[i];
	                }
	                break;
	              case 'NNNN':
	                if (name === eraName) {
	                  return eras[i];
	                }
	                break;
	              case 'NNNNN':
	                if (narrow === eraName) {
	                  return eras[i];
	                }
	                break;
	            }
	          } else if ([name, abbr, narrow].indexOf(eraName) >= 0) {
	            return eras[i];
	          }
	        }
	      }
	      function localeErasConvertYear(era, year) {
	        var dir = era.since <= era.until ? 1 : -1;
	        if (year === undefined) {
	          return hooks(era.since).year();
	        } else {
	          return hooks(era.since).year() + (year - era.offset) * dir;
	        }
	      }
	      function getEraName() {
	        var i,
	          l,
	          val,
	          eras = this.localeData().eras();
	        for (i = 0, l = eras.length; i < l; ++i) {
	          // truncate time
	          val = this.clone().startOf('day').valueOf();
	          if (eras[i].since <= val && val <= eras[i].until) {
	            return eras[i].name;
	          }
	          if (eras[i].until <= val && val <= eras[i].since) {
	            return eras[i].name;
	          }
	        }
	        return '';
	      }
	      function getEraNarrow() {
	        var i,
	          l,
	          val,
	          eras = this.localeData().eras();
	        for (i = 0, l = eras.length; i < l; ++i) {
	          // truncate time
	          val = this.clone().startOf('day').valueOf();
	          if (eras[i].since <= val && val <= eras[i].until) {
	            return eras[i].narrow;
	          }
	          if (eras[i].until <= val && val <= eras[i].since) {
	            return eras[i].narrow;
	          }
	        }
	        return '';
	      }
	      function getEraAbbr() {
	        var i,
	          l,
	          val,
	          eras = this.localeData().eras();
	        for (i = 0, l = eras.length; i < l; ++i) {
	          // truncate time
	          val = this.clone().startOf('day').valueOf();
	          if (eras[i].since <= val && val <= eras[i].until) {
	            return eras[i].abbr;
	          }
	          if (eras[i].until <= val && val <= eras[i].since) {
	            return eras[i].abbr;
	          }
	        }
	        return '';
	      }
	      function getEraYear() {
	        var i,
	          l,
	          dir,
	          val,
	          eras = this.localeData().eras();
	        for (i = 0, l = eras.length; i < l; ++i) {
	          dir = eras[i].since <= eras[i].until ? 1 : -1;

	          // truncate time
	          val = this.clone().startOf('day').valueOf();
	          if (eras[i].since <= val && val <= eras[i].until || eras[i].until <= val && val <= eras[i].since) {
	            return (this.year() - hooks(eras[i].since).year()) * dir + eras[i].offset;
	          }
	        }
	        return this.year();
	      }
	      function erasNameRegex(isStrict) {
	        if (!hasOwnProp(this, '_erasNameRegex')) {
	          computeErasParse.call(this);
	        }
	        return isStrict ? this._erasNameRegex : this._erasRegex;
	      }
	      function erasAbbrRegex(isStrict) {
	        if (!hasOwnProp(this, '_erasAbbrRegex')) {
	          computeErasParse.call(this);
	        }
	        return isStrict ? this._erasAbbrRegex : this._erasRegex;
	      }
	      function erasNarrowRegex(isStrict) {
	        if (!hasOwnProp(this, '_erasNarrowRegex')) {
	          computeErasParse.call(this);
	        }
	        return isStrict ? this._erasNarrowRegex : this._erasRegex;
	      }
	      function matchEraAbbr(isStrict, locale) {
	        return locale.erasAbbrRegex(isStrict);
	      }
	      function matchEraName(isStrict, locale) {
	        return locale.erasNameRegex(isStrict);
	      }
	      function matchEraNarrow(isStrict, locale) {
	        return locale.erasNarrowRegex(isStrict);
	      }
	      function matchEraYearOrdinal(isStrict, locale) {
	        return locale._eraYearOrdinalRegex || matchUnsigned;
	      }
	      function computeErasParse() {
	        var abbrPieces = [],
	          namePieces = [],
	          narrowPieces = [],
	          mixedPieces = [],
	          i,
	          l,
	          erasName,
	          erasAbbr,
	          erasNarrow,
	          eras = this.eras();
	        for (i = 0, l = eras.length; i < l; ++i) {
	          erasName = regexEscape(eras[i].name);
	          erasAbbr = regexEscape(eras[i].abbr);
	          erasNarrow = regexEscape(eras[i].narrow);
	          namePieces.push(erasName);
	          abbrPieces.push(erasAbbr);
	          narrowPieces.push(erasNarrow);
	          mixedPieces.push(erasName);
	          mixedPieces.push(erasAbbr);
	          mixedPieces.push(erasNarrow);
	        }
	        this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
	        this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i');
	        this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i');
	        this._erasNarrowRegex = new RegExp('^(' + narrowPieces.join('|') + ')', 'i');
	      }

	      // FORMATTING

	      addFormatToken(0, ['gg', 2], 0, function () {
	        return this.weekYear() % 100;
	      });
	      addFormatToken(0, ['GG', 2], 0, function () {
	        return this.isoWeekYear() % 100;
	      });
	      function addWeekYearFormatToken(token, getter) {
	        addFormatToken(0, [token, token.length], 0, getter);
	      }
	      addWeekYearFormatToken('gggg', 'weekYear');
	      addWeekYearFormatToken('ggggg', 'weekYear');
	      addWeekYearFormatToken('GGGG', 'isoWeekYear');
	      addWeekYearFormatToken('GGGGG', 'isoWeekYear');

	      // ALIASES

	      // PARSING

	      addRegexToken('G', matchSigned);
	      addRegexToken('g', matchSigned);
	      addRegexToken('GG', match1to2, match2);
	      addRegexToken('gg', match1to2, match2);
	      addRegexToken('GGGG', match1to4, match4);
	      addRegexToken('gggg', match1to4, match4);
	      addRegexToken('GGGGG', match1to6, match6);
	      addRegexToken('ggggg', match1to6, match6);
	      addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
	        week[token.substr(0, 2)] = toInt(input);
	      });
	      addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
	        week[token] = hooks.parseTwoDigitYear(input);
	      });

	      // MOMENTS

	      function getSetWeekYear(input) {
	        return getSetWeekYearHelper.call(this, input, this.week(), this.weekday() + this.localeData()._week.dow, this.localeData()._week.dow, this.localeData()._week.doy);
	      }
	      function getSetISOWeekYear(input) {
	        return getSetWeekYearHelper.call(this, input, this.isoWeek(), this.isoWeekday(), 1, 4);
	      }
	      function getISOWeeksInYear() {
	        return weeksInYear(this.year(), 1, 4);
	      }
	      function getISOWeeksInISOWeekYear() {
	        return weeksInYear(this.isoWeekYear(), 1, 4);
	      }
	      function getWeeksInYear() {
	        var weekInfo = this.localeData()._week;
	        return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
	      }
	      function getWeeksInWeekYear() {
	        var weekInfo = this.localeData()._week;
	        return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy);
	      }
	      function getSetWeekYearHelper(input, week, weekday, dow, doy) {
	        var weeksTarget;
	        if (input == null) {
	          return weekOfYear(this, dow, doy).year;
	        } else {
	          weeksTarget = weeksInYear(input, dow, doy);
	          if (week > weeksTarget) {
	            week = weeksTarget;
	          }
	          return setWeekAll.call(this, input, week, weekday, dow, doy);
	        }
	      }
	      function setWeekAll(weekYear, week, weekday, dow, doy) {
	        var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
	          date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
	        this.year(date.getUTCFullYear());
	        this.month(date.getUTCMonth());
	        this.date(date.getUTCDate());
	        return this;
	      }

	      // FORMATTING

	      addFormatToken('Q', 0, 'Qo', 'quarter');

	      // PARSING

	      addRegexToken('Q', match1);
	      addParseToken('Q', function (input, array) {
	        array[MONTH] = (toInt(input) - 1) * 3;
	      });

	      // MOMENTS

	      function getSetQuarter(input) {
	        return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
	      }

	      // FORMATTING

	      addFormatToken('D', ['DD', 2], 'Do', 'date');

	      // PARSING

	      addRegexToken('D', match1to2, match1to2NoLeadingZero);
	      addRegexToken('DD', match1to2, match2);
	      addRegexToken('Do', function (isStrict, locale) {
	        // TODO: Remove "ordinalParse" fallback in next major release.
	        return isStrict ? locale._dayOfMonthOrdinalParse || locale._ordinalParse : locale._dayOfMonthOrdinalParseLenient;
	      });
	      addParseToken(['D', 'DD'], DATE);
	      addParseToken('Do', function (input, array) {
	        array[DATE] = toInt(input.match(match1to2)[0]);
	      });

	      // MOMENTS

	      var getSetDayOfMonth = makeGetSet('Date', true);

	      // FORMATTING

	      addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');

	      // PARSING

	      addRegexToken('DDD', match1to3);
	      addRegexToken('DDDD', match3);
	      addParseToken(['DDD', 'DDDD'], function (input, array, config) {
	        config._dayOfYear = toInt(input);
	      });

	      // HELPERS

	      // MOMENTS

	      function getSetDayOfYear(input) {
	        var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
	        return input == null ? dayOfYear : this.add(input - dayOfYear, 'd');
	      }

	      // FORMATTING

	      addFormatToken('m', ['mm', 2], 0, 'minute');

	      // PARSING

	      addRegexToken('m', match1to2, match1to2HasZero);
	      addRegexToken('mm', match1to2, match2);
	      addParseToken(['m', 'mm'], MINUTE);

	      // MOMENTS

	      var getSetMinute = makeGetSet('Minutes', false);

	      // FORMATTING

	      addFormatToken('s', ['ss', 2], 0, 'second');

	      // PARSING

	      addRegexToken('s', match1to2, match1to2HasZero);
	      addRegexToken('ss', match1to2, match2);
	      addParseToken(['s', 'ss'], SECOND);

	      // MOMENTS

	      var getSetSecond = makeGetSet('Seconds', false);

	      // FORMATTING

	      addFormatToken('S', 0, 0, function () {
	        return ~~(this.millisecond() / 100);
	      });
	      addFormatToken(0, ['SS', 2], 0, function () {
	        return ~~(this.millisecond() / 10);
	      });
	      addFormatToken(0, ['SSS', 3], 0, 'millisecond');
	      addFormatToken(0, ['SSSS', 4], 0, function () {
	        return this.millisecond() * 10;
	      });
	      addFormatToken(0, ['SSSSS', 5], 0, function () {
	        return this.millisecond() * 100;
	      });
	      addFormatToken(0, ['SSSSSS', 6], 0, function () {
	        return this.millisecond() * 1000;
	      });
	      addFormatToken(0, ['SSSSSSS', 7], 0, function () {
	        return this.millisecond() * 10000;
	      });
	      addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
	        return this.millisecond() * 100000;
	      });
	      addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
	        return this.millisecond() * 1000000;
	      });

	      // PARSING

	      addRegexToken('S', match1to3, match1);
	      addRegexToken('SS', match1to3, match2);
	      addRegexToken('SSS', match1to3, match3);
	      var token, getSetMillisecond;
	      for (token = 'SSSS'; token.length <= 9; token += 'S') {
	        addRegexToken(token, matchUnsigned);
	      }
	      function parseMs(input, array) {
	        array[MILLISECOND] = toInt(('0.' + input) * 1000);
	      }
	      for (token = 'S'; token.length <= 9; token += 'S') {
	        addParseToken(token, parseMs);
	      }
	      getSetMillisecond = makeGetSet('Milliseconds', false);

	      // FORMATTING

	      addFormatToken('z', 0, 0, 'zoneAbbr');
	      addFormatToken('zz', 0, 0, 'zoneName');

	      // MOMENTS

	      function getZoneAbbr() {
	        return this._isUTC ? 'UTC' : '';
	      }
	      function getZoneName() {
	        return this._isUTC ? 'Coordinated Universal Time' : '';
	      }
	      var proto = Moment.prototype;
	      proto.add = add;
	      proto.calendar = calendar$1;
	      proto.clone = clone;
	      proto.diff = diff;
	      proto.endOf = endOf;
	      proto.format = format;
	      proto.from = from;
	      proto.fromNow = fromNow;
	      proto.to = to;
	      proto.toNow = toNow;
	      proto.get = stringGet;
	      proto.invalidAt = invalidAt;
	      proto.isAfter = isAfter;
	      proto.isBefore = isBefore;
	      proto.isBetween = isBetween;
	      proto.isSame = isSame;
	      proto.isSameOrAfter = isSameOrAfter;
	      proto.isSameOrBefore = isSameOrBefore;
	      proto.isValid = isValid$2;
	      proto.lang = lang;
	      proto.locale = locale;
	      proto.localeData = localeData;
	      proto.max = prototypeMax;
	      proto.min = prototypeMin;
	      proto.parsingFlags = parsingFlags;
	      proto.set = stringSet;
	      proto.startOf = startOf;
	      proto.subtract = subtract;
	      proto.toArray = toArray;
	      proto.toObject = toObject;
	      proto.toDate = toDate;
	      proto.toISOString = toISOString;
	      proto.inspect = inspect;
	      if (typeof Symbol !== 'undefined' && Symbol.for != null) {
	        proto[Symbol.for('nodejs.util.inspect.custom')] = function () {
	          return 'Moment<' + this.format() + '>';
	        };
	      }
	      proto.toJSON = toJSON;
	      proto.toString = toString;
	      proto.unix = unix;
	      proto.valueOf = valueOf;
	      proto.creationData = creationData;
	      proto.eraName = getEraName;
	      proto.eraNarrow = getEraNarrow;
	      proto.eraAbbr = getEraAbbr;
	      proto.eraYear = getEraYear;
	      proto.year = getSetYear;
	      proto.isLeapYear = getIsLeapYear;
	      proto.weekYear = getSetWeekYear;
	      proto.isoWeekYear = getSetISOWeekYear;
	      proto.quarter = proto.quarters = getSetQuarter;
	      proto.month = getSetMonth;
	      proto.daysInMonth = getDaysInMonth;
	      proto.week = proto.weeks = getSetWeek;
	      proto.isoWeek = proto.isoWeeks = getSetISOWeek;
	      proto.weeksInYear = getWeeksInYear;
	      proto.weeksInWeekYear = getWeeksInWeekYear;
	      proto.isoWeeksInYear = getISOWeeksInYear;
	      proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear;
	      proto.date = getSetDayOfMonth;
	      proto.day = proto.days = getSetDayOfWeek;
	      proto.weekday = getSetLocaleDayOfWeek;
	      proto.isoWeekday = getSetISODayOfWeek;
	      proto.dayOfYear = getSetDayOfYear;
	      proto.hour = proto.hours = getSetHour;
	      proto.minute = proto.minutes = getSetMinute;
	      proto.second = proto.seconds = getSetSecond;
	      proto.millisecond = proto.milliseconds = getSetMillisecond;
	      proto.utcOffset = getSetOffset;
	      proto.utc = setOffsetToUTC;
	      proto.local = setOffsetToLocal;
	      proto.parseZone = setOffsetToParsedOffset;
	      proto.hasAlignedHourOffset = hasAlignedHourOffset;
	      proto.isDST = isDaylightSavingTime;
	      proto.isLocal = isLocal;
	      proto.isUtcOffset = isUtcOffset;
	      proto.isUtc = isUtc;
	      proto.isUTC = isUtc;
	      proto.zoneAbbr = getZoneAbbr;
	      proto.zoneName = getZoneName;
	      proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
	      proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
	      proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
	      proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
	      proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);
	      function createUnix(input) {
	        return createLocal(input * 1000);
	      }
	      function createInZone() {
	        return createLocal.apply(null, arguments).parseZone();
	      }
	      function preParsePostFormat(string) {
	        return string;
	      }
	      var proto$1 = Locale.prototype;
	      proto$1.calendar = calendar;
	      proto$1.longDateFormat = longDateFormat;
	      proto$1.invalidDate = invalidDate;
	      proto$1.ordinal = ordinal;
	      proto$1.preparse = preParsePostFormat;
	      proto$1.postformat = preParsePostFormat;
	      proto$1.relativeTime = relativeTime;
	      proto$1.pastFuture = pastFuture;
	      proto$1.set = set;
	      proto$1.eras = localeEras;
	      proto$1.erasParse = localeErasParse;
	      proto$1.erasConvertYear = localeErasConvertYear;
	      proto$1.erasAbbrRegex = erasAbbrRegex;
	      proto$1.erasNameRegex = erasNameRegex;
	      proto$1.erasNarrowRegex = erasNarrowRegex;
	      proto$1.months = localeMonths;
	      proto$1.monthsShort = localeMonthsShort;
	      proto$1.monthsParse = localeMonthsParse;
	      proto$1.monthsRegex = monthsRegex;
	      proto$1.monthsShortRegex = monthsShortRegex;
	      proto$1.week = localeWeek;
	      proto$1.firstDayOfYear = localeFirstDayOfYear;
	      proto$1.firstDayOfWeek = localeFirstDayOfWeek;
	      proto$1.weekdays = localeWeekdays;
	      proto$1.weekdaysMin = localeWeekdaysMin;
	      proto$1.weekdaysShort = localeWeekdaysShort;
	      proto$1.weekdaysParse = localeWeekdaysParse;
	      proto$1.weekdaysRegex = weekdaysRegex;
	      proto$1.weekdaysShortRegex = weekdaysShortRegex;
	      proto$1.weekdaysMinRegex = weekdaysMinRegex;
	      proto$1.isPM = localeIsPM;
	      proto$1.meridiem = localeMeridiem;
	      function get$1(format, index, field, setter) {
	        var locale = getLocale(),
	          utc = createUTC().set(setter, index);
	        return locale[field](utc, format);
	      }
	      function listMonthsImpl(format, index, field) {
	        if (isNumber(format)) {
	          index = format;
	          format = undefined;
	        }
	        format = format || '';
	        if (index != null) {
	          return get$1(format, index, field, 'month');
	        }
	        var i,
	          out = [];
	        for (i = 0; i < 12; i++) {
	          out[i] = get$1(format, i, field, 'month');
	        }
	        return out;
	      }

	      // ()
	      // (5)
	      // (fmt, 5)
	      // (fmt)
	      // (true)
	      // (true, 5)
	      // (true, fmt, 5)
	      // (true, fmt)
	      function listWeekdaysImpl(localeSorted, format, index, field) {
	        if (typeof localeSorted === 'boolean') {
	          if (isNumber(format)) {
	            index = format;
	            format = undefined;
	          }
	          format = format || '';
	        } else {
	          format = localeSorted;
	          index = format;
	          localeSorted = false;
	          if (isNumber(format)) {
	            index = format;
	            format = undefined;
	          }
	          format = format || '';
	        }
	        var locale = getLocale(),
	          shift = localeSorted ? locale._week.dow : 0,
	          i,
	          out = [];
	        if (index != null) {
	          return get$1(format, (index + shift) % 7, field, 'day');
	        }
	        for (i = 0; i < 7; i++) {
	          out[i] = get$1(format, (i + shift) % 7, field, 'day');
	        }
	        return out;
	      }
	      function listMonths(format, index) {
	        return listMonthsImpl(format, index, 'months');
	      }
	      function listMonthsShort(format, index) {
	        return listMonthsImpl(format, index, 'monthsShort');
	      }
	      function listWeekdays(localeSorted, format, index) {
	        return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
	      }
	      function listWeekdaysShort(localeSorted, format, index) {
	        return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
	      }
	      function listWeekdaysMin(localeSorted, format, index) {
	        return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
	      }
	      getSetGlobalLocale('en', {
	        eras: [{
	          since: '0001-01-01',
	          until: +Infinity,
	          offset: 1,
	          name: 'Anno Domini',
	          narrow: 'AD',
	          abbr: 'AD'
	        }, {
	          since: '0000-12-31',
	          until: -Infinity,
	          offset: 1,
	          name: 'Before Christ',
	          narrow: 'BC',
	          abbr: 'BC'
	        }],
	        dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
	        ordinal: function (number) {
	          var b = number % 10,
	            output = toInt(number % 100 / 10) === 1 ? 'th' : b === 1 ? 'st' : b === 2 ? 'nd' : b === 3 ? 'rd' : 'th';
	          return number + output;
	        }
	      });

	      // Side effect imports

	      hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
	      hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);
	      var mathAbs = Math.abs;
	      function abs() {
	        var data = this._data;
	        this._milliseconds = mathAbs(this._milliseconds);
	        this._days = mathAbs(this._days);
	        this._months = mathAbs(this._months);
	        data.milliseconds = mathAbs(data.milliseconds);
	        data.seconds = mathAbs(data.seconds);
	        data.minutes = mathAbs(data.minutes);
	        data.hours = mathAbs(data.hours);
	        data.months = mathAbs(data.months);
	        data.years = mathAbs(data.years);
	        return this;
	      }
	      function addSubtract$1(duration, input, value, direction) {
	        var other = createDuration(input, value);
	        duration._milliseconds += direction * other._milliseconds;
	        duration._days += direction * other._days;
	        duration._months += direction * other._months;
	        return duration._bubble();
	      }

	      // supports only 2.0-style add(1, 's') or add(duration)
	      function add$1(input, value) {
	        return addSubtract$1(this, input, value, 1);
	      }

	      // supports only 2.0-style subtract(1, 's') or subtract(duration)
	      function subtract$1(input, value) {
	        return addSubtract$1(this, input, value, -1);
	      }
	      function absCeil(number) {
	        if (number < 0) {
	          return Math.floor(number);
	        } else {
	          return Math.ceil(number);
	        }
	      }
	      function bubble() {
	        var milliseconds = this._milliseconds,
	          days = this._days,
	          months = this._months,
	          data = this._data,
	          seconds,
	          minutes,
	          hours,
	          years,
	          monthsFromDays;

	        // if we have a mix of positive and negative values, bubble down first
	        // check: https://github.com/moment/moment/issues/2166
	        if (!(milliseconds >= 0 && days >= 0 && months >= 0 || milliseconds <= 0 && days <= 0 && months <= 0)) {
	          milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
	          days = 0;
	          months = 0;
	        }

	        // The following code bubbles up values, see the tests for
	        // examples of what that means.
	        data.milliseconds = milliseconds % 1000;
	        seconds = absFloor(milliseconds / 1000);
	        data.seconds = seconds % 60;
	        minutes = absFloor(seconds / 60);
	        data.minutes = minutes % 60;
	        hours = absFloor(minutes / 60);
	        data.hours = hours % 24;
	        days += absFloor(hours / 24);

	        // convert days to months
	        monthsFromDays = absFloor(daysToMonths(days));
	        months += monthsFromDays;
	        days -= absCeil(monthsToDays(monthsFromDays));

	        // 12 months -> 1 year
	        years = absFloor(months / 12);
	        months %= 12;
	        data.days = days;
	        data.months = months;
	        data.years = years;
	        return this;
	      }
	      function daysToMonths(days) {
	        // 400 years have 146097 days (taking into account leap year rules)
	        // 400 years have 12 months === 4800
	        return days * 4800 / 146097;
	      }
	      function monthsToDays(months) {
	        // the reverse of daysToMonths
	        return months * 146097 / 4800;
	      }
	      function as(units) {
	        if (!this.isValid()) {
	          return NaN;
	        }
	        var days,
	          months,
	          milliseconds = this._milliseconds;
	        units = normalizeUnits(units);
	        if (units === 'month' || units === 'quarter' || units === 'year') {
	          days = this._days + milliseconds / 864e5;
	          months = this._months + daysToMonths(days);
	          switch (units) {
	            case 'month':
	              return months;
	            case 'quarter':
	              return months / 3;
	            case 'year':
	              return months / 12;
	          }
	        } else {
	          // handle milliseconds separately because of floating point math errors (issue #1867)
	          days = this._days + Math.round(monthsToDays(this._months));
	          switch (units) {
	            case 'week':
	              return days / 7 + milliseconds / 6048e5;
	            case 'day':
	              return days + milliseconds / 864e5;
	            case 'hour':
	              return days * 24 + milliseconds / 36e5;
	            case 'minute':
	              return days * 1440 + milliseconds / 6e4;
	            case 'second':
	              return days * 86400 + milliseconds / 1000;
	            // Math.floor prevents floating point math errors here
	            case 'millisecond':
	              return Math.floor(days * 864e5) + milliseconds;
	            default:
	              throw new Error('Unknown unit ' + units);
	          }
	        }
	      }
	      function makeAs(alias) {
	        return function () {
	          return this.as(alias);
	        };
	      }
	      var asMilliseconds = makeAs('ms'),
	        asSeconds = makeAs('s'),
	        asMinutes = makeAs('m'),
	        asHours = makeAs('h'),
	        asDays = makeAs('d'),
	        asWeeks = makeAs('w'),
	        asMonths = makeAs('M'),
	        asQuarters = makeAs('Q'),
	        asYears = makeAs('y'),
	        valueOf$1 = asMilliseconds;
	      function clone$1() {
	        return createDuration(this);
	      }
	      function get$2(units) {
	        units = normalizeUnits(units);
	        return this.isValid() ? this[units + 's']() : NaN;
	      }
	      function makeGetter(name) {
	        return function () {
	          return this.isValid() ? this._data[name] : NaN;
	        };
	      }
	      var milliseconds = makeGetter('milliseconds'),
	        seconds = makeGetter('seconds'),
	        minutes = makeGetter('minutes'),
	        hours = makeGetter('hours'),
	        days = makeGetter('days'),
	        months = makeGetter('months'),
	        years = makeGetter('years');
	      function weeks() {
	        return absFloor(this.days() / 7);
	      }
	      var round = Math.round,
	        thresholds = {
	          ss: 44,
	          // a few seconds to seconds
	          s: 45,
	          // seconds to minute
	          m: 45,
	          // minutes to hour
	          h: 22,
	          // hours to day
	          d: 26,
	          // days to month/week
	          w: null,
	          // weeks to month
	          M: 11 // months to year
	        };

	      // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
	      function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
	        return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
	      }
	      function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) {
	        var duration = createDuration(posNegDuration).abs(),
	          seconds = round(duration.as('s')),
	          minutes = round(duration.as('m')),
	          hours = round(duration.as('h')),
	          days = round(duration.as('d')),
	          months = round(duration.as('M')),
	          weeks = round(duration.as('w')),
	          years = round(duration.as('y')),
	          a = seconds <= thresholds.ss && ['s', seconds] || seconds < thresholds.s && ['ss', seconds] || minutes <= 1 && ['m'] || minutes < thresholds.m && ['mm', minutes] || hours <= 1 && ['h'] || hours < thresholds.h && ['hh', hours] || days <= 1 && ['d'] || days < thresholds.d && ['dd', days];
	        if (thresholds.w != null) {
	          a = a || weeks <= 1 && ['w'] || weeks < thresholds.w && ['ww', weeks];
	        }
	        a = a || months <= 1 && ['M'] || months < thresholds.M && ['MM', months] || years <= 1 && ['y'] || ['yy', years];
	        a[2] = withoutSuffix;
	        a[3] = +posNegDuration > 0;
	        a[4] = locale;
	        return substituteTimeAgo.apply(null, a);
	      }

	      // This function allows you to set the rounding function for relative time strings
	      function getSetRelativeTimeRounding(roundingFunction) {
	        if (roundingFunction === undefined) {
	          return round;
	        }
	        if (typeof roundingFunction === 'function') {
	          round = roundingFunction;
	          return true;
	        }
	        return false;
	      }

	      // This function allows you to set a threshold for relative time strings
	      function getSetRelativeTimeThreshold(threshold, limit) {
	        if (thresholds[threshold] === undefined) {
	          return false;
	        }
	        if (limit === undefined) {
	          return thresholds[threshold];
	        }
	        thresholds[threshold] = limit;
	        if (threshold === 's') {
	          thresholds.ss = limit - 1;
	        }
	        return true;
	      }
	      function humanize(argWithSuffix, argThresholds) {
	        if (!this.isValid()) {
	          return this.localeData().invalidDate();
	        }
	        var withSuffix = false,
	          th = thresholds,
	          locale,
	          output;
	        if (typeof argWithSuffix === 'object') {
	          argThresholds = argWithSuffix;
	          argWithSuffix = false;
	        }
	        if (typeof argWithSuffix === 'boolean') {
	          withSuffix = argWithSuffix;
	        }
	        if (typeof argThresholds === 'object') {
	          th = Object.assign({}, thresholds, argThresholds);
	          if (argThresholds.s != null && argThresholds.ss == null) {
	            th.ss = argThresholds.s - 1;
	          }
	        }
	        locale = this.localeData();
	        output = relativeTime$1(this, !withSuffix, th, locale);
	        if (withSuffix) {
	          output = locale.pastFuture(+this, output);
	        }
	        return locale.postformat(output);
	      }
	      var abs$1 = Math.abs;
	      function sign(x) {
	        return (x > 0) - (x < 0) || +x;
	      }
	      function toISOString$1() {
	        // for ISO strings we do not use the normal bubbling rules:
	        //  * milliseconds bubble up until they become hours
	        //  * days do not bubble at all
	        //  * months bubble up until they become years
	        // This is because there is no context-free conversion between hours and days
	        // (think of clock changes)
	        // and also not between days and months (28-31 days per month)
	        if (!this.isValid()) {
	          return this.localeData().invalidDate();
	        }
	        var seconds = abs$1(this._milliseconds) / 1000,
	          days = abs$1(this._days),
	          months = abs$1(this._months),
	          minutes,
	          hours,
	          years,
	          s,
	          total = this.asSeconds(),
	          totalSign,
	          ymSign,
	          daysSign,
	          hmsSign;
	        if (!total) {
	          // this is the same as C#'s (Noda) and python (isodate)...
	          // but not other JS (goog.date)
	          return 'P0D';
	        }

	        // 3600 seconds -> 60 minutes -> 1 hour
	        minutes = absFloor(seconds / 60);
	        hours = absFloor(minutes / 60);
	        seconds %= 60;
	        minutes %= 60;

	        // 12 months -> 1 year
	        years = absFloor(months / 12);
	        months %= 12;

	        // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
	        s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
	        totalSign = total < 0 ? '-' : '';
	        ymSign = sign(this._months) !== sign(total) ? '-' : '';
	        daysSign = sign(this._days) !== sign(total) ? '-' : '';
	        hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
	        return totalSign + 'P' + (years ? ymSign + years + 'Y' : '') + (months ? ymSign + months + 'M' : '') + (days ? daysSign + days + 'D' : '') + (hours || minutes || seconds ? 'T' : '') + (hours ? hmsSign + hours + 'H' : '') + (minutes ? hmsSign + minutes + 'M' : '') + (seconds ? hmsSign + s + 'S' : '');
	      }
	      var proto$2 = Duration.prototype;
	      proto$2.isValid = isValid$1;
	      proto$2.abs = abs;
	      proto$2.add = add$1;
	      proto$2.subtract = subtract$1;
	      proto$2.as = as;
	      proto$2.asMilliseconds = asMilliseconds;
	      proto$2.asSeconds = asSeconds;
	      proto$2.asMinutes = asMinutes;
	      proto$2.asHours = asHours;
	      proto$2.asDays = asDays;
	      proto$2.asWeeks = asWeeks;
	      proto$2.asMonths = asMonths;
	      proto$2.asQuarters = asQuarters;
	      proto$2.asYears = asYears;
	      proto$2.valueOf = valueOf$1;
	      proto$2._bubble = bubble;
	      proto$2.clone = clone$1;
	      proto$2.get = get$2;
	      proto$2.milliseconds = milliseconds;
	      proto$2.seconds = seconds;
	      proto$2.minutes = minutes;
	      proto$2.hours = hours;
	      proto$2.days = days;
	      proto$2.weeks = weeks;
	      proto$2.months = months;
	      proto$2.years = years;
	      proto$2.humanize = humanize;
	      proto$2.toISOString = toISOString$1;
	      proto$2.toString = toISOString$1;
	      proto$2.toJSON = toISOString$1;
	      proto$2.locale = locale;
	      proto$2.localeData = localeData;
	      proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
	      proto$2.lang = lang;

	      // FORMATTING

	      addFormatToken('X', 0, 0, 'unix');
	      addFormatToken('x', 0, 0, 'valueOf');

	      // PARSING

	      addRegexToken('x', matchSigned);
	      addRegexToken('X', matchTimestamp);
	      addParseToken('X', function (input, array, config) {
	        config._d = new Date(parseFloat(input) * 1000);
	      });
	      addParseToken('x', function (input, array, config) {
	        config._d = new Date(toInt(input));
	      });

	      //! moment.js

	      hooks.version = '2.30.1';
	      setHookCallback(createLocal);
	      hooks.fn = proto;
	      hooks.min = min;
	      hooks.max = max;
	      hooks.now = now;
	      hooks.utc = createUTC;
	      hooks.unix = createUnix;
	      hooks.months = listMonths;
	      hooks.isDate = isDate;
	      hooks.locale = getSetGlobalLocale;
	      hooks.invalid = createInvalid;
	      hooks.duration = createDuration;
	      hooks.isMoment = isMoment;
	      hooks.weekdays = listWeekdays;
	      hooks.parseZone = createInZone;
	      hooks.localeData = getLocale;
	      hooks.isDuration = isDuration;
	      hooks.monthsShort = listMonthsShort;
	      hooks.weekdaysMin = listWeekdaysMin;
	      hooks.defineLocale = defineLocale;
	      hooks.updateLocale = updateLocale;
	      hooks.locales = listLocales;
	      hooks.weekdaysShort = listWeekdaysShort;
	      hooks.normalizeUnits = normalizeUnits;
	      hooks.relativeTimeRounding = getSetRelativeTimeRounding;
	      hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
	      hooks.calendarFormat = getCalendarFormat;
	      hooks.prototype = proto;

	      // currently HTML5 input type only supports 24-hour formats
	      hooks.HTML5_FMT = {
	        DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm',
	        // <input type="datetime-local" />
	        DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss',
	        // <input type="datetime-local" step="1" />
	        DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS',
	        // <input type="datetime-local" step="0.001" />
	        DATE: 'YYYY-MM-DD',
	        // <input type="date" />
	        TIME: 'HH:mm',
	        // <input type="time" />
	        TIME_SECONDS: 'HH:mm:ss',
	        // <input type="time" step="1" />
	        TIME_MS: 'HH:mm:ss.SSS',
	        // <input type="time" step="0.001" />
	        WEEK: 'GGGG-[W]WW',
	        // <input type="week" />
	        MONTH: 'YYYY-MM' // <input type="month" />
	      };
	      return hooks;
	    });
	  })(moment$2);
	  return moment$2.exports;
	}

	var momentExports = requireMoment();
	const moment = /*@__PURE__*/getDefaultExportFromCjs(momentExports);

	var momentTimezoneWithData10YearRange$1 = {exports: {}};

	var momentTimezoneWithData10YearRange = momentTimezoneWithData10YearRange$1.exports;
	var hasRequiredMomentTimezoneWithData10YearRange;
	function requireMomentTimezoneWithData10YearRange() {
	  if (hasRequiredMomentTimezoneWithData10YearRange) return momentTimezoneWithData10YearRange$1.exports;
	  hasRequiredMomentTimezoneWithData10YearRange = 1;
	  (function (module) {
	    //! moment-timezone.js
	    //! version : 0.6.2
	    //! Copyright (c) JS Foundation and other contributors
	    //! license : MIT
	    //! github.com/moment/moment-timezone

	    (function (root, factory) {

	      /*global define*/
	      if (module.exports) {
	        module.exports = factory(requireMoment()); // Node
	      } else {
	        factory(root.moment); // Browser
	      }
	    })(momentTimezoneWithData10YearRange, function (moment) {

	      // Resolves es6 module loading issue
	      if (moment.version === undefined && moment.default) {
	        moment = moment.default;
	      }

	      // Do not load moment-timezone a second time.
	      // if (moment.tz !== undefined) {
	      // 	logError('Moment Timezone ' + moment.tz.version + ' was already loaded ' + (moment.tz.dataVersion ? 'with data from ' : 'without any data') + moment.tz.dataVersion);
	      // 	return moment;
	      // }

	      var VERSION = "0.6.2",
	        zones = {},
	        links = {},
	        countries = {},
	        names = {},
	        guesses = {},
	        cachedGuess;
	      if (!moment || typeof moment.version !== 'string') {
	        logError('Moment Timezone requires Moment.js. See https://momentjs.com/timezone/docs/#/use-it/browser/');
	      }
	      var momentVersion = moment.version.split('.'),
	        major = +momentVersion[0],
	        minor = +momentVersion[1];

	      // Moment.js version check
	      if (major < 2 || major === 2 && minor < 6) {
	        logError('Moment Timezone requires Moment.js >= 2.6.0. You are using Moment.js ' + moment.version + '. See momentjs.com');
	      }

	      /************************************
	      	Unpacking
	      ************************************/

	      function charCodeToInt(charCode) {
	        if (charCode > 96) {
	          return charCode - 87;
	        } else if (charCode > 64) {
	          return charCode - 29;
	        }
	        return charCode - 48;
	      }
	      function unpackBase60(string) {
	        var i = 0,
	          parts = string.split('.'),
	          whole = parts[0],
	          fractional = parts[1] || '',
	          multiplier = 1,
	          num,
	          out = 0,
	          sign = 1;

	        // handle negative numbers
	        if (string.charCodeAt(0) === 45) {
	          i = 1;
	          sign = -1;
	        }

	        // handle digits before the decimal
	        for (i; i < whole.length; i++) {
	          num = charCodeToInt(whole.charCodeAt(i));
	          out = 60 * out + num;
	        }

	        // handle digits after the decimal
	        for (i = 0; i < fractional.length; i++) {
	          multiplier = multiplier / 60;
	          num = charCodeToInt(fractional.charCodeAt(i));
	          out += num * multiplier;
	        }
	        return out * sign;
	      }
	      function arrayToInt(array) {
	        for (var i = 0; i < array.length; i++) {
	          array[i] = unpackBase60(array[i]);
	        }
	      }
	      function intToUntil(array, length) {
	        for (var i = 0; i < length; i++) {
	          array[i] = Math.round((array[i - 1] || 0) + array[i] * 60000); // minutes to milliseconds
	        }
	        array[length - 1] = Infinity;
	      }
	      function mapIndices(source, indices) {
	        var out = [],
	          i;
	        for (i = 0; i < indices.length; i++) {
	          out[i] = source[indices[i]];
	        }
	        return out;
	      }
	      function unpack(string) {
	        var data = string.split('|'),
	          offsets = data[2].split(' '),
	          indices = data[3].split(''),
	          untils = data[4].split(' ');
	        arrayToInt(offsets);
	        arrayToInt(indices);
	        arrayToInt(untils);
	        intToUntil(untils, indices.length);
	        return {
	          name: data[0],
	          abbrs: mapIndices(data[1].split(' '), indices),
	          offsets: mapIndices(offsets, indices),
	          untils: untils,
	          population: data[5] | 0
	        };
	      }

	      /************************************
	      	Zone object
	      ************************************/

	      function Zone(packedString) {
	        if (packedString) {
	          this._set(unpack(packedString));
	        }
	      }
	      function closest(num, arr) {
	        var len = arr.length;
	        if (num < arr[0]) {
	          return 0;
	        } else if (len > 1 && arr[len - 1] === Infinity && num >= arr[len - 2]) {
	          return len - 1;
	        } else if (num >= arr[len - 1]) {
	          return -1;
	        }
	        var mid;
	        var lo = 0;
	        var hi = len - 1;
	        while (hi - lo > 1) {
	          mid = Math.floor((lo + hi) / 2);
	          if (arr[mid] <= num) {
	            lo = mid;
	          } else {
	            hi = mid;
	          }
	        }
	        return hi;
	      }
	      Zone.prototype = {
	        _set: function (unpacked) {
	          this.name = unpacked.name;
	          this.abbrs = unpacked.abbrs;
	          this.untils = unpacked.untils;
	          this.offsets = unpacked.offsets;
	          this.population = unpacked.population;
	        },
	        _index: function (timestamp) {
	          var target = +timestamp,
	            untils = this.untils,
	            i;
	          i = closest(target, untils);
	          if (i >= 0) {
	            return i;
	          }
	        },
	        countries: function () {
	          var zone_name = this.name;
	          return Object.keys(countries).filter(function (country_code) {
	            return countries[country_code].zones.indexOf(zone_name) !== -1;
	          });
	        },
	        parse: function (timestamp) {
	          var target = +timestamp,
	            offsets = this.offsets,
	            untils = this.untils,
	            max = untils.length - 1,
	            offset,
	            offsetNext,
	            offsetPrev,
	            i;
	          for (i = 0; i < max; i++) {
	            offset = offsets[i];
	            offsetNext = offsets[i + 1];
	            offsetPrev = offsets[i ? i - 1 : i];
	            if (offset < offsetNext && tz.moveAmbiguousForward) {
	              offset = offsetNext;
	            } else if (offset > offsetPrev && tz.moveInvalidForward) {
	              offset = offsetPrev;
	            }
	            if (target < untils[i] - offset * 60000) {
	              return offsets[i];
	            }
	          }
	          return offsets[max];
	        },
	        abbr: function (mom) {
	          return this.abbrs[this._index(mom)];
	        },
	        offset: function (mom) {
	          logError("zone.offset has been deprecated in favor of zone.utcOffset");
	          return this.offsets[this._index(mom)];
	        },
	        utcOffset: function (mom) {
	          return this.offsets[this._index(mom)];
	        }
	      };

	      /************************************
	      	Country object
	      ************************************/

	      function Country(country_name, zone_names) {
	        this.name = country_name;
	        this.zones = zone_names;
	      }

	      /************************************
	      	Current Timezone
	      ************************************/

	      function OffsetAt(at) {
	        var timeString = at.toTimeString();
	        var abbr = timeString.match(/\([a-z ]+\)/i);
	        if (abbr && abbr[0]) {
	          // 17:56:31 GMT-0600 (CST)
	          // 17:56:31 GMT-0600 (Central Standard Time)
	          abbr = abbr[0].match(/[A-Z]/g);
	          abbr = abbr ? abbr.join('') : undefined;
	        } else {
	          // 17:56:31 CST
	          // 17:56:31 GMT+0800 (台北標準時間)
	          abbr = timeString.match(/[A-Z]{3,5}/g);
	          abbr = abbr ? abbr[0] : undefined;
	        }
	        if (abbr === 'GMT') {
	          abbr = undefined;
	        }
	        this.at = +at;
	        this.abbr = abbr;
	        this.offset = at.getTimezoneOffset();
	      }
	      function ZoneScore(zone) {
	        this.zone = zone;
	        this.offsetScore = 0;
	        this.abbrScore = 0;
	      }
	      ZoneScore.prototype.scoreOffsetAt = function (offsetAt) {
	        this.offsetScore += Math.abs(this.zone.utcOffset(offsetAt.at) - offsetAt.offset);
	        if (this.zone.abbr(offsetAt.at).replace(/[^A-Z]/g, '') !== offsetAt.abbr) {
	          this.abbrScore++;
	        }
	      };
	      function findChange(low, high) {
	        var mid, diff;
	        while (diff = ((high.at - low.at) / 12e4 | 0) * 6e4) {
	          mid = new OffsetAt(new Date(low.at + diff));
	          if (mid.offset === low.offset) {
	            low = mid;
	          } else {
	            high = mid;
	          }
	        }
	        return low;
	      }
	      function userOffsets() {
	        var startYear = new Date().getFullYear() - 2,
	          last = new OffsetAt(new Date(startYear, 0, 1)),
	          lastOffset = last.offset,
	          offsets = [last],
	          change,
	          next,
	          nextOffset,
	          i;
	        for (i = 1; i < 48; i++) {
	          nextOffset = new Date(startYear, i, 1).getTimezoneOffset();
	          if (nextOffset !== lastOffset) {
	            // Create OffsetAt here to avoid unnecessary abbr parsing before checking offsets
	            next = new OffsetAt(new Date(startYear, i, 1));
	            change = findChange(last, next);
	            offsets.push(change);
	            offsets.push(new OffsetAt(new Date(change.at + 6e4)));
	            last = next;
	            lastOffset = nextOffset;
	          }
	        }
	        for (i = 0; i < 4; i++) {
	          offsets.push(new OffsetAt(new Date(startYear + i, 0, 1)));
	          offsets.push(new OffsetAt(new Date(startYear + i, 6, 1)));
	        }
	        return offsets;
	      }
	      function sortZoneScores(a, b) {
	        if (a.offsetScore !== b.offsetScore) {
	          return a.offsetScore - b.offsetScore;
	        }
	        if (a.abbrScore !== b.abbrScore) {
	          return a.abbrScore - b.abbrScore;
	        }
	        if (a.zone.population !== b.zone.population) {
	          return b.zone.population - a.zone.population;
	        }
	        return b.zone.name.localeCompare(a.zone.name);
	      }
	      function addToGuesses(name, offsets) {
	        var i, offset;
	        arrayToInt(offsets);
	        for (i = 0; i < offsets.length; i++) {
	          offset = offsets[i];
	          guesses[offset] = guesses[offset] || {};
	          guesses[offset][name] = true;
	        }
	      }
	      function guessesForUserOffsets(offsets) {
	        var offsetsLength = offsets.length,
	          filteredGuesses = {},
	          out = [],
	          checkedOffsets = {},
	          i,
	          j,
	          offset,
	          guessesOffset;
	        for (i = 0; i < offsetsLength; i++) {
	          offset = offsets[i].offset;
	          if (checkedOffsets.hasOwnProperty(offset)) {
	            continue;
	          }
	          guessesOffset = guesses[offset] || {};
	          for (j in guessesOffset) {
	            if (guessesOffset.hasOwnProperty(j)) {
	              filteredGuesses[j] = true;
	            }
	          }
	          checkedOffsets[offset] = true;
	        }
	        for (i in filteredGuesses) {
	          if (filteredGuesses.hasOwnProperty(i)) {
	            out.push(names[i]);
	          }
	        }
	        return out;
	      }
	      function rebuildGuess() {
	        // use Intl API when available and returning valid time zone
	        try {
	          var intlName = Intl.DateTimeFormat().resolvedOptions().timeZone;
	          if (intlName && intlName.length > 3) {
	            var name = names[normalizeName(intlName)];
	            if (name) {
	              return name;
	            }
	            logError("Moment Timezone found " + intlName + " from the Intl api, but did not have that data loaded.");
	          }
	        } catch (e) {
	          // Intl unavailable, fall back to manual guessing.
	        }
	        var offsets = userOffsets(),
	          offsetsLength = offsets.length,
	          guesses = guessesForUserOffsets(offsets),
	          zoneScores = [],
	          zoneScore,
	          i,
	          j;
	        for (i = 0; i < guesses.length; i++) {
	          zoneScore = new ZoneScore(getZone(guesses[i]));
	          for (j = 0; j < offsetsLength; j++) {
	            zoneScore.scoreOffsetAt(offsets[j]);
	          }
	          zoneScores.push(zoneScore);
	        }
	        zoneScores.sort(sortZoneScores);
	        return zoneScores.length > 0 ? zoneScores[0].zone.name : undefined;
	      }
	      function guess(ignoreCache) {
	        if (!cachedGuess || ignoreCache) {
	          cachedGuess = rebuildGuess();
	        }
	        return cachedGuess;
	      }

	      /************************************
	      	Global Methods
	      ************************************/

	      function normalizeName(name) {
	        return (name || '').toLowerCase().replace(/\//g, '_');
	      }
	      function addZone(packed) {
	        var i, name, split, normalized;
	        if (typeof packed === "string") {
	          packed = [packed];
	        }
	        for (i = 0; i < packed.length; i++) {
	          split = packed[i].split('|');
	          name = split[0];
	          normalized = normalizeName(name);
	          zones[normalized] = packed[i];
	          names[normalized] = name;
	          addToGuesses(normalized, split[2].split(' '));
	        }
	      }
	      function getZone(name, caller) {
	        name = normalizeName(name);
	        var zone = zones[name];
	        var link;
	        if (zone instanceof Zone) {
	          return zone;
	        }
	        if (typeof zone === 'string') {
	          zone = new Zone(zone);
	          zones[name] = zone;
	          return zone;
	        }

	        // Pass getZone to prevent recursion more than 1 level deep
	        if (links[name] && caller !== getZone && (link = getZone(links[name], getZone))) {
	          zone = zones[name] = new Zone();
	          zone._set(link);
	          zone.name = names[name];
	          return zone;
	        }
	        return null;
	      }
	      function getNames() {
	        var i,
	          out = [];
	        for (i in names) {
	          if (names.hasOwnProperty(i) && (zones[i] || zones[links[i]]) && names[i]) {
	            out.push(names[i]);
	          }
	        }
	        return out.sort();
	      }
	      function getCountryNames() {
	        return Object.keys(countries);
	      }
	      function addLink(aliases) {
	        var i, alias, normal0, normal1;
	        if (typeof aliases === "string") {
	          aliases = [aliases];
	        }
	        for (i = 0; i < aliases.length; i++) {
	          alias = aliases[i].split('|');
	          normal0 = normalizeName(alias[0]);
	          normal1 = normalizeName(alias[1]);
	          links[normal0] = normal1;
	          names[normal0] = alias[0];
	          links[normal1] = normal0;
	          names[normal1] = alias[1];
	        }
	      }
	      function addCountries(data) {
	        var i, country_code, country_zones, split;
	        if (!data || !data.length) return;
	        for (i = 0; i < data.length; i++) {
	          split = data[i].split('|');
	          country_code = split[0].toUpperCase();
	          country_zones = split[1].split(' ');
	          countries[country_code] = new Country(country_code, country_zones);
	        }
	      }
	      function getCountry(name) {
	        name = name.toUpperCase();
	        return countries[name] || null;
	      }
	      function zonesForCountry(country, with_offset) {
	        country = getCountry(country);
	        if (!country) return null;
	        var zones = country.zones.sort();
	        if (with_offset) {
	          return zones.map(function (zone_name) {
	            var zone = getZone(zone_name);
	            return {
	              name: zone_name,
	              offset: zone.utcOffset(new Date())
	            };
	          });
	        }
	        return zones;
	      }
	      function loadData(data) {
	        addZone(data.zones);
	        addLink(data.links);
	        addCountries(data.countries);
	        tz.dataVersion = data.version;
	      }
	      function zoneExists(name) {
	        if (!zoneExists.didShowError) {
	          zoneExists.didShowError = true;
	          logError("moment.tz.zoneExists('" + name + "') has been deprecated in favor of !moment.tz.zone('" + name + "')");
	        }
	        return !!getZone(name);
	      }
	      function needsOffset(m) {
	        var isUnixTimestamp = m._f === 'X' || m._f === 'x';
	        return !!(m._a && m._tzm === undefined && !isUnixTimestamp);
	      }
	      function logError(message) {
	        if (typeof console !== 'undefined' && typeof console.error === 'function') {
	          console.error(message);
	        }
	      }

	      /************************************
	      	moment.tz namespace
	      ************************************/

	      function tz(input) {
	        var args = Array.prototype.slice.call(arguments, 0, -1),
	          name = arguments[arguments.length - 1],
	          out = moment.utc.apply(null, args),
	          zone;
	        if (!moment.isMoment(input) && needsOffset(out) && (zone = getZone(name))) {
	          out.add(zone.parse(out), 'minutes');
	        }
	        out.tz(name);
	        return out;
	      }
	      tz.version = VERSION;
	      tz.dataVersion = '';
	      tz._zones = zones;
	      tz._links = links;
	      tz._names = names;
	      tz._countries = countries;
	      tz.add = addZone;
	      tz.link = addLink;
	      tz.load = loadData;
	      tz.zone = getZone;
	      tz.zoneExists = zoneExists; // deprecated in 0.1.0
	      tz.guess = guess;
	      tz.names = getNames;
	      tz.Zone = Zone;
	      tz.unpack = unpack;
	      tz.unpackBase60 = unpackBase60;
	      tz.needsOffset = needsOffset;
	      tz.moveInvalidForward = true;
	      tz.moveAmbiguousForward = false;
	      tz.countries = getCountryNames;
	      tz.zonesForCountry = zonesForCountry;

	      /************************************
	      	Interface with Moment.js
	      ************************************/

	      var fn = moment.fn;
	      moment.tz = tz;
	      moment.defaultZone = null;
	      moment.updateOffset = function (mom, keepTime) {
	        var zone = moment.defaultZone,
	          offset;
	        if (mom._z === undefined) {
	          if (zone && needsOffset(mom) && !mom._isUTC && mom.isValid()) {
	            mom._d = moment.utc(mom._a)._d;
	            mom.utc().add(zone.parse(mom), 'minutes');
	          }
	          mom._z = zone;
	        }
	        if (mom._z) {
	          offset = mom._z.utcOffset(mom);
	          if (Math.abs(offset) < 16) {
	            offset = offset / 60;
	          }
	          if (mom.utcOffset !== undefined) {
	            var z = mom._z;
	            mom.utcOffset(-offset, keepTime);
	            mom._z = z;
	          } else {
	            mom.zone(offset, keepTime);
	          }
	        }
	      };
	      fn.tz = function (name, keepTime) {
	        if (name) {
	          if (typeof name !== 'string') {
	            throw new Error('Time zone name must be a string, got ' + name + ' [' + typeof name + ']');
	          }
	          this._z = getZone(name);
	          if (this._z) {
	            moment.updateOffset(this, keepTime);
	          } else {
	            logError("Moment Timezone has no data for " + name + ". See http://momentjs.com/timezone/docs/#/data-loading/.");
	          }
	          return this;
	        }
	        if (this._z) {
	          return this._z.name;
	        }
	      };
	      function abbrWrap(old) {
	        return function () {
	          if (this._z) {
	            return this._z.abbr(this);
	          }
	          return old.call(this);
	        };
	      }
	      function resetZoneWrap(old) {
	        return function () {
	          this._z = null;
	          return old.apply(this, arguments);
	        };
	      }
	      function resetZoneWrap2(old) {
	        return function () {
	          if (arguments.length > 0) this._z = null;
	          return old.apply(this, arguments);
	        };
	      }
	      fn.zoneName = abbrWrap(fn.zoneName);
	      fn.zoneAbbr = abbrWrap(fn.zoneAbbr);
	      fn.utc = resetZoneWrap(fn.utc);
	      fn.local = resetZoneWrap(fn.local);
	      fn.utcOffset = resetZoneWrap2(fn.utcOffset);
	      moment.tz.setDefault = function (name) {
	        if (major < 2 || major === 2 && minor < 9) {
	          logError('Moment Timezone setDefault() requires Moment.js >= 2.9.0. You are using Moment.js ' + moment.version + '.');
	        }
	        moment.defaultZone = name ? getZone(name) : null;
	        return moment;
	      };

	      // Cloning a moment should include the _z property.
	      var momentProperties = moment.momentProperties;
	      if (Object.prototype.toString.call(momentProperties) === '[object Array]') {
	        // moment 2.8.1+
	        momentProperties.push('_z');
	        momentProperties.push('_a');
	      } else if (momentProperties) {
	        // moment 2.7.0
	        momentProperties._z = null;
	      }
	      loadData({
	        "version": "2026b",
	        "zones": ["Africa/Abidjan|GMT|0|0||48e5", "Africa/Nairobi|EAT|-30|0||47e5", "Africa/Algiers|CET|-10|0||26e5", "Africa/Lagos|WAT|-10|0||17e6", "Africa/Khartoum|CAT|-20|0||51e5", "Africa/Cairo|EET EEST|-20 -30|0101010101010101010|29NW0 1cL0 1cN0 1fz0 1a10 1fz0 1a10 1fz0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1fz0 1a10 1fz0|15e6", "Africa/Casablanca|+01 +00|-10 0|010101010101010101010101|24Pe0 e00 2600 gM0 2600 e00 28M0 e00 2600 gM0 2600 e00 28M0 e00 2600 gM0 2600 e00 2600 gM0 2600 e00 28M0|32e5", "Europe/Paris|CET CEST|-10 -20|01010101010101010101010|24JB0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00|11e6", "Africa/Johannesburg|SAST|-20|0||84e5", "Africa/Juba|EAT CAT|-30 -20|01|24nx0|", "Africa/Tripoli|EET|-20|0||11e5", "America/Adak|HST HDT|a0 90|01010101010101010101010|24Ec0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0|326", "America/Anchorage|AKST AKDT|90 80|01010101010101010101010|24Eb0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0|30e4", "America/Santo_Domingo|AST|40|0||29e5", "America/Sao_Paulo|-03|30|0||20e6", "America/Asuncion|-03 -04|30 40|010101010|24JD0 1fB0 19X0 1fB0 19X0 1fB0 19X0 1ip0|28e5", "America/Panama|EST|50|0||15e5", "America/Mexico_City|CST CDT|60 50|01010|24Mw0 1nX0 11B0 1nX0|20e6", "America/Managua|CST|60|0||22e5", "America/Caracas|-04|40|0||29e5", "America/Lima|-05|50|0||11e6", "America/Denver|MST MDT|70 60|01010101010101010101010|24E90 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0|26e5", "America/Chicago|CST CDT|60 50|01010101010101010101010|24E80 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0|92e5", "America/Chihuahua|MST MDT CST|70 60 60|01012|24Mx0 1nX0 11B0 1nX0|81e4", "America/Ciudad_Juarez|MST MDT CST|70 60 60|010120101010101010101010|24E90 1zb0 Op0 1wn0 cm0 EP0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0|", "America/Coyhaique|-03 -04|30 40|010101010|24Mr0 11B0 1nX0 14p0 1lb0 11B0 1qL0 11B0|", "America/Phoenix|MST|70|0||42e5", "America/New_York|EST EDT|50 40|01010101010101010101010|24E70 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0|21e6", "America/Los_Angeles|PST PDT|80 70|01010101010101010101010|24Ea0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0|15e6", "America/Halifax|AST ADT|40 30|01010101010101010101010|24E60 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0|39e4", "America/Godthab|-03 -02 -01|30 20 10|0101012121212121212121|24JB0 1qM0 WM0 1qM0 WM0 2so0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00|17e3", "America/Havana|CST CDT|50 40|01010101010101010101010|24E50 1zc0 Oo0 1zc0 Oo0 1zc0 Oo0 1zc0 Oo0 1zc0 Oo0 1zc0 Rc0 1zc0 Oo0 1zc0 Oo0 1zc0 Oo0 1zc0 Oo0 1zc0|21e5", "America/Mazatlan|MST MDT|70 60|01010|24Mx0 1nX0 11B0 1nX0|44e4", "America/Miquelon|-03 -02|30 20|01010101010101010101010|24E50 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0|61e2", "America/Noronha|-02|20|0||30e2", "America/Ojinaga|MST MDT CST CDT|70 60 60 50|01012323232323232323232|24E90 1zb0 Op0 1wn0 Rc0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0|23e3", "America/Santiago|-03 -04|30 40|01010101010101010101010|24Mr0 11B0 1nX0 14p0 1lb0 11B0 1qL0 11B0 1nX0 11B0 1nX0 11B0 1nX0 11B0 1nX0 11B0 1qL0 WN0 1qL0 11B0 1nX0 11B0|62e5", "America/Scoresbysund|-01 +00 -02|10 0 20|0101010202020202020202|24JB0 1qM0 WM0 1qM0 WM0 1qM0 2pA0 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00|452", "America/St_Johns|NST NDT|3u 2u|01010101010101010101010|24E5u 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0|11e4", "America/Vancouver|PST PDT MST|80 70 70|0101010101012|24Ea0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0|23e5", "Antarctica/Casey|+11 +08|-b0 -80|010101|24DN0 1lf1 14kX 1lf1 13bX|10", "Asia/Bangkok|+07|-70|0||15e6", "Asia/Vladivostok|+10|-a0|0||60e4", "Australia/Sydney|AEDT AEST|-b0 -a0|01010101010101010101010|24Mg0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0|40e5", "Asia/Tashkent|+05|-50|0||23e5", "Pacific/Auckland|NZDT NZST|-d0 -c0|01010101010101010101010|24Me0 1a00 1fA0 1a00 1fA0 1a00 1io0 1a00 1fA0 1a00 1fA0 1a00 1fA0 1a00 1fA0 1a00 1fA0 1cM0 1fA0 1a00 1fA0 1a00|14e5", "Europe/Istanbul|+03|-30|0||13e6", "Antarctica/Troll|+00 +02|0 -20|01010101010101010101010|24JB0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00|40", "Antarctica/Vostok|+07 +05|-70 -50|01|2bnv0|25", "Asia/Almaty|+06 +05|-60 -50|01|2bR60|15e5", "Asia/Amman|EET EEST +03|-20 -30 -30|01012|24IK0 1qM0 LA0 1C00|25e5", "Asia/Kamchatka|+12|-c0|0||18e4", "Asia/Dubai|+04|-40|0||39e5", "Asia/Beirut|EET EEST|-20 -30|01010101010101010101010|24Jy0 1qL0 WN0 1qL0 WN0 1qL0 11B0 1nX0 11B0 1nX0 11B0 1nX0 11B0 1qL0 WN0 1qL0 WN0 1qL0 11B0 1nX0 11B0 1nX0|22e5", "Asia/Dhaka|+06|-60|0||16e6", "Asia/Kuala_Lumpur|+08|-80|0||71e5", "Asia/Kolkata|IST|-5u|0||15e6", "Asia/Chita|+09|-90|0||33e4", "Asia/Shanghai|CST|-80|0||23e6", "Asia/Colombo|+0530|-5u|0||22e5", "Asia/Damascus|EET EEST +03|-20 -30 -30|01012|24IK0 1qL0 WN0 1qL0|26e5", "Europe/Athens|EET EEST|-20 -30|01010101010101010101010|24JB0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00|35e5", "Asia/Gaza|EET EEST|-20 -30|01010101010101010101010|24Ja0 1qo0 XA0 1qp0 1cN0 1cL0 1a10 1fz0 17d0 1in0 11B0 1nX0 11B0 1qL0 WN0 1qL0 WN0 1qL0 11B0 1nX0 11B0 1nX0|18e5", "Asia/Hong_Kong|HKT|-80|0||73e5", "Asia/Jakarta|WIB|-70|0||31e6", "Asia/Jayapura|WIT|-90|0||26e4", "Asia/Jerusalem|IST IDT|-20 -30|01010101010101010101010|24IM0 1rz0 W10 1rz0 W10 1rz0 10N0 1oL0 10N0 1oL0 10N0 1oL0 10N0 1rz0 W10 1rz0 W10 1rz0 10N0 1oL0 10N0 1oL0|81e4", "Asia/Kabul|+0430|-4u|0||46e5", "Asia/Karachi|PKT|-50|0||24e6", "Asia/Kathmandu|+0545|-5J|0||12e5", "Asia/Sakhalin|+11|-b0|0||58e4", "Asia/Makassar|WITA|-80|0||15e5", "Asia/Manila|PST|-80|0||24e6", "Asia/Seoul|KST|-90|0||23e6", "Asia/Rangoon|+0630|-6u|0||48e5", "Asia/Tehran|+0330 +0430|-3u -4u|01010|24H8u 1dz0 1cp0 1dz0|14e6", "Asia/Tokyo|JST|-90|0||38e6", "Atlantic/Azores|-01 +00|10 0|01010101010101010101010|24JB0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00|25e4", "Europe/Lisbon|WET WEST|0 -10|01010101010101010101010|24JB0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00|27e5", "Atlantic/Cape_Verde|-01|10|0||50e4", "Australia/Adelaide|ACDT ACST|-au -9u|01010101010101010101010|24Mgu 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0|11e5", "Australia/Brisbane|AEST|-a0|0||20e5", "Australia/Darwin|ACST|-9u|0||12e4", "Australia/Eucla|+0845|-8J|0||368", "Australia/Lord_Howe|+11 +1030|-b0 -au|01010101010101010101010|24Mf0 1cMu 1cLu 1cMu 1cLu 1cMu 1fzu 1cMu 1cLu 1cMu 1cLu 1cMu 1cLu 1cMu 1cLu 1cMu 1cLu 1fAu 1cLu 1cMu 1cLu 1cMu|347", "Australia/Perth|AWST|-80|0||18e5", "Pacific/Easter|-05 -06|50 60|01010101010101010101010|24Mr0 11B0 1nX0 14p0 1lb0 11B0 1qL0 11B0 1nX0 11B0 1nX0 11B0 1nX0 11B0 1nX0 11B0 1qL0 WN0 1qL0 11B0 1nX0 11B0|30e2", "Europe/Dublin|GMT IST|0 -10|01010101010101010101010|24JB0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00|12e5", "Etc/GMT-1|+01|-10|0||", "Pacific/Tongatapu|+13|-d0|0||75e3", "Pacific/Kiritimati|+14|-e0|0||51e2", "Etc/GMT-2|+02|-20|0||", "Pacific/Tahiti|-10|a0|0||18e4", "Pacific/Niue|-11|b0|0||12e2", "Etc/GMT+12|-12|c0|0||", "Pacific/Galapagos|-06|60|0||25e3", "Etc/GMT+7|-07|70|0||", "Pacific/Pitcairn|-08|80|0||56", "Pacific/Gambier|-09|90|0||125", "Etc/UTC|UTC|0|0||", "Europe/London|GMT BST|0 -10|01010101010101010101010|24JB0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00|10e6", "Europe/Chisinau|EET EEST|-20 -30|01010101010101010101010|24JA0 1qM0 WN0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00|67e4", "Europe/Moscow|MSK|-30|0||16e6", "Pacific/Honolulu|HST|a0|0||37e4", "Pacific/Chatham|+1345 +1245|-dJ -cJ|01010101010101010101010|24Me0 1a00 1fA0 1a00 1fA0 1a00 1io0 1a00 1fA0 1a00 1fA0 1a00 1fA0 1a00 1fA0 1a00 1fA0 1cM0 1fA0 1a00 1fA0 1a00|600", "Pacific/Apia|+14 +13|-e0 -d0|01|24Me0|37e3", "Pacific/Fiji|+13 +12|-d0 -c0|01|24hq0|88e4", "Pacific/Guam|ChST|-a0|0||17e4", "Pacific/Marquesas|-0930|9u|0||86e2", "Pacific/Pago_Pago|SST|b0|0||37e2", "Pacific/Norfolk|+12 +11|-c0 -b0|01010101010101010101010|24Mf0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0|25e4"],
	        "links": ["Africa/Abidjan|Africa/Accra", "Africa/Abidjan|Africa/Bamako", "Africa/Abidjan|Africa/Banjul", "Africa/Abidjan|Africa/Bissau", "Africa/Abidjan|Africa/Conakry", "Africa/Abidjan|Africa/Dakar", "Africa/Abidjan|Africa/Freetown", "Africa/Abidjan|Africa/Lome", "Africa/Abidjan|Africa/Monrovia", "Africa/Abidjan|Africa/Nouakchott", "Africa/Abidjan|Africa/Ouagadougou", "Africa/Abidjan|Africa/Sao_Tome", "Africa/Abidjan|Africa/Timbuktu", "Africa/Abidjan|America/Danmarkshavn", "Africa/Abidjan|Atlantic/Reykjavik", "Africa/Abidjan|Atlantic/St_Helena", "Africa/Abidjan|Etc/GMT", "Africa/Abidjan|Etc/GMT+0", "Africa/Abidjan|Etc/GMT-0", "Africa/Abidjan|Etc/GMT0", "Africa/Abidjan|Etc/Greenwich", "Africa/Abidjan|GMT", "Africa/Abidjan|GMT+0", "Africa/Abidjan|GMT-0", "Africa/Abidjan|GMT0", "Africa/Abidjan|Greenwich", "Africa/Abidjan|Iceland", "Africa/Algiers|Africa/Tunis", "Africa/Cairo|Egypt", "Africa/Casablanca|Africa/El_Aaiun", "Africa/Johannesburg|Africa/Maseru", "Africa/Johannesburg|Africa/Mbabane", "Africa/Khartoum|Africa/Blantyre", "Africa/Khartoum|Africa/Bujumbura", "Africa/Khartoum|Africa/Gaborone", "Africa/Khartoum|Africa/Harare", "Africa/Khartoum|Africa/Kigali", "Africa/Khartoum|Africa/Lubumbashi", "Africa/Khartoum|Africa/Lusaka", "Africa/Khartoum|Africa/Maputo", "Africa/Khartoum|Africa/Windhoek", "Africa/Lagos|Africa/Bangui", "Africa/Lagos|Africa/Brazzaville", "Africa/Lagos|Africa/Douala", "Africa/Lagos|Africa/Kinshasa", "Africa/Lagos|Africa/Libreville", "Africa/Lagos|Africa/Luanda", "Africa/Lagos|Africa/Malabo", "Africa/Lagos|Africa/Ndjamena", "Africa/Lagos|Africa/Niamey", "Africa/Lagos|Africa/Porto-Novo", "Africa/Nairobi|Africa/Addis_Ababa", "Africa/Nairobi|Africa/Asmara", "Africa/Nairobi|Africa/Asmera", "Africa/Nairobi|Africa/Dar_es_Salaam", "Africa/Nairobi|Africa/Djibouti", "Africa/Nairobi|Africa/Kampala", "Africa/Nairobi|Africa/Mogadishu", "Africa/Nairobi|Indian/Antananarivo", "Africa/Nairobi|Indian/Comoro", "Africa/Nairobi|Indian/Mayotte", "Africa/Tripoli|Europe/Kaliningrad", "Africa/Tripoli|Libya", "America/Adak|America/Atka", "America/Adak|US/Aleutian", "America/Anchorage|America/Juneau", "America/Anchorage|America/Metlakatla", "America/Anchorage|America/Nome", "America/Anchorage|America/Sitka", "America/Anchorage|America/Yakutat", "America/Anchorage|US/Alaska", "America/Caracas|America/Boa_Vista", "America/Caracas|America/Campo_Grande", "America/Caracas|America/Cuiaba", "America/Caracas|America/Guyana", "America/Caracas|America/La_Paz", "America/Caracas|America/Manaus", "America/Caracas|America/Porto_Velho", "America/Caracas|Brazil/West", "America/Caracas|Etc/GMT+4", "America/Chicago|America/Indiana/Knox", "America/Chicago|America/Indiana/Tell_City", "America/Chicago|America/Knox_IN", "America/Chicago|America/Matamoros", "America/Chicago|America/Menominee", "America/Chicago|America/North_Dakota/Beulah", "America/Chicago|America/North_Dakota/Center", "America/Chicago|America/North_Dakota/New_Salem", "America/Chicago|America/Rainy_River", "America/Chicago|America/Rankin_Inlet", "America/Chicago|America/Resolute", "America/Chicago|America/Winnipeg", "America/Chicago|CST6CDT", "America/Chicago|Canada/Central", "America/Chicago|US/Central", "America/Chicago|US/Indiana-Starke", "America/Denver|America/Boise", "America/Denver|America/Cambridge_Bay", "America/Denver|America/Edmonton", "America/Denver|America/Inuvik", "America/Denver|America/Shiprock", "America/Denver|America/Yellowknife", "America/Denver|Canada/Mountain", "America/Denver|MST7MDT", "America/Denver|Navajo", "America/Denver|US/Mountain", "America/Godthab|America/Nuuk", "America/Halifax|America/Glace_Bay", "America/Halifax|America/Goose_Bay", "America/Halifax|America/Moncton", "America/Halifax|America/Thule", "America/Halifax|Atlantic/Bermuda", "America/Halifax|Canada/Atlantic", "America/Havana|Cuba", "America/Lima|America/Bogota", "America/Lima|America/Eirunepe", "America/Lima|America/Guayaquil", "America/Lima|America/Porto_Acre", "America/Lima|America/Rio_Branco", "America/Lima|Brazil/Acre", "America/Lima|Etc/GMT+5", "America/Los_Angeles|America/Ensenada", "America/Los_Angeles|America/Santa_Isabel", "America/Los_Angeles|America/Tijuana", "America/Los_Angeles|Mexico/BajaNorte", "America/Los_Angeles|PST8PDT", "America/Los_Angeles|US/Pacific", "America/Managua|America/Belize", "America/Managua|America/Costa_Rica", "America/Managua|America/El_Salvador", "America/Managua|America/Guatemala", "America/Managua|America/Regina", "America/Managua|America/Swift_Current", "America/Managua|America/Tegucigalpa", "America/Managua|Canada/Saskatchewan", "America/Mazatlan|Mexico/BajaSur", "America/Mexico_City|America/Bahia_Banderas", "America/Mexico_City|America/Merida", "America/Mexico_City|America/Monterrey", "America/Mexico_City|Mexico/General", "America/New_York|America/Detroit", "America/New_York|America/Fort_Wayne", "America/New_York|America/Grand_Turk", "America/New_York|America/Indiana/Indianapolis", "America/New_York|America/Indiana/Marengo", "America/New_York|America/Indiana/Petersburg", "America/New_York|America/Indiana/Vevay", "America/New_York|America/Indiana/Vincennes", "America/New_York|America/Indiana/Winamac", "America/New_York|America/Indianapolis", "America/New_York|America/Iqaluit", "America/New_York|America/Kentucky/Louisville", "America/New_York|America/Kentucky/Monticello", "America/New_York|America/Louisville", "America/New_York|America/Montreal", "America/New_York|America/Nassau", "America/New_York|America/Nipigon", "America/New_York|America/Pangnirtung", "America/New_York|America/Port-au-Prince", "America/New_York|America/Thunder_Bay", "America/New_York|America/Toronto", "America/New_York|Canada/Eastern", "America/New_York|EST5EDT", "America/New_York|US/East-Indiana", "America/New_York|US/Eastern", "America/New_York|US/Michigan", "America/Noronha|Atlantic/South_Georgia", "America/Noronha|Brazil/DeNoronha", "America/Noronha|Etc/GMT+2", "America/Panama|America/Atikokan", "America/Panama|America/Cancun", "America/Panama|America/Cayman", "America/Panama|America/Coral_Harbour", "America/Panama|America/Jamaica", "America/Panama|EST", "America/Panama|Jamaica", "America/Phoenix|America/Creston", "America/Phoenix|America/Dawson", "America/Phoenix|America/Dawson_Creek", "America/Phoenix|America/Fort_Nelson", "America/Phoenix|America/Hermosillo", "America/Phoenix|America/Whitehorse", "America/Phoenix|Canada/Yukon", "America/Phoenix|MST", "America/Phoenix|US/Arizona", "America/Santiago|Chile/Continental", "America/Santo_Domingo|America/Anguilla", "America/Santo_Domingo|America/Antigua", "America/Santo_Domingo|America/Aruba", "America/Santo_Domingo|America/Barbados", "America/Santo_Domingo|America/Blanc-Sablon", "America/Santo_Domingo|America/Curacao", "America/Santo_Domingo|America/Dominica", "America/Santo_Domingo|America/Grenada", "America/Santo_Domingo|America/Guadeloupe", "America/Santo_Domingo|America/Kralendijk", "America/Santo_Domingo|America/Lower_Princes", "America/Santo_Domingo|America/Marigot", "America/Santo_Domingo|America/Martinique", "America/Santo_Domingo|America/Montserrat", "America/Santo_Domingo|America/Port_of_Spain", "America/Santo_Domingo|America/Puerto_Rico", "America/Santo_Domingo|America/St_Barthelemy", "America/Santo_Domingo|America/St_Kitts", "America/Santo_Domingo|America/St_Lucia", "America/Santo_Domingo|America/St_Thomas", "America/Santo_Domingo|America/St_Vincent", "America/Santo_Domingo|America/Tortola", "America/Santo_Domingo|America/Virgin", "America/Sao_Paulo|America/Araguaina", "America/Sao_Paulo|America/Argentina/Buenos_Aires", "America/Sao_Paulo|America/Argentina/Catamarca", "America/Sao_Paulo|America/Argentina/ComodRivadavia", "America/Sao_Paulo|America/Argentina/Cordoba", "America/Sao_Paulo|America/Argentina/Jujuy", "America/Sao_Paulo|America/Argentina/La_Rioja", "America/Sao_Paulo|America/Argentina/Mendoza", "America/Sao_Paulo|America/Argentina/Rio_Gallegos", "America/Sao_Paulo|America/Argentina/Salta", "America/Sao_Paulo|America/Argentina/San_Juan", "America/Sao_Paulo|America/Argentina/San_Luis", "America/Sao_Paulo|America/Argentina/Tucuman", "America/Sao_Paulo|America/Argentina/Ushuaia", "America/Sao_Paulo|America/Bahia", "America/Sao_Paulo|America/Belem", "America/Sao_Paulo|America/Buenos_Aires", "America/Sao_Paulo|America/Catamarca", "America/Sao_Paulo|America/Cayenne", "America/Sao_Paulo|America/Cordoba", "America/Sao_Paulo|America/Fortaleza", "America/Sao_Paulo|America/Jujuy", "America/Sao_Paulo|America/Maceio", "America/Sao_Paulo|America/Mendoza", "America/Sao_Paulo|America/Montevideo", "America/Sao_Paulo|America/Paramaribo", "America/Sao_Paulo|America/Punta_Arenas", "America/Sao_Paulo|America/Recife", "America/Sao_Paulo|America/Rosario", "America/Sao_Paulo|America/Santarem", "America/Sao_Paulo|Antarctica/Palmer", "America/Sao_Paulo|Antarctica/Rothera", "America/Sao_Paulo|Atlantic/Stanley", "America/Sao_Paulo|Brazil/East", "America/Sao_Paulo|Etc/GMT+3", "America/St_Johns|Canada/Newfoundland", "America/Vancouver|Canada/Pacific", "Asia/Almaty|Asia/Qostanay", "Asia/Bangkok|Antarctica/Davis", "Asia/Bangkok|Asia/Barnaul", "Asia/Bangkok|Asia/Ho_Chi_Minh", "Asia/Bangkok|Asia/Hovd", "Asia/Bangkok|Asia/Krasnoyarsk", "Asia/Bangkok|Asia/Novokuznetsk", "Asia/Bangkok|Asia/Novosibirsk", "Asia/Bangkok|Asia/Phnom_Penh", "Asia/Bangkok|Asia/Saigon", "Asia/Bangkok|Asia/Tomsk", "Asia/Bangkok|Asia/Vientiane", "Asia/Bangkok|Etc/GMT-7", "Asia/Bangkok|Indian/Christmas", "Asia/Chita|Asia/Dili", "Asia/Chita|Asia/Khandyga", "Asia/Chita|Asia/Yakutsk", "Asia/Chita|Etc/GMT-9", "Asia/Chita|Pacific/Palau", "Asia/Dhaka|Asia/Bishkek", "Asia/Dhaka|Asia/Dacca", "Asia/Dhaka|Asia/Kashgar", "Asia/Dhaka|Asia/Omsk", "Asia/Dhaka|Asia/Thimbu", "Asia/Dhaka|Asia/Thimphu", "Asia/Dhaka|Asia/Urumqi", "Asia/Dhaka|Etc/GMT-6", "Asia/Dhaka|Indian/Chagos", "Asia/Dubai|Asia/Baku", "Asia/Dubai|Asia/Muscat", "Asia/Dubai|Asia/Tbilisi", "Asia/Dubai|Asia/Yerevan", "Asia/Dubai|Etc/GMT-4", "Asia/Dubai|Europe/Astrakhan", "Asia/Dubai|Europe/Samara", "Asia/Dubai|Europe/Saratov", "Asia/Dubai|Europe/Ulyanovsk", "Asia/Dubai|Indian/Mahe", "Asia/Dubai|Indian/Mauritius", "Asia/Dubai|Indian/Reunion", "Asia/Gaza|Asia/Hebron", "Asia/Hong_Kong|Hongkong", "Asia/Jakarta|Asia/Pontianak", "Asia/Jerusalem|Asia/Tel_Aviv", "Asia/Jerusalem|Israel", "Asia/Kamchatka|Asia/Anadyr", "Asia/Kamchatka|Etc/GMT-12", "Asia/Kamchatka|Kwajalein", "Asia/Kamchatka|Pacific/Funafuti", "Asia/Kamchatka|Pacific/Kwajalein", "Asia/Kamchatka|Pacific/Majuro", "Asia/Kamchatka|Pacific/Nauru", "Asia/Kamchatka|Pacific/Tarawa", "Asia/Kamchatka|Pacific/Wake", "Asia/Kamchatka|Pacific/Wallis", "Asia/Kathmandu|Asia/Katmandu", "Asia/Kolkata|Asia/Calcutta", "Asia/Kuala_Lumpur|Asia/Brunei", "Asia/Kuala_Lumpur|Asia/Choibalsan", "Asia/Kuala_Lumpur|Asia/Irkutsk", "Asia/Kuala_Lumpur|Asia/Kuching", "Asia/Kuala_Lumpur|Asia/Singapore", "Asia/Kuala_Lumpur|Asia/Ulaanbaatar", "Asia/Kuala_Lumpur|Asia/Ulan_Bator", "Asia/Kuala_Lumpur|Etc/GMT-8", "Asia/Kuala_Lumpur|Singapore", "Asia/Makassar|Asia/Ujung_Pandang", "Asia/Rangoon|Asia/Yangon", "Asia/Rangoon|Indian/Cocos", "Asia/Sakhalin|Asia/Magadan", "Asia/Sakhalin|Asia/Srednekolymsk", "Asia/Sakhalin|Etc/GMT-11", "Asia/Sakhalin|Pacific/Bougainville", "Asia/Sakhalin|Pacific/Efate", "Asia/Sakhalin|Pacific/Guadalcanal", "Asia/Sakhalin|Pacific/Kosrae", "Asia/Sakhalin|Pacific/Noumea", "Asia/Sakhalin|Pacific/Pohnpei", "Asia/Sakhalin|Pacific/Ponape", "Asia/Seoul|Asia/Pyongyang", "Asia/Seoul|ROK", "Asia/Shanghai|Asia/Chongqing", "Asia/Shanghai|Asia/Chungking", "Asia/Shanghai|Asia/Harbin", "Asia/Shanghai|Asia/Macao", "Asia/Shanghai|Asia/Macau", "Asia/Shanghai|Asia/Taipei", "Asia/Shanghai|PRC", "Asia/Shanghai|ROC", "Asia/Tashkent|Antarctica/Mawson", "Asia/Tashkent|Asia/Aqtau", "Asia/Tashkent|Asia/Aqtobe", "Asia/Tashkent|Asia/Ashgabat", "Asia/Tashkent|Asia/Ashkhabad", "Asia/Tashkent|Asia/Atyrau", "Asia/Tashkent|Asia/Dushanbe", "Asia/Tashkent|Asia/Oral", "Asia/Tashkent|Asia/Qyzylorda", "Asia/Tashkent|Asia/Samarkand", "Asia/Tashkent|Asia/Yekaterinburg", "Asia/Tashkent|Etc/GMT-5", "Asia/Tashkent|Indian/Kerguelen", "Asia/Tashkent|Indian/Maldives", "Asia/Tehran|Iran", "Asia/Tokyo|Japan", "Asia/Vladivostok|Antarctica/DumontDUrville", "Asia/Vladivostok|Asia/Ust-Nera", "Asia/Vladivostok|Etc/GMT-10", "Asia/Vladivostok|Pacific/Chuuk", "Asia/Vladivostok|Pacific/Port_Moresby", "Asia/Vladivostok|Pacific/Truk", "Asia/Vladivostok|Pacific/Yap", "Atlantic/Cape_Verde|Etc/GMT+1", "Australia/Adelaide|Australia/Broken_Hill", "Australia/Adelaide|Australia/South", "Australia/Adelaide|Australia/Yancowinna", "Australia/Brisbane|Australia/Lindeman", "Australia/Brisbane|Australia/Queensland", "Australia/Darwin|Australia/North", "Australia/Lord_Howe|Australia/LHI", "Australia/Perth|Australia/West", "Australia/Sydney|Antarctica/Macquarie", "Australia/Sydney|Australia/ACT", "Australia/Sydney|Australia/Canberra", "Australia/Sydney|Australia/Currie", "Australia/Sydney|Australia/Hobart", "Australia/Sydney|Australia/Melbourne", "Australia/Sydney|Australia/NSW", "Australia/Sydney|Australia/Tasmania", "Australia/Sydney|Australia/Victoria", "Etc/UTC|Etc/UCT", "Etc/UTC|Etc/Universal", "Etc/UTC|Etc/Zulu", "Etc/UTC|UCT", "Etc/UTC|UTC", "Etc/UTC|Universal", "Etc/UTC|Zulu", "Europe/Athens|Asia/Famagusta", "Europe/Athens|Asia/Nicosia", "Europe/Athens|EET", "Europe/Athens|Europe/Bucharest", "Europe/Athens|Europe/Helsinki", "Europe/Athens|Europe/Kiev", "Europe/Athens|Europe/Kyiv", "Europe/Athens|Europe/Mariehamn", "Europe/Athens|Europe/Nicosia", "Europe/Athens|Europe/Riga", "Europe/Athens|Europe/Sofia", "Europe/Athens|Europe/Tallinn", "Europe/Athens|Europe/Uzhgorod", "Europe/Athens|Europe/Vilnius", "Europe/Athens|Europe/Zaporozhye", "Europe/Chisinau|Europe/Tiraspol", "Europe/Dublin|Eire", "Europe/Istanbul|Antarctica/Syowa", "Europe/Istanbul|Asia/Aden", "Europe/Istanbul|Asia/Baghdad", "Europe/Istanbul|Asia/Bahrain", "Europe/Istanbul|Asia/Istanbul", "Europe/Istanbul|Asia/Kuwait", "Europe/Istanbul|Asia/Qatar", "Europe/Istanbul|Asia/Riyadh", "Europe/Istanbul|Etc/GMT-3", "Europe/Istanbul|Europe/Minsk", "Europe/Istanbul|Turkey", "Europe/Lisbon|Atlantic/Canary", "Europe/Lisbon|Atlantic/Faeroe", "Europe/Lisbon|Atlantic/Faroe", "Europe/Lisbon|Atlantic/Madeira", "Europe/Lisbon|Portugal", "Europe/Lisbon|WET", "Europe/London|Europe/Belfast", "Europe/London|Europe/Guernsey", "Europe/London|Europe/Isle_of_Man", "Europe/London|Europe/Jersey", "Europe/London|GB", "Europe/London|GB-Eire", "Europe/Moscow|Europe/Kirov", "Europe/Moscow|Europe/Simferopol", "Europe/Moscow|Europe/Volgograd", "Europe/Moscow|W-SU", "Europe/Paris|Africa/Ceuta", "Europe/Paris|Arctic/Longyearbyen", "Europe/Paris|Atlantic/Jan_Mayen", "Europe/Paris|CET", "Europe/Paris|Europe/Amsterdam", "Europe/Paris|Europe/Andorra", "Europe/Paris|Europe/Belgrade", "Europe/Paris|Europe/Berlin", "Europe/Paris|Europe/Bratislava", "Europe/Paris|Europe/Brussels", "Europe/Paris|Europe/Budapest", "Europe/Paris|Europe/Busingen", "Europe/Paris|Europe/Copenhagen", "Europe/Paris|Europe/Gibraltar", "Europe/Paris|Europe/Ljubljana", "Europe/Paris|Europe/Luxembourg", "Europe/Paris|Europe/Madrid", "Europe/Paris|Europe/Malta", "Europe/Paris|Europe/Monaco", "Europe/Paris|Europe/Oslo", "Europe/Paris|Europe/Podgorica", "Europe/Paris|Europe/Prague", "Europe/Paris|Europe/Rome", "Europe/Paris|Europe/San_Marino", "Europe/Paris|Europe/Sarajevo", "Europe/Paris|Europe/Skopje", "Europe/Paris|Europe/Stockholm", "Europe/Paris|Europe/Tirane", "Europe/Paris|Europe/Vaduz", "Europe/Paris|Europe/Vatican", "Europe/Paris|Europe/Vienna", "Europe/Paris|Europe/Warsaw", "Europe/Paris|Europe/Zagreb", "Europe/Paris|Europe/Zurich", "Europe/Paris|MET", "Europe/Paris|Poland", "Pacific/Auckland|Antarctica/McMurdo", "Pacific/Auckland|Antarctica/South_Pole", "Pacific/Auckland|NZ", "Pacific/Chatham|NZ-CHAT", "Pacific/Easter|Chile/EasterIsland", "Pacific/Galapagos|Etc/GMT+6", "Pacific/Gambier|Etc/GMT+9", "Pacific/Guam|Pacific/Saipan", "Pacific/Honolulu|HST", "Pacific/Honolulu|Pacific/Johnston", "Pacific/Honolulu|US/Hawaii", "Pacific/Kiritimati|Etc/GMT-14", "Pacific/Niue|Etc/GMT+11", "Pacific/Pago_Pago|Pacific/Midway", "Pacific/Pago_Pago|Pacific/Samoa", "Pacific/Pago_Pago|US/Samoa", "Pacific/Pitcairn|Etc/GMT+8", "Pacific/Tahiti|Etc/GMT+10", "Pacific/Tahiti|Pacific/Rarotonga", "Pacific/Tongatapu|Etc/GMT-13", "Pacific/Tongatapu|Pacific/Enderbury", "Pacific/Tongatapu|Pacific/Fakaofo", "Pacific/Tongatapu|Pacific/Kanton"],
	        "countries": ["AD|Europe/Andorra", "AE|Asia/Dubai", "AF|Asia/Kabul", "AG|America/Puerto_Rico America/Antigua", "AI|America/Puerto_Rico America/Anguilla", "AL|Europe/Tirane", "AM|Asia/Yerevan", "AO|Africa/Lagos Africa/Luanda", "AQ|Antarctica/Casey Antarctica/Davis Antarctica/Mawson Antarctica/Palmer Antarctica/Rothera Antarctica/Troll Antarctica/Vostok Pacific/Auckland Pacific/Port_Moresby Asia/Riyadh Asia/Singapore Antarctica/McMurdo Antarctica/DumontDUrville Antarctica/Syowa", "AR|America/Argentina/Buenos_Aires America/Argentina/Cordoba America/Argentina/Salta America/Argentina/Jujuy America/Argentina/Tucuman America/Argentina/Catamarca America/Argentina/La_Rioja America/Argentina/San_Juan America/Argentina/Mendoza America/Argentina/San_Luis America/Argentina/Rio_Gallegos America/Argentina/Ushuaia", "AS|Pacific/Pago_Pago", "AT|Europe/Vienna", "AU|Australia/Lord_Howe Antarctica/Macquarie Australia/Hobart Australia/Melbourne Australia/Sydney Australia/Broken_Hill Australia/Brisbane Australia/Lindeman Australia/Adelaide Australia/Darwin Australia/Perth Australia/Eucla Asia/Tokyo", "AW|America/Puerto_Rico America/Aruba", "AX|Europe/Helsinki Europe/Mariehamn", "AZ|Asia/Baku", "BA|Europe/Belgrade Europe/Sarajevo", "BB|America/Barbados", "BD|Asia/Dhaka", "BE|Europe/Brussels", "BF|Africa/Abidjan Africa/Ouagadougou", "BG|Europe/Sofia", "BH|Asia/Qatar Asia/Bahrain", "BI|Africa/Maputo Africa/Bujumbura", "BJ|Africa/Lagos Africa/Porto-Novo", "BL|America/Puerto_Rico America/St_Barthelemy", "BM|Atlantic/Bermuda", "BN|Asia/Kuching Asia/Brunei", "BO|America/La_Paz", "BQ|America/Puerto_Rico America/Kralendijk", "BR|America/Noronha America/Belem America/Fortaleza America/Recife America/Araguaina America/Maceio America/Bahia America/Sao_Paulo America/Campo_Grande America/Cuiaba America/Santarem America/Porto_Velho America/Boa_Vista America/Manaus America/Eirunepe America/Rio_Branco", "BS|America/Toronto America/Nassau", "BT|Asia/Thimphu", "BW|Africa/Maputo Africa/Gaborone", "BY|Europe/Minsk", "BZ|America/Belize", "CA|America/St_Johns America/Halifax America/Glace_Bay America/Moncton America/Goose_Bay America/Toronto America/Iqaluit America/Winnipeg America/Resolute America/Rankin_Inlet America/Regina America/Swift_Current America/Edmonton America/Cambridge_Bay America/Inuvik America/Vancouver America/Dawson_Creek America/Fort_Nelson America/Whitehorse America/Dawson America/Panama America/Puerto_Rico America/Phoenix America/Blanc-Sablon America/Atikokan America/Creston", "CC|Asia/Yangon Indian/Cocos", "CD|Africa/Maputo Africa/Lagos Africa/Kinshasa Africa/Lubumbashi", "CF|Africa/Lagos Africa/Bangui", "CG|Africa/Lagos Africa/Brazzaville", "CH|Europe/Zurich", "CI|Africa/Abidjan", "CK|Pacific/Rarotonga", "CL|America/Santiago America/Coyhaique America/Punta_Arenas Pacific/Easter", "CM|Africa/Lagos Africa/Douala", "CN|Asia/Shanghai Asia/Urumqi", "CO|America/Bogota", "CR|America/Costa_Rica", "CU|America/Havana", "CV|Atlantic/Cape_Verde", "CW|America/Puerto_Rico America/Curacao", "CX|Asia/Bangkok Indian/Christmas", "CY|Asia/Nicosia Asia/Famagusta", "CZ|Europe/Prague", "DE|Europe/Zurich Europe/Berlin Europe/Busingen", "DJ|Africa/Nairobi Africa/Djibouti", "DK|Europe/Berlin Europe/Copenhagen", "DM|America/Puerto_Rico America/Dominica", "DO|America/Santo_Domingo", "DZ|Africa/Algiers", "EC|America/Guayaquil Pacific/Galapagos", "EE|Europe/Tallinn", "EG|Africa/Cairo", "EH|Africa/El_Aaiun", "ER|Africa/Nairobi Africa/Asmara", "ES|Europe/Madrid Africa/Ceuta Atlantic/Canary", "ET|Africa/Nairobi Africa/Addis_Ababa", "FI|Europe/Helsinki", "FJ|Pacific/Fiji", "FK|Atlantic/Stanley", "FM|Pacific/Kosrae Pacific/Port_Moresby Pacific/Guadalcanal Pacific/Chuuk Pacific/Pohnpei", "FO|Atlantic/Faroe", "FR|Europe/Paris", "GA|Africa/Lagos Africa/Libreville", "GB|Europe/London", "GD|America/Puerto_Rico America/Grenada", "GE|Asia/Tbilisi", "GF|America/Cayenne", "GG|Europe/London Europe/Guernsey", "GH|Africa/Abidjan Africa/Accra", "GI|Europe/Gibraltar", "GL|America/Nuuk America/Danmarkshavn America/Scoresbysund America/Thule", "GM|Africa/Abidjan Africa/Banjul", "GN|Africa/Abidjan Africa/Conakry", "GP|America/Puerto_Rico America/Guadeloupe", "GQ|Africa/Lagos Africa/Malabo", "GR|Europe/Athens", "GS|Atlantic/South_Georgia", "GT|America/Guatemala", "GU|Pacific/Guam", "GW|Africa/Bissau", "GY|America/Guyana", "HK|Asia/Hong_Kong", "HN|America/Tegucigalpa", "HR|Europe/Belgrade Europe/Zagreb", "HT|America/Port-au-Prince", "HU|Europe/Budapest", "ID|Asia/Jakarta Asia/Pontianak Asia/Makassar Asia/Jayapura", "IE|Europe/Dublin", "IL|Asia/Jerusalem", "IM|Europe/London Europe/Isle_of_Man", "IN|Asia/Kolkata", "IO|Indian/Chagos", "IQ|Asia/Baghdad", "IR|Asia/Tehran", "IS|Africa/Abidjan Atlantic/Reykjavik", "IT|Europe/Rome", "JE|Europe/London Europe/Jersey", "JM|America/Jamaica", "JO|Asia/Amman", "JP|Asia/Tokyo", "KE|Africa/Nairobi", "KG|Asia/Bishkek", "KH|Asia/Bangkok Asia/Phnom_Penh", "KI|Pacific/Tarawa Pacific/Kanton Pacific/Kiritimati", "KM|Africa/Nairobi Indian/Comoro", "KN|America/Puerto_Rico America/St_Kitts", "KP|Asia/Pyongyang", "KR|Asia/Seoul", "KW|Asia/Riyadh Asia/Kuwait", "KY|America/Panama America/Cayman", "KZ|Asia/Almaty Asia/Qyzylorda Asia/Qostanay Asia/Aqtobe Asia/Aqtau Asia/Atyrau Asia/Oral", "LA|Asia/Bangkok Asia/Vientiane", "LB|Asia/Beirut", "LC|America/Puerto_Rico America/St_Lucia", "LI|Europe/Zurich Europe/Vaduz", "LK|Asia/Colombo", "LR|Africa/Monrovia", "LS|Africa/Johannesburg Africa/Maseru", "LT|Europe/Vilnius", "LU|Europe/Brussels Europe/Luxembourg", "LV|Europe/Riga", "LY|Africa/Tripoli", "MA|Africa/Casablanca", "MC|Europe/Paris Europe/Monaco", "MD|Europe/Chisinau", "ME|Europe/Belgrade Europe/Podgorica", "MF|America/Puerto_Rico America/Marigot", "MG|Africa/Nairobi Indian/Antananarivo", "MH|Pacific/Tarawa Pacific/Kwajalein Pacific/Majuro", "MK|Europe/Belgrade Europe/Skopje", "ML|Africa/Abidjan Africa/Bamako", "MM|Asia/Yangon", "MN|Asia/Ulaanbaatar Asia/Hovd", "MO|Asia/Macau", "MP|Pacific/Guam Pacific/Saipan", "MQ|America/Martinique", "MR|Africa/Abidjan Africa/Nouakchott", "MS|America/Puerto_Rico America/Montserrat", "MT|Europe/Malta", "MU|Indian/Mauritius", "MV|Indian/Maldives", "MW|Africa/Maputo Africa/Blantyre", "MX|America/Mexico_City America/Cancun America/Merida America/Monterrey America/Matamoros America/Chihuahua America/Ciudad_Juarez America/Ojinaga America/Mazatlan America/Bahia_Banderas America/Hermosillo America/Tijuana", "MY|Asia/Kuching Asia/Singapore Asia/Kuala_Lumpur", "MZ|Africa/Maputo", "NA|Africa/Windhoek", "NC|Pacific/Noumea", "NE|Africa/Lagos Africa/Niamey", "NF|Pacific/Norfolk", "NG|Africa/Lagos", "NI|America/Managua", "NL|Europe/Brussels Europe/Amsterdam", "NO|Europe/Berlin Europe/Oslo", "NP|Asia/Kathmandu", "NR|Pacific/Nauru", "NU|Pacific/Niue", "NZ|Pacific/Auckland Pacific/Chatham", "OM|Asia/Dubai Asia/Muscat", "PA|America/Panama", "PE|America/Lima", "PF|Pacific/Tahiti Pacific/Marquesas Pacific/Gambier", "PG|Pacific/Port_Moresby Pacific/Bougainville", "PH|Asia/Manila", "PK|Asia/Karachi", "PL|Europe/Warsaw", "PM|America/Miquelon", "PN|Pacific/Pitcairn", "PR|America/Puerto_Rico", "PS|Asia/Gaza Asia/Hebron", "PT|Europe/Lisbon Atlantic/Madeira Atlantic/Azores", "PW|Pacific/Palau", "PY|America/Asuncion", "QA|Asia/Qatar", "RE|Asia/Dubai Indian/Reunion", "RO|Europe/Bucharest", "RS|Europe/Belgrade", "RU|Europe/Kaliningrad Europe/Moscow Europe/Simferopol Europe/Kirov Europe/Volgograd Europe/Astrakhan Europe/Saratov Europe/Ulyanovsk Europe/Samara Asia/Yekaterinburg Asia/Omsk Asia/Novosibirsk Asia/Barnaul Asia/Tomsk Asia/Novokuznetsk Asia/Krasnoyarsk Asia/Irkutsk Asia/Chita Asia/Yakutsk Asia/Khandyga Asia/Vladivostok Asia/Ust-Nera Asia/Magadan Asia/Sakhalin Asia/Srednekolymsk Asia/Kamchatka Asia/Anadyr", "RW|Africa/Maputo Africa/Kigali", "SA|Asia/Riyadh", "SB|Pacific/Guadalcanal", "SC|Asia/Dubai Indian/Mahe", "SD|Africa/Khartoum", "SE|Europe/Berlin Europe/Stockholm", "SG|Asia/Singapore", "SH|Africa/Abidjan Atlantic/St_Helena", "SI|Europe/Belgrade Europe/Ljubljana", "SJ|Europe/Berlin Arctic/Longyearbyen", "SK|Europe/Prague Europe/Bratislava", "SL|Africa/Abidjan Africa/Freetown", "SM|Europe/Rome Europe/San_Marino", "SN|Africa/Abidjan Africa/Dakar", "SO|Africa/Nairobi Africa/Mogadishu", "SR|America/Paramaribo", "SS|Africa/Juba", "ST|Africa/Sao_Tome", "SV|America/El_Salvador", "SX|America/Puerto_Rico America/Lower_Princes", "SY|Asia/Damascus", "SZ|Africa/Johannesburg Africa/Mbabane", "TC|America/Grand_Turk", "TD|Africa/Ndjamena", "TF|Asia/Dubai Indian/Maldives Indian/Kerguelen", "TG|Africa/Abidjan Africa/Lome", "TH|Asia/Bangkok", "TJ|Asia/Dushanbe", "TK|Pacific/Fakaofo", "TL|Asia/Dili", "TM|Asia/Ashgabat", "TN|Africa/Tunis", "TO|Pacific/Tongatapu", "TR|Europe/Istanbul", "TT|America/Puerto_Rico America/Port_of_Spain", "TV|Pacific/Tarawa Pacific/Funafuti", "TW|Asia/Taipei", "TZ|Africa/Nairobi Africa/Dar_es_Salaam", "UA|Europe/Simferopol Europe/Kyiv", "UG|Africa/Nairobi Africa/Kampala", "UM|Pacific/Pago_Pago Pacific/Tarawa Pacific/Midway Pacific/Wake", "US|America/New_York America/Detroit America/Kentucky/Louisville America/Kentucky/Monticello America/Indiana/Indianapolis America/Indiana/Vincennes America/Indiana/Winamac America/Indiana/Marengo America/Indiana/Petersburg America/Indiana/Vevay America/Chicago America/Indiana/Tell_City America/Indiana/Knox America/Menominee America/North_Dakota/Center America/North_Dakota/New_Salem America/North_Dakota/Beulah America/Denver America/Boise America/Phoenix America/Los_Angeles America/Anchorage America/Juneau America/Sitka America/Metlakatla America/Yakutat America/Nome America/Adak Pacific/Honolulu", "UY|America/Montevideo", "UZ|Asia/Samarkand Asia/Tashkent", "VA|Europe/Rome Europe/Vatican", "VC|America/Puerto_Rico America/St_Vincent", "VE|America/Caracas", "VG|America/Puerto_Rico America/Tortola", "VI|America/Puerto_Rico America/St_Thomas", "VN|Asia/Bangkok Asia/Ho_Chi_Minh", "VU|Pacific/Efate", "WF|Pacific/Tarawa Pacific/Wallis", "WS|Pacific/Apia", "YE|Asia/Riyadh Asia/Aden", "YT|Africa/Nairobi Indian/Mayotte", "ZA|Africa/Johannesburg", "ZM|Africa/Maputo Africa/Lusaka", "ZW|Africa/Maputo Africa/Harare"]
	      });
	      return moment;
	    });
	  })(momentTimezoneWithData10YearRange$1);
	  return momentTimezoneWithData10YearRange$1.exports;
	}

	requireMomentTimezoneWithData10YearRange();

	var codemirror$1 = {exports: {}};

	var codemirror = codemirror$1.exports;
	var hasRequiredCodemirror;
	function requireCodemirror() {
	  if (hasRequiredCodemirror) return codemirror$1.exports;
	  hasRequiredCodemirror = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    // This is CodeMirror (https://codemirror.net/5), a code editor
	    // implemented in JavaScript on top of the browser's DOM.
	    //
	    // You can find some technical background for some of the code below
	    // at http://marijnhaverbeke.nl/blog/#cm-internals .

	    (function (global, factory) {
	      module.exports = factory() ;
	    })(codemirror, function () {

	      // Kludges for bugs and behavior differences that can't be feature
	      // detected are enabled based on userAgent etc sniffing.
	      var userAgent = navigator.userAgent;
	      var platform = navigator.platform;
	      var gecko = /gecko\/\d/i.test(userAgent);
	      var ie_upto10 = /MSIE \d/.test(userAgent);
	      var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
	      var edge = /Edge\/(\d+)/.exec(userAgent);
	      var ie = ie_upto10 || ie_11up || edge;
	      var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
	      var webkit = !edge && /WebKit\//.test(userAgent);
	      var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
	      var chrome = !edge && /Chrome\/(\d+)/.exec(userAgent);
	      var chrome_version = chrome && +chrome[1];
	      var presto = /Opera\//.test(userAgent);
	      var safari = /Apple Computer/.test(navigator.vendor);
	      var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
	      var phantom = /PhantomJS/.test(userAgent);
	      var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2);
	      var android = /Android/.test(userAgent);
	      // This is woefully incomplete. Suggestions for alternative methods welcome.
	      var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
	      var mac = ios || /Mac/.test(platform);
	      var chromeOS = /\bCrOS\b/.test(userAgent);
	      var windows = /win/i.test(platform);
	      var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
	      if (presto_version) {
	        presto_version = Number(presto_version[1]);
	      }
	      if (presto_version && presto_version >= 15) {
	        presto = false;
	        webkit = true;
	      }
	      // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
	      var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
	      var captureRightClick = gecko || ie && ie_version >= 9;
	      function classTest(cls) {
	        return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*");
	      }
	      var rmClass = function (node, cls) {
	        var current = node.className;
	        var match = classTest(cls).exec(current);
	        if (match) {
	          var after = current.slice(match.index + match[0].length);
	          node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
	        }
	      };
	      function removeChildren(e) {
	        for (var count = e.childNodes.length; count > 0; --count) {
	          e.removeChild(e.firstChild);
	        }
	        return e;
	      }
	      function removeChildrenAndAdd(parent, e) {
	        return removeChildren(parent).appendChild(e);
	      }
	      function elt(tag, content, className, style) {
	        var e = document.createElement(tag);
	        if (className) {
	          e.className = className;
	        }
	        if (style) {
	          e.style.cssText = style;
	        }
	        if (typeof content == "string") {
	          e.appendChild(document.createTextNode(content));
	        } else if (content) {
	          for (var i = 0; i < content.length; ++i) {
	            e.appendChild(content[i]);
	          }
	        }
	        return e;
	      }
	      // wrapper for elt, which removes the elt from the accessibility tree
	      function eltP(tag, content, className, style) {
	        var e = elt(tag, content, className, style);
	        e.setAttribute("role", "presentation");
	        return e;
	      }
	      var range;
	      if (document.createRange) {
	        range = function (node, start, end, endNode) {
	          var r = document.createRange();
	          r.setEnd(endNode || node, end);
	          r.setStart(node, start);
	          return r;
	        };
	      } else {
	        range = function (node, start, end) {
	          var r = document.body.createTextRange();
	          try {
	            r.moveToElementText(node.parentNode);
	          } catch (e) {
	            return r;
	          }
	          r.collapse(true);
	          r.moveEnd("character", end);
	          r.moveStart("character", start);
	          return r;
	        };
	      }
	      function contains(parent, child) {
	        if (child.nodeType == 3)
	          // Android browser always returns false when child is a textnode
	          {
	            child = child.parentNode;
	          }
	        if (parent.contains) {
	          return parent.contains(child);
	        }
	        do {
	          if (child.nodeType == 11) {
	            child = child.host;
	          }
	          if (child == parent) {
	            return true;
	          }
	        } while (child = child.parentNode);
	      }
	      function activeElt(rootNode) {
	        // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
	        // IE < 10 will throw when accessed while the page is loading or in an iframe.
	        // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
	        var doc = rootNode.ownerDocument || rootNode;
	        var activeElement;
	        try {
	          activeElement = rootNode.activeElement;
	        } catch (e) {
	          activeElement = doc.body || null;
	        }
	        while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) {
	          activeElement = activeElement.shadowRoot.activeElement;
	        }
	        return activeElement;
	      }
	      function addClass(node, cls) {
	        var current = node.className;
	        if (!classTest(cls).test(current)) {
	          node.className += (current ? " " : "") + cls;
	        }
	      }
	      function joinClasses(a, b) {
	        var as = a.split(" ");
	        for (var i = 0; i < as.length; i++) {
	          if (as[i] && !classTest(as[i]).test(b)) {
	            b += " " + as[i];
	          }
	        }
	        return b;
	      }
	      var selectInput = function (node) {
	        node.select();
	      };
	      if (ios)
	        // Mobile Safari apparently has a bug where select() is broken.
	        {
	          selectInput = function (node) {
	            node.selectionStart = 0;
	            node.selectionEnd = node.value.length;
	          };
	        } else if (ie)
	        // Suppress mysterious IE10 errors
	        {
	          selectInput = function (node) {
	            try {
	              node.select();
	            } catch (_e) {}
	          };
	        }
	      function doc(cm) {
	        return cm.display.wrapper.ownerDocument;
	      }
	      function root(cm) {
	        return rootNode(cm.display.wrapper);
	      }
	      function rootNode(element) {
	        // Detect modern browsers (2017+).
	        return element.getRootNode ? element.getRootNode() : element.ownerDocument;
	      }
	      function win(cm) {
	        return doc(cm).defaultView;
	      }
	      function bind(f) {
	        var args = Array.prototype.slice.call(arguments, 1);
	        return function () {
	          return f.apply(null, args);
	        };
	      }
	      function copyObj(obj, target, overwrite) {
	        if (!target) {
	          target = {};
	        }
	        for (var prop in obj) {
	          if (Object.prototype.hasOwnProperty.call(obj, prop) && (overwrite !== false || !Object.prototype.hasOwnProperty.call(target, prop))) {
	            target[prop] = obj[prop];
	          }
	        }
	        return target;
	      }

	      // Counts the column offset in a string, taking tabs into account.
	      // Used mostly to find indentation.
	      function countColumn(string, end, tabSize, startIndex, startValue) {
	        if (end == null) {
	          end = string.search(/[^\s\u00a0]/);
	          if (end == -1) {
	            end = string.length;
	          }
	        }
	        for (var i = startIndex || 0, n = startValue || 0;;) {
	          var nextTab = string.indexOf("\t", i);
	          if (nextTab < 0 || nextTab >= end) {
	            return n + (end - i);
	          }
	          n += nextTab - i;
	          n += tabSize - n % tabSize;
	          i = nextTab + 1;
	        }
	      }
	      var Delayed = function () {
	        this.id = null;
	        this.f = null;
	        this.time = 0;
	        this.handler = bind(this.onTimeout, this);
	      };
	      Delayed.prototype.onTimeout = function (self) {
	        self.id = 0;
	        if (self.time <= +new Date()) {
	          self.f();
	        } else {
	          setTimeout(self.handler, self.time - +new Date());
	        }
	      };
	      Delayed.prototype.set = function (ms, f) {
	        this.f = f;
	        var time = +new Date() + ms;
	        if (!this.id || time < this.time) {
	          clearTimeout(this.id);
	          this.id = setTimeout(this.handler, ms);
	          this.time = time;
	        }
	      };
	      function indexOf(array, elt) {
	        for (var i = 0; i < array.length; ++i) {
	          if (array[i] == elt) {
	            return i;
	          }
	        }
	        return -1;
	      }

	      // Number of pixels added to scroller and sizer to hide scrollbar
	      var scrollerGap = 50;

	      // Returned or thrown by various protocols to signal 'I'm not
	      // handling this'.
	      var Pass = {
	        toString: function () {
	          return "CodeMirror.Pass";
	        }
	      };

	      // Reused option objects for setSelection & friends
	      var sel_dontScroll = {
	          scroll: false
	        },
	        sel_mouse = {
	          origin: "*mouse"
	        },
	        sel_move = {
	          origin: "+move"
	        };

	      // The inverse of countColumn -- find the offset that corresponds to
	      // a particular column.
	      function findColumn(string, goal, tabSize) {
	        for (var pos = 0, col = 0;;) {
	          var nextTab = string.indexOf("\t", pos);
	          if (nextTab == -1) {
	            nextTab = string.length;
	          }
	          var skipped = nextTab - pos;
	          if (nextTab == string.length || col + skipped >= goal) {
	            return pos + Math.min(skipped, goal - col);
	          }
	          col += nextTab - pos;
	          col += tabSize - col % tabSize;
	          pos = nextTab + 1;
	          if (col >= goal) {
	            return pos;
	          }
	        }
	      }
	      var spaceStrs = [""];
	      function spaceStr(n) {
	        while (spaceStrs.length <= n) {
	          spaceStrs.push(lst(spaceStrs) + " ");
	        }
	        return spaceStrs[n];
	      }
	      function lst(arr) {
	        return arr[arr.length - 1];
	      }
	      function map(array, f) {
	        var out = [];
	        for (var i = 0; i < array.length; i++) {
	          out[i] = f(array[i], i);
	        }
	        return out;
	      }
	      function insertSorted(array, value, score) {
	        var pos = 0,
	          priority = score(value);
	        while (pos < array.length && score(array[pos]) <= priority) {
	          pos++;
	        }
	        array.splice(pos, 0, value);
	      }
	      function nothing() {}
	      function createObj(base, props) {
	        var inst;
	        if (Object.create) {
	          inst = Object.create(base);
	        } else {
	          nothing.prototype = base;
	          inst = new nothing();
	        }
	        if (props) {
	          copyObj(props, inst);
	        }
	        return inst;
	      }
	      var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
	      function isWordCharBasic(ch) {
	        return /\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
	      }
	      function isWordChar(ch, helper) {
	        if (!helper) {
	          return isWordCharBasic(ch);
	        }
	        if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) {
	          return true;
	        }
	        return helper.test(ch);
	      }
	      function isEmpty(obj) {
	        for (var n in obj) {
	          if (obj.hasOwnProperty(n) && obj[n]) {
	            return false;
	          }
	        }
	        return true;
	      }

	      // Extending unicode characters. A series of a non-extending char +
	      // any number of extending chars is treated as a single unit as far
	      // as editing and measuring is concerned. This is not fully correct,
	      // since some scripts/fonts/browsers also treat other configurations
	      // of code points as a group.
	      var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
	      function isExtendingChar(ch) {
	        return ch.charCodeAt(0) >= 768 && extendingChars.test(ch);
	      }

	      // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
	      function skipExtendingChars(str, pos, dir) {
	        while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) {
	          pos += dir;
	        }
	        return pos;
	      }

	      // Returns the value from the range [`from`; `to`] that satisfies
	      // `pred` and is closest to `from`. Assumes that at least `to`
	      // satisfies `pred`. Supports `from` being greater than `to`.
	      function findFirst(pred, from, to) {
	        // At any point we are certain `to` satisfies `pred`, don't know
	        // whether `from` does.
	        var dir = from > to ? -1 : 1;
	        for (;;) {
	          if (from == to) {
	            return from;
	          }
	          var midF = (from + to) / 2,
	            mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
	          if (mid == from) {
	            return pred(mid) ? from : to;
	          }
	          if (pred(mid)) {
	            to = mid;
	          } else {
	            from = mid + dir;
	          }
	        }
	      }

	      // BIDI HELPERS

	      function iterateBidiSections(order, from, to, f) {
	        if (!order) {
	          return f(from, to, "ltr", 0);
	        }
	        var found = false;
	        for (var i = 0; i < order.length; ++i) {
	          var part = order[i];
	          if (part.from < to && part.to > from || from == to && part.to == from) {
	            f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
	            found = true;
	          }
	        }
	        if (!found) {
	          f(from, to, "ltr");
	        }
	      }
	      var bidiOther = null;
	      function getBidiPartAt(order, ch, sticky) {
	        var found;
	        bidiOther = null;
	        for (var i = 0; i < order.length; ++i) {
	          var cur = order[i];
	          if (cur.from < ch && cur.to > ch) {
	            return i;
	          }
	          if (cur.to == ch) {
	            if (cur.from != cur.to && sticky == "before") {
	              found = i;
	            } else {
	              bidiOther = i;
	            }
	          }
	          if (cur.from == ch) {
	            if (cur.from != cur.to && sticky != "before") {
	              found = i;
	            } else {
	              bidiOther = i;
	            }
	          }
	        }
	        return found != null ? found : bidiOther;
	      }

	      // Bidirectional ordering algorithm
	      // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
	      // that this (partially) implements.

	      // One-char codes used for character types:
	      // L (L):   Left-to-Right
	      // R (R):   Right-to-Left
	      // r (AL):  Right-to-Left Arabic
	      // 1 (EN):  European Number
	      // + (ES):  European Number Separator
	      // % (ET):  European Number Terminator
	      // n (AN):  Arabic Number
	      // , (CS):  Common Number Separator
	      // m (NSM): Non-Spacing Mark
	      // b (BN):  Boundary Neutral
	      // s (B):   Paragraph Separator
	      // t (S):   Segment Separator
	      // w (WS):  Whitespace
	      // N (ON):  Other Neutrals

	      // Returns null if characters are ordered as they appear
	      // (left-to-right), or an array of sections ({from, to, level}
	      // objects) in the order in which they occur visually.
	      var bidiOrdering = function () {
	        // Character types for codepoints 0 to 0xff
	        var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
	        // Character types for codepoints 0x600 to 0x6f9
	        var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
	        function charType(code) {
	          if (code <= 0xf7) {
	            return lowTypes.charAt(code);
	          } else if (0x590 <= code && code <= 0x5f4) {
	            return "R";
	          } else if (0x600 <= code && code <= 0x6f9) {
	            return arabicTypes.charAt(code - 0x600);
	          } else if (0x6ee <= code && code <= 0x8ac) {
	            return "r";
	          } else if (0x2000 <= code && code <= 0x200b) {
	            return "w";
	          } else if (code == 0x200c) {
	            return "b";
	          } else {
	            return "L";
	          }
	        }
	        var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
	        var isNeutral = /[stwN]/,
	          isStrong = /[LRr]/,
	          countsAsLeft = /[Lb1n]/,
	          countsAsNum = /[1n]/;
	        function BidiSpan(level, from, to) {
	          this.level = level;
	          this.from = from;
	          this.to = to;
	        }
	        return function (str, direction) {
	          var outerType = direction == "ltr" ? "L" : "R";
	          if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) {
	            return false;
	          }
	          var len = str.length,
	            types = [];
	          for (var i = 0; i < len; ++i) {
	            types.push(charType(str.charCodeAt(i)));
	          }

	          // W1. Examine each non-spacing mark (NSM) in the level run, and
	          // change the type of the NSM to the type of the previous
	          // character. If the NSM is at the start of the level run, it will
	          // get the type of sor.
	          for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
	            var type = types[i$1];
	            if (type == "m") {
	              types[i$1] = prev;
	            } else {
	              prev = type;
	            }
	          }

	          // W2. Search backwards from each instance of a European number
	          // until the first strong type (R, L, AL, or sor) is found. If an
	          // AL is found, change the type of the European number to Arabic
	          // number.
	          // W3. Change all ALs to R.
	          for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
	            var type$1 = types[i$2];
	            if (type$1 == "1" && cur == "r") {
	              types[i$2] = "n";
	            } else if (isStrong.test(type$1)) {
	              cur = type$1;
	              if (type$1 == "r") {
	                types[i$2] = "R";
	              }
	            }
	          }

	          // W4. A single European separator between two European numbers
	          // changes to a European number. A single common separator between
	          // two numbers of the same type changes to that type.
	          for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
	            var type$2 = types[i$3];
	            if (type$2 == "+" && prev$1 == "1" && types[i$3 + 1] == "1") {
	              types[i$3] = "1";
	            } else if (type$2 == "," && prev$1 == types[i$3 + 1] && (prev$1 == "1" || prev$1 == "n")) {
	              types[i$3] = prev$1;
	            }
	            prev$1 = type$2;
	          }

	          // W5. A sequence of European terminators adjacent to European
	          // numbers changes to all European numbers.
	          // W6. Otherwise, separators and terminators change to Other
	          // Neutral.
	          for (var i$4 = 0; i$4 < len; ++i$4) {
	            var type$3 = types[i$4];
	            if (type$3 == ",") {
	              types[i$4] = "N";
	            } else if (type$3 == "%") {
	              var end = void 0;
	              for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
	              var replace = i$4 && types[i$4 - 1] == "!" || end < len && types[end] == "1" ? "1" : "N";
	              for (var j = i$4; j < end; ++j) {
	                types[j] = replace;
	              }
	              i$4 = end - 1;
	            }
	          }

	          // W7. Search backwards from each instance of a European number
	          // until the first strong type (R, L, or sor) is found. If an L is
	          // found, then change the type of the European number to L.
	          for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
	            var type$4 = types[i$5];
	            if (cur$1 == "L" && type$4 == "1") {
	              types[i$5] = "L";
	            } else if (isStrong.test(type$4)) {
	              cur$1 = type$4;
	            }
	          }

	          // N1. A sequence of neutrals takes the direction of the
	          // surrounding strong text if the text on both sides has the same
	          // direction. European and Arabic numbers act as if they were R in
	          // terms of their influence on neutrals. Start-of-level-run (sor)
	          // and end-of-level-run (eor) are used at level run boundaries.
	          // N2. Any remaining neutrals take the embedding direction.
	          for (var i$6 = 0; i$6 < len; ++i$6) {
	            if (isNeutral.test(types[i$6])) {
	              var end$1 = void 0;
	              for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
	              var before = (i$6 ? types[i$6 - 1] : outerType) == "L";
	              var after = (end$1 < len ? types[end$1] : outerType) == "L";
	              var replace$1 = before == after ? before ? "L" : "R" : outerType;
	              for (var j$1 = i$6; j$1 < end$1; ++j$1) {
	                types[j$1] = replace$1;
	              }
	              i$6 = end$1 - 1;
	            }
	          }

	          // Here we depart from the documented algorithm, in order to avoid
	          // building up an actual levels array. Since there are only three
	          // levels (0, 1, 2) in an implementation that doesn't take
	          // explicit embedding into account, we can build up the order on
	          // the fly, without following the level-based algorithm.
	          var order = [],
	            m;
	          for (var i$7 = 0; i$7 < len;) {
	            if (countsAsLeft.test(types[i$7])) {
	              var start = i$7;
	              for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
	              order.push(new BidiSpan(0, start, i$7));
	            } else {
	              var pos = i$7,
	                at = order.length,
	                isRTL = direction == "rtl" ? 1 : 0;
	              for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
	              for (var j$2 = pos; j$2 < i$7;) {
	                if (countsAsNum.test(types[j$2])) {
	                  if (pos < j$2) {
	                    order.splice(at, 0, new BidiSpan(1, pos, j$2));
	                    at += isRTL;
	                  }
	                  var nstart = j$2;
	                  for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
	                  order.splice(at, 0, new BidiSpan(2, nstart, j$2));
	                  at += isRTL;
	                  pos = j$2;
	                } else {
	                  ++j$2;
	                }
	              }
	              if (pos < i$7) {
	                order.splice(at, 0, new BidiSpan(1, pos, i$7));
	              }
	            }
	          }
	          if (direction == "ltr") {
	            if (order[0].level == 1 && (m = str.match(/^\s+/))) {
	              order[0].from = m[0].length;
	              order.unshift(new BidiSpan(0, 0, m[0].length));
	            }
	            if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
	              lst(order).to -= m[0].length;
	              order.push(new BidiSpan(0, len - m[0].length, len));
	            }
	          }
	          return direction == "rtl" ? order.reverse() : order;
	        };
	      }();

	      // Get the bidi ordering for the given line (and cache it). Returns
	      // false for lines that are fully left-to-right, and an array of
	      // BidiSpan objects otherwise.
	      function getOrder(line, direction) {
	        var order = line.order;
	        if (order == null) {
	          order = line.order = bidiOrdering(line.text, direction);
	        }
	        return order;
	      }

	      // EVENT HANDLING

	      // Lightweight event framework. on/off also work on DOM nodes,
	      // registering native DOM handlers.

	      var noHandlers = [];
	      var on = function (emitter, type, f) {
	        if (emitter.addEventListener) {
	          emitter.addEventListener(type, f, false);
	        } else if (emitter.attachEvent) {
	          emitter.attachEvent("on" + type, f);
	        } else {
	          var map = emitter._handlers || (emitter._handlers = {});
	          map[type] = (map[type] || noHandlers).concat(f);
	        }
	      };
	      function getHandlers(emitter, type) {
	        return emitter._handlers && emitter._handlers[type] || noHandlers;
	      }
	      function off(emitter, type, f) {
	        if (emitter.removeEventListener) {
	          emitter.removeEventListener(type, f, false);
	        } else if (emitter.detachEvent) {
	          emitter.detachEvent("on" + type, f);
	        } else {
	          var map = emitter._handlers,
	            arr = map && map[type];
	          if (arr) {
	            var index = indexOf(arr, f);
	            if (index > -1) {
	              map[type] = arr.slice(0, index).concat(arr.slice(index + 1));
	            }
	          }
	        }
	      }
	      function signal(emitter, type /*, values...*/) {
	        var handlers = getHandlers(emitter, type);
	        if (!handlers.length) {
	          return;
	        }
	        var args = Array.prototype.slice.call(arguments, 2);
	        for (var i = 0; i < handlers.length; ++i) {
	          handlers[i].apply(null, args);
	        }
	      }

	      // The DOM events that CodeMirror handles can be overridden by
	      // registering a (non-DOM) handler on the editor for the event name,
	      // and preventDefault-ing the event in that handler.
	      function signalDOMEvent(cm, e, override) {
	        if (typeof e == "string") {
	          e = {
	            type: e,
	            preventDefault: function () {
	              this.defaultPrevented = true;
	            }
	          };
	        }
	        signal(cm, override || e.type, cm, e);
	        return e_defaultPrevented(e) || e.codemirrorIgnore;
	      }
	      function signalCursorActivity(cm) {
	        var arr = cm._handlers && cm._handlers.cursorActivity;
	        if (!arr) {
	          return;
	        }
	        var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
	        for (var i = 0; i < arr.length; ++i) {
	          if (indexOf(set, arr[i]) == -1) {
	            set.push(arr[i]);
	          }
	        }
	      }
	      function hasHandler(emitter, type) {
	        return getHandlers(emitter, type).length > 0;
	      }

	      // Add on and off methods to a constructor's prototype, to make
	      // registering events on such objects more convenient.
	      function eventMixin(ctor) {
	        ctor.prototype.on = function (type, f) {
	          on(this, type, f);
	        };
	        ctor.prototype.off = function (type, f) {
	          off(this, type, f);
	        };
	      }

	      // Due to the fact that we still support jurassic IE versions, some
	      // compatibility wrappers are needed.

	      function e_preventDefault(e) {
	        if (e.preventDefault) {
	          e.preventDefault();
	        } else {
	          e.returnValue = false;
	        }
	      }
	      function e_stopPropagation(e) {
	        if (e.stopPropagation) {
	          e.stopPropagation();
	        } else {
	          e.cancelBubble = true;
	        }
	      }
	      function e_defaultPrevented(e) {
	        return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
	      }
	      function e_stop(e) {
	        e_preventDefault(e);
	        e_stopPropagation(e);
	      }
	      function e_target(e) {
	        return e.target || e.srcElement;
	      }
	      function e_button(e) {
	        var b = e.which;
	        if (b == null) {
	          if (e.button & 1) {
	            b = 1;
	          } else if (e.button & 2) {
	            b = 3;
	          } else if (e.button & 4) {
	            b = 2;
	          }
	        }
	        if (mac && e.ctrlKey && b == 1) {
	          b = 3;
	        }
	        return b;
	      }

	      // Detect drag-and-drop
	      var dragAndDrop = function () {
	        // There is *some* kind of drag-and-drop support in IE6-8, but I
	        // couldn't get it to work yet.
	        if (ie && ie_version < 9) {
	          return false;
	        }
	        var div = elt('div');
	        return "draggable" in div || "dragDrop" in div;
	      }();
	      var zwspSupported;
	      function zeroWidthElement(measure) {
	        if (zwspSupported == null) {
	          var test = elt("span", "\u200b");
	          removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
	          if (measure.firstChild.offsetHeight != 0) {
	            zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
	          }
	        }
	        var node = zwspSupported ? elt("span", "\u200b") : elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
	        node.setAttribute("cm-text", "");
	        return node;
	      }

	      // Feature-detect IE's crummy client rect reporting for bidi text
	      var badBidiRects;
	      function hasBadBidiRects(measure) {
	        if (badBidiRects != null) {
	          return badBidiRects;
	        }
	        var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
	        var r0 = range(txt, 0, 1).getBoundingClientRect();
	        var r1 = range(txt, 1, 2).getBoundingClientRect();
	        removeChildren(measure);
	        if (!r0 || r0.left == r0.right) {
	          return false;
	        } // Safari returns null in some cases (#2780)
	        return badBidiRects = r1.right - r0.right < 3;
	      }

	      // See if "".split is the broken IE version, if so, provide an
	      // alternative way to split lines.
	      var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
	        var pos = 0,
	          result = [],
	          l = string.length;
	        while (pos <= l) {
	          var nl = string.indexOf("\n", pos);
	          if (nl == -1) {
	            nl = string.length;
	          }
	          var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
	          var rt = line.indexOf("\r");
	          if (rt != -1) {
	            result.push(line.slice(0, rt));
	            pos += rt + 1;
	          } else {
	            result.push(line);
	            pos = nl + 1;
	          }
	        }
	        return result;
	      } : function (string) {
	        return string.split(/\r\n?|\n/);
	      };
	      var hasSelection = window.getSelection ? function (te) {
	        try {
	          return te.selectionStart != te.selectionEnd;
	        } catch (e) {
	          return false;
	        }
	      } : function (te) {
	        var range;
	        try {
	          range = te.ownerDocument.selection.createRange();
	        } catch (e) {}
	        if (!range || range.parentElement() != te) {
	          return false;
	        }
	        return range.compareEndPoints("StartToEnd", range) != 0;
	      };
	      var hasCopyEvent = function () {
	        var e = elt("div");
	        if ("oncopy" in e) {
	          return true;
	        }
	        e.setAttribute("oncopy", "return;");
	        return typeof e.oncopy == "function";
	      }();
	      var badZoomedRects = null;
	      function hasBadZoomedRects(measure) {
	        if (badZoomedRects != null) {
	          return badZoomedRects;
	        }
	        var node = removeChildrenAndAdd(measure, elt("span", "x"));
	        var normal = node.getBoundingClientRect();
	        var fromRange = range(node, 0, 1).getBoundingClientRect();
	        return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
	      }

	      // Known modes, by name and by MIME
	      var modes = {},
	        mimeModes = {};

	      // Extra arguments are stored as the mode's dependencies, which is
	      // used by (legacy) mechanisms like loadmode.js to automatically
	      // load a mode. (Preferred mechanism is the require/define calls.)
	      function defineMode(name, mode) {
	        if (arguments.length > 2) {
	          mode.dependencies = Array.prototype.slice.call(arguments, 2);
	        }
	        modes[name] = mode;
	      }
	      function defineMIME(mime, spec) {
	        mimeModes[mime] = spec;
	      }

	      // Given a MIME type, a {name, ...options} config object, or a name
	      // string, return a mode config object.
	      function resolveMode(spec) {
	        if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
	          spec = mimeModes[spec];
	        } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
	          var found = mimeModes[spec.name];
	          if (typeof found == "string") {
	            found = {
	              name: found
	            };
	          }
	          spec = createObj(found, spec);
	          spec.name = found.name;
	        } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
	          return resolveMode("application/xml");
	        } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
	          return resolveMode("application/json");
	        }
	        if (typeof spec == "string") {
	          return {
	            name: spec
	          };
	        } else {
	          return spec || {
	            name: "null"
	          };
	        }
	      }

	      // Given a mode spec (anything that resolveMode accepts), find and
	      // initialize an actual mode object.
	      function getMode(options, spec) {
	        spec = resolveMode(spec);
	        var mfactory = modes[spec.name];
	        if (!mfactory) {
	          return getMode(options, "text/plain");
	        }
	        var modeObj = mfactory(options, spec);
	        if (modeExtensions.hasOwnProperty(spec.name)) {
	          var exts = modeExtensions[spec.name];
	          for (var prop in exts) {
	            if (!exts.hasOwnProperty(prop)) {
	              continue;
	            }
	            if (modeObj.hasOwnProperty(prop)) {
	              modeObj["_" + prop] = modeObj[prop];
	            }
	            modeObj[prop] = exts[prop];
	          }
	        }
	        modeObj.name = spec.name;
	        if (spec.helperType) {
	          modeObj.helperType = spec.helperType;
	        }
	        if (spec.modeProps) {
	          for (var prop$1 in spec.modeProps) {
	            modeObj[prop$1] = spec.modeProps[prop$1];
	          }
	        }
	        return modeObj;
	      }

	      // This can be used to attach properties to mode objects from
	      // outside the actual mode definition.
	      var modeExtensions = {};
	      function extendMode(mode, properties) {
	        var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : modeExtensions[mode] = {};
	        copyObj(properties, exts);
	      }
	      function copyState(mode, state) {
	        if (state === true) {
	          return state;
	        }
	        if (mode.copyState) {
	          return mode.copyState(state);
	        }
	        var nstate = {};
	        for (var n in state) {
	          var val = state[n];
	          if (val instanceof Array) {
	            val = val.concat([]);
	          }
	          nstate[n] = val;
	        }
	        return nstate;
	      }

	      // Given a mode and a state (for that mode), find the inner mode and
	      // state at the position that the state refers to.
	      function innerMode(mode, state) {
	        var info;
	        while (mode.innerMode) {
	          info = mode.innerMode(state);
	          if (!info || info.mode == mode) {
	            break;
	          }
	          state = info.state;
	          mode = info.mode;
	        }
	        return info || {
	          mode: mode,
	          state: state
	        };
	      }
	      function startState(mode, a1, a2) {
	        return mode.startState ? mode.startState(a1, a2) : true;
	      }

	      // STRING STREAM

	      // Fed to the mode parsers, provides helper functions to make
	      // parsers more succinct.

	      var StringStream = function (string, tabSize, lineOracle) {
	        this.pos = this.start = 0;
	        this.string = string;
	        this.tabSize = tabSize || 8;
	        this.lastColumnPos = this.lastColumnValue = 0;
	        this.lineStart = 0;
	        this.lineOracle = lineOracle;
	      };
	      StringStream.prototype.eol = function () {
	        return this.pos >= this.string.length;
	      };
	      StringStream.prototype.sol = function () {
	        return this.pos == this.lineStart;
	      };
	      StringStream.prototype.peek = function () {
	        return this.string.charAt(this.pos) || undefined;
	      };
	      StringStream.prototype.next = function () {
	        if (this.pos < this.string.length) {
	          return this.string.charAt(this.pos++);
	        }
	      };
	      StringStream.prototype.eat = function (match) {
	        var ch = this.string.charAt(this.pos);
	        var ok;
	        if (typeof match == "string") {
	          ok = ch == match;
	        } else {
	          ok = ch && (match.test ? match.test(ch) : match(ch));
	        }
	        if (ok) {
	          ++this.pos;
	          return ch;
	        }
	      };
	      StringStream.prototype.eatWhile = function (match) {
	        var start = this.pos;
	        while (this.eat(match)) {}
	        return this.pos > start;
	      };
	      StringStream.prototype.eatSpace = function () {
	        var start = this.pos;
	        while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) {
	          ++this.pos;
	        }
	        return this.pos > start;
	      };
	      StringStream.prototype.skipToEnd = function () {
	        this.pos = this.string.length;
	      };
	      StringStream.prototype.skipTo = function (ch) {
	        var found = this.string.indexOf(ch, this.pos);
	        if (found > -1) {
	          this.pos = found;
	          return true;
	        }
	      };
	      StringStream.prototype.backUp = function (n) {
	        this.pos -= n;
	      };
	      StringStream.prototype.column = function () {
	        if (this.lastColumnPos < this.start) {
	          this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
	          this.lastColumnPos = this.start;
	        }
	        return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
	      };
	      StringStream.prototype.indentation = function () {
	        return countColumn(this.string, null, this.tabSize) - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
	      };
	      StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
	        if (typeof pattern == "string") {
	          var cased = function (str) {
	            return caseInsensitive ? str.toLowerCase() : str;
	          };
	          var substr = this.string.substr(this.pos, pattern.length);
	          if (cased(substr) == cased(pattern)) {
	            if (consume !== false) {
	              this.pos += pattern.length;
	            }
	            return true;
	          }
	        } else {
	          var match = this.string.slice(this.pos).match(pattern);
	          if (match && match.index > 0) {
	            return null;
	          }
	          if (match && consume !== false) {
	            this.pos += match[0].length;
	          }
	          return match;
	        }
	      };
	      StringStream.prototype.current = function () {
	        return this.string.slice(this.start, this.pos);
	      };
	      StringStream.prototype.hideFirstChars = function (n, inner) {
	        this.lineStart += n;
	        try {
	          return inner();
	        } finally {
	          this.lineStart -= n;
	        }
	      };
	      StringStream.prototype.lookAhead = function (n) {
	        var oracle = this.lineOracle;
	        return oracle && oracle.lookAhead(n);
	      };
	      StringStream.prototype.baseToken = function () {
	        var oracle = this.lineOracle;
	        return oracle && oracle.baseToken(this.pos);
	      };

	      // Find the line object corresponding to the given line number.
	      function getLine(doc, n) {
	        n -= doc.first;
	        if (n < 0 || n >= doc.size) {
	          throw new Error("There is no line " + (n + doc.first) + " in the document.");
	        }
	        var chunk = doc;
	        while (!chunk.lines) {
	          for (var i = 0;; ++i) {
	            var child = chunk.children[i],
	              sz = child.chunkSize();
	            if (n < sz) {
	              chunk = child;
	              break;
	            }
	            n -= sz;
	          }
	        }
	        return chunk.lines[n];
	      }

	      // Get the part of a document between two positions, as an array of
	      // strings.
	      function getBetween(doc, start, end) {
	        var out = [],
	          n = start.line;
	        doc.iter(start.line, end.line + 1, function (line) {
	          var text = line.text;
	          if (n == end.line) {
	            text = text.slice(0, end.ch);
	          }
	          if (n == start.line) {
	            text = text.slice(start.ch);
	          }
	          out.push(text);
	          ++n;
	        });
	        return out;
	      }
	      // Get the lines between from and to, as array of strings.
	      function getLines(doc, from, to) {
	        var out = [];
	        doc.iter(from, to, function (line) {
	          out.push(line.text);
	        }); // iter aborts when callback returns truthy value
	        return out;
	      }

	      // Update the height of a line, propagating the height change
	      // upwards to parent nodes.
	      function updateLineHeight(line, height) {
	        var diff = height - line.height;
	        if (diff) {
	          for (var n = line; n; n = n.parent) {
	            n.height += diff;
	          }
	        }
	      }

	      // Given a line object, find its line number by walking up through
	      // its parent links.
	      function lineNo(line) {
	        if (line.parent == null) {
	          return null;
	        }
	        var cur = line.parent,
	          no = indexOf(cur.lines, line);
	        for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
	          for (var i = 0;; ++i) {
	            if (chunk.children[i] == cur) {
	              break;
	            }
	            no += chunk.children[i].chunkSize();
	          }
	        }
	        return no + cur.first;
	      }

	      // Find the line at the given vertical position, using the height
	      // information in the document tree.
	      function lineAtHeight(chunk, h) {
	        var n = chunk.first;
	        outer: do {
	          for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
	            var child = chunk.children[i$1],
	              ch = child.height;
	            if (h < ch) {
	              chunk = child;
	              continue outer;
	            }
	            h -= ch;
	            n += child.chunkSize();
	          }
	          return n;
	        } while (!chunk.lines);
	        var i = 0;
	        for (; i < chunk.lines.length; ++i) {
	          var line = chunk.lines[i],
	            lh = line.height;
	          if (h < lh) {
	            break;
	          }
	          h -= lh;
	        }
	        return n + i;
	      }
	      function isLine(doc, l) {
	        return l >= doc.first && l < doc.first + doc.size;
	      }
	      function lineNumberFor(options, i) {
	        return String(options.lineNumberFormatter(i + options.firstLineNumber));
	      }

	      // A Pos instance represents a position within the text.
	      function Pos(line, ch, sticky) {
	        if (sticky === void 0) sticky = null;
	        if (!(this instanceof Pos)) {
	          return new Pos(line, ch, sticky);
	        }
	        this.line = line;
	        this.ch = ch;
	        this.sticky = sticky;
	      }

	      // Compare two positions, return 0 if they are the same, a negative
	      // number when a is less, and a positive number otherwise.
	      function cmp(a, b) {
	        return a.line - b.line || a.ch - b.ch;
	      }
	      function equalCursorPos(a, b) {
	        return a.sticky == b.sticky && cmp(a, b) == 0;
	      }
	      function copyPos(x) {
	        return Pos(x.line, x.ch);
	      }
	      function maxPos(a, b) {
	        return cmp(a, b) < 0 ? b : a;
	      }
	      function minPos(a, b) {
	        return cmp(a, b) < 0 ? a : b;
	      }

	      // Most of the external API clips given positions to make sure they
	      // actually exist within the document.
	      function clipLine(doc, n) {
	        return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));
	      }
	      function clipPos(doc, pos) {
	        if (pos.line < doc.first) {
	          return Pos(doc.first, 0);
	        }
	        var last = doc.first + doc.size - 1;
	        if (pos.line > last) {
	          return Pos(last, getLine(doc, last).text.length);
	        }
	        return clipToLen(pos, getLine(doc, pos.line).text.length);
	      }
	      function clipToLen(pos, linelen) {
	        var ch = pos.ch;
	        if (ch == null || ch > linelen) {
	          return Pos(pos.line, linelen);
	        } else if (ch < 0) {
	          return Pos(pos.line, 0);
	        } else {
	          return pos;
	        }
	      }
	      function clipPosArray(doc, array) {
	        var out = [];
	        for (var i = 0; i < array.length; i++) {
	          out[i] = clipPos(doc, array[i]);
	        }
	        return out;
	      }
	      var SavedContext = function (state, lookAhead) {
	        this.state = state;
	        this.lookAhead = lookAhead;
	      };
	      var Context = function (doc, state, line, lookAhead) {
	        this.state = state;
	        this.doc = doc;
	        this.line = line;
	        this.maxLookAhead = lookAhead || 0;
	        this.baseTokens = null;
	        this.baseTokenPos = 1;
	      };
	      Context.prototype.lookAhead = function (n) {
	        var line = this.doc.getLine(this.line + n);
	        if (line != null && n > this.maxLookAhead) {
	          this.maxLookAhead = n;
	        }
	        return line;
	      };
	      Context.prototype.baseToken = function (n) {
	        if (!this.baseTokens) {
	          return null;
	        }
	        while (this.baseTokens[this.baseTokenPos] <= n) {
	          this.baseTokenPos += 2;
	        }
	        var type = this.baseTokens[this.baseTokenPos + 1];
	        return {
	          type: type && type.replace(/( |^)overlay .*/, ""),
	          size: this.baseTokens[this.baseTokenPos] - n
	        };
	      };
	      Context.prototype.nextLine = function () {
	        this.line++;
	        if (this.maxLookAhead > 0) {
	          this.maxLookAhead--;
	        }
	      };
	      Context.fromSaved = function (doc, saved, line) {
	        if (saved instanceof SavedContext) {
	          return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead);
	        } else {
	          return new Context(doc, copyState(doc.mode, saved), line);
	        }
	      };
	      Context.prototype.save = function (copy) {
	        var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
	        return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state;
	      };

	      // Compute a style array (an array starting with a mode generation
	      // -- for invalidation -- followed by pairs of end positions and
	      // style strings), which is used to highlight the tokens on the
	      // line.
	      function highlightLine(cm, line, context, forceToEnd) {
	        // A styles array always starts with a number identifying the
	        // mode/overlays that it is based on (for easy invalidation).
	        var st = [cm.state.modeGen],
	          lineClasses = {};
	        // Compute the base array of styles
	        runMode(cm, line.text, cm.doc.mode, context, function (end, style) {
	          return st.push(end, style);
	        }, lineClasses, forceToEnd);
	        var state = context.state;

	        // Run overlays, adjust style array.
	        var loop = function (o) {
	          context.baseTokens = st;
	          var overlay = cm.state.overlays[o],
	            i = 1,
	            at = 0;
	          context.state = true;
	          runMode(cm, line.text, overlay.mode, context, function (end, style) {
	            var start = i;
	            // Ensure there's a token end at the current position, and that i points at it
	            while (at < end) {
	              var i_end = st[i];
	              if (i_end > end) {
	                st.splice(i, 1, end, st[i + 1], i_end);
	              }
	              i += 2;
	              at = Math.min(end, i_end);
	            }
	            if (!style) {
	              return;
	            }
	            if (overlay.opaque) {
	              st.splice(start, i - start, end, "overlay " + style);
	              i = start + 2;
	            } else {
	              for (; start < i; start += 2) {
	                var cur = st[start + 1];
	                st[start + 1] = (cur ? cur + " " : "") + "overlay " + style;
	              }
	            }
	          }, lineClasses);
	          context.state = state;
	          context.baseTokens = null;
	          context.baseTokenPos = 1;
	        };
	        for (var o = 0; o < cm.state.overlays.length; ++o) loop(o);
	        return {
	          styles: st,
	          classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null
	        };
	      }
	      function getLineStyles(cm, line, updateFrontier) {
	        if (!line.styles || line.styles[0] != cm.state.modeGen) {
	          var context = getContextBefore(cm, lineNo(line));
	          var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
	          var result = highlightLine(cm, line, context);
	          if (resetState) {
	            context.state = resetState;
	          }
	          line.stateAfter = context.save(!resetState);
	          line.styles = result.styles;
	          if (result.classes) {
	            line.styleClasses = result.classes;
	          } else if (line.styleClasses) {
	            line.styleClasses = null;
	          }
	          if (updateFrontier === cm.doc.highlightFrontier) {
	            cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier);
	          }
	        }
	        return line.styles;
	      }
	      function getContextBefore(cm, n, precise) {
	        var doc = cm.doc,
	          display = cm.display;
	        if (!doc.mode.startState) {
	          return new Context(doc, true, n);
	        }
	        var start = findStartLine(cm, n, precise);
	        var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
	        var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
	        doc.iter(start, n, function (line) {
	          processLine(cm, line.text, context);
	          var pos = context.line;
	          line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
	          context.nextLine();
	        });
	        if (precise) {
	          doc.modeFrontier = context.line;
	        }
	        return context;
	      }

	      // Lightweight form of highlight -- proceed over this line and
	      // update state, but don't save a style array. Used for lines that
	      // aren't currently visible.
	      function processLine(cm, text, context, startAt) {
	        var mode = cm.doc.mode;
	        var stream = new StringStream(text, cm.options.tabSize, context);
	        stream.start = stream.pos = startAt || 0;
	        if (text == "") {
	          callBlankLine(mode, context.state);
	        }
	        while (!stream.eol()) {
	          readToken(mode, stream, context.state);
	          stream.start = stream.pos;
	        }
	      }
	      function callBlankLine(mode, state) {
	        if (mode.blankLine) {
	          return mode.blankLine(state);
	        }
	        if (!mode.innerMode) {
	          return;
	        }
	        var inner = innerMode(mode, state);
	        if (inner.mode.blankLine) {
	          return inner.mode.blankLine(inner.state);
	        }
	      }
	      function readToken(mode, stream, state, inner) {
	        for (var i = 0; i < 10; i++) {
	          if (inner) {
	            inner[0] = innerMode(mode, state).mode;
	          }
	          var style = mode.token(stream, state);
	          if (stream.pos > stream.start) {
	            return style;
	          }
	        }
	        throw new Error("Mode " + mode.name + " failed to advance stream.");
	      }
	      var Token = function (stream, type, state) {
	        this.start = stream.start;
	        this.end = stream.pos;
	        this.string = stream.current();
	        this.type = type || null;
	        this.state = state;
	      };

	      // Utility for getTokenAt and getLineTokens
	      function takeToken(cm, pos, precise, asArray) {
	        var doc = cm.doc,
	          mode = doc.mode,
	          style;
	        pos = clipPos(doc, pos);
	        var line = getLine(doc, pos.line),
	          context = getContextBefore(cm, pos.line, precise);
	        var stream = new StringStream(line.text, cm.options.tabSize, context),
	          tokens;
	        if (asArray) {
	          tokens = [];
	        }
	        while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
	          stream.start = stream.pos;
	          style = readToken(mode, stream, context.state);
	          if (asArray) {
	            tokens.push(new Token(stream, style, copyState(doc.mode, context.state)));
	          }
	        }
	        return asArray ? tokens : new Token(stream, style, context.state);
	      }
	      function extractLineClasses(type, output) {
	        if (type) {
	          for (;;) {
	            var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
	            if (!lineClass) {
	              break;
	            }
	            type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
	            var prop = lineClass[1] ? "bgClass" : "textClass";
	            if (output[prop] == null) {
	              output[prop] = lineClass[2];
	            } else if (!new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)").test(output[prop])) {
	              output[prop] += " " + lineClass[2];
	            }
	          }
	        }
	        return type;
	      }

	      // Run the given mode's parser over a line, calling f for each token.
	      function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
	        var flattenSpans = mode.flattenSpans;
	        if (flattenSpans == null) {
	          flattenSpans = cm.options.flattenSpans;
	        }
	        var curStart = 0,
	          curStyle = null;
	        var stream = new StringStream(text, cm.options.tabSize, context),
	          style;
	        var inner = cm.options.addModeClass && [null];
	        if (text == "") {
	          extractLineClasses(callBlankLine(mode, context.state), lineClasses);
	        }
	        while (!stream.eol()) {
	          if (stream.pos > cm.options.maxHighlightLength) {
	            flattenSpans = false;
	            if (forceToEnd) {
	              processLine(cm, text, context, stream.pos);
	            }
	            stream.pos = text.length;
	            style = null;
	          } else {
	            style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
	          }
	          if (inner) {
	            var mName = inner[0].name;
	            if (mName) {
	              style = "m-" + (style ? mName + " " + style : mName);
	            }
	          }
	          if (!flattenSpans || curStyle != style) {
	            while (curStart < stream.start) {
	              curStart = Math.min(stream.start, curStart + 5000);
	              f(curStart, curStyle);
	            }
	            curStyle = style;
	          }
	          stream.start = stream.pos;
	        }
	        while (curStart < stream.pos) {
	          // Webkit seems to refuse to render text nodes longer than 57444
	          // characters, and returns inaccurate measurements in nodes
	          // starting around 5000 chars.
	          var pos = Math.min(stream.pos, curStart + 5000);
	          f(pos, curStyle);
	          curStart = pos;
	        }
	      }

	      // Finds the line to start with when starting a parse. Tries to
	      // find a line with a stateAfter, so that it can start with a
	      // valid state. If that fails, it returns the line with the
	      // smallest indentation, which tends to need the least context to
	      // parse correctly.
	      function findStartLine(cm, n, precise) {
	        var minindent,
	          minline,
	          doc = cm.doc;
	        var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
	        for (var search = n; search > lim; --search) {
	          if (search <= doc.first) {
	            return doc.first;
	          }
	          var line = getLine(doc, search - 1),
	            after = line.stateAfter;
	          if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) {
	            return search;
	          }
	          var indented = countColumn(line.text, null, cm.options.tabSize);
	          if (minline == null || minindent > indented) {
	            minline = search - 1;
	            minindent = indented;
	          }
	        }
	        return minline;
	      }
	      function retreatFrontier(doc, n) {
	        doc.modeFrontier = Math.min(doc.modeFrontier, n);
	        if (doc.highlightFrontier < n - 10) {
	          return;
	        }
	        var start = doc.first;
	        for (var line = n - 1; line > start; line--) {
	          var saved = getLine(doc, line).stateAfter;
	          // change is on 3
	          // state on line 1 looked ahead 2 -- so saw 3
	          // test 1 + 2 < 3 should cover this
	          if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
	            start = line + 1;
	            break;
	          }
	        }
	        doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
	      }

	      // Optimize some code when these features are not used.
	      var sawReadOnlySpans = false,
	        sawCollapsedSpans = false;
	      function seeReadOnlySpans() {
	        sawReadOnlySpans = true;
	      }
	      function seeCollapsedSpans() {
	        sawCollapsedSpans = true;
	      }

	      // TEXTMARKER SPANS

	      function MarkedSpan(marker, from, to) {
	        this.marker = marker;
	        this.from = from;
	        this.to = to;
	      }

	      // Search an array of spans for a span matching the given marker.
	      function getMarkedSpanFor(spans, marker) {
	        if (spans) {
	          for (var i = 0; i < spans.length; ++i) {
	            var span = spans[i];
	            if (span.marker == marker) {
	              return span;
	            }
	          }
	        }
	      }

	      // Remove a span from an array, returning undefined if no spans are
	      // left (we don't store arrays for lines without spans).
	      function removeMarkedSpan(spans, span) {
	        var r;
	        for (var i = 0; i < spans.length; ++i) {
	          if (spans[i] != span) {
	            (r || (r = [])).push(spans[i]);
	          }
	        }
	        return r;
	      }

	      // Add a span to a line.
	      function addMarkedSpan(line, span, op) {
	        var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = new WeakSet()));
	        if (inThisOp && line.markedSpans && inThisOp.has(line.markedSpans)) {
	          line.markedSpans.push(span);
	        } else {
	          line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
	          if (inThisOp) {
	            inThisOp.add(line.markedSpans);
	          }
	        }
	        span.marker.attachLine(line);
	      }

	      // Used for the algorithm that adjusts markers for a change in the
	      // document. These functions cut an array of spans at a given
	      // character position, returning an array of remaining chunks (or
	      // undefined if nothing remains).
	      function markedSpansBefore(old, startCh, isInsert) {
	        var nw;
	        if (old) {
	          for (var i = 0; i < old.length; ++i) {
	            var span = old[i],
	              marker = span.marker;
	            var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
	            if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
	              var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
	              (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
	            }
	          }
	        }
	        return nw;
	      }
	      function markedSpansAfter(old, endCh, isInsert) {
	        var nw;
	        if (old) {
	          for (var i = 0; i < old.length; ++i) {
	            var span = old[i],
	              marker = span.marker;
	            var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
	            if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
	              var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
	              (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, span.to == null ? null : span.to - endCh));
	            }
	          }
	        }
	        return nw;
	      }

	      // Given a change object, compute the new set of marker spans that
	      // cover the line in which the change took place. Removes spans
	      // entirely within the change, reconnects spans belonging to the
	      // same marker that appear on both sides of the change, and cuts off
	      // spans partially within the change. Returns an array of span
	      // arrays with one element for each line in (after) the change.
	      function stretchSpansOverChange(doc, change) {
	        if (change.full) {
	          return null;
	        }
	        var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
	        var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
	        if (!oldFirst && !oldLast) {
	          return null;
	        }
	        var startCh = change.from.ch,
	          endCh = change.to.ch,
	          isInsert = cmp(change.from, change.to) == 0;
	        // Get the spans that 'stick out' on both sides
	        var first = markedSpansBefore(oldFirst, startCh, isInsert);
	        var last = markedSpansAfter(oldLast, endCh, isInsert);

	        // Next, merge those two ends
	        var sameLine = change.text.length == 1,
	          offset = lst(change.text).length + (sameLine ? startCh : 0);
	        if (first) {
	          // Fix up .to properties of first
	          for (var i = 0; i < first.length; ++i) {
	            var span = first[i];
	            if (span.to == null) {
	              var found = getMarkedSpanFor(last, span.marker);
	              if (!found) {
	                span.to = startCh;
	              } else if (sameLine) {
	                span.to = found.to == null ? null : found.to + offset;
	              }
	            }
	          }
	        }
	        if (last) {
	          // Fix up .from in last (or move them into first in case of sameLine)
	          for (var i$1 = 0; i$1 < last.length; ++i$1) {
	            var span$1 = last[i$1];
	            if (span$1.to != null) {
	              span$1.to += offset;
	            }
	            if (span$1.from == null) {
	              var found$1 = getMarkedSpanFor(first, span$1.marker);
	              if (!found$1) {
	                span$1.from = offset;
	                if (sameLine) {
	                  (first || (first = [])).push(span$1);
	                }
	              }
	            } else {
	              span$1.from += offset;
	              if (sameLine) {
	                (first || (first = [])).push(span$1);
	              }
	            }
	          }
	        }
	        // Make sure we didn't create any zero-length spans
	        if (first) {
	          first = clearEmptySpans(first);
	        }
	        if (last && last != first) {
	          last = clearEmptySpans(last);
	        }
	        var newMarkers = [first];
	        if (!sameLine) {
	          // Fill gap with whole-line-spans
	          var gap = change.text.length - 2,
	            gapMarkers;
	          if (gap > 0 && first) {
	            for (var i$2 = 0; i$2 < first.length; ++i$2) {
	              if (first[i$2].to == null) {
	                (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null));
	              }
	            }
	          }
	          for (var i$3 = 0; i$3 < gap; ++i$3) {
	            newMarkers.push(gapMarkers);
	          }
	          newMarkers.push(last);
	        }
	        return newMarkers;
	      }

	      // Remove spans that are empty and don't have a clearWhenEmpty
	      // option of false.
	      function clearEmptySpans(spans) {
	        for (var i = 0; i < spans.length; ++i) {
	          var span = spans[i];
	          if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) {
	            spans.splice(i--, 1);
	          }
	        }
	        if (!spans.length) {
	          return null;
	        }
	        return spans;
	      }

	      // Used to 'clip' out readOnly ranges when making a change.
	      function removeReadOnlyRanges(doc, from, to) {
	        var markers = null;
	        doc.iter(from.line, to.line + 1, function (line) {
	          if (line.markedSpans) {
	            for (var i = 0; i < line.markedSpans.length; ++i) {
	              var mark = line.markedSpans[i].marker;
	              if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) {
	                (markers || (markers = [])).push(mark);
	              }
	            }
	          }
	        });
	        if (!markers) {
	          return null;
	        }
	        var parts = [{
	          from: from,
	          to: to
	        }];
	        for (var i = 0; i < markers.length; ++i) {
	          var mk = markers[i],
	            m = mk.find(0);
	          for (var j = 0; j < parts.length; ++j) {
	            var p = parts[j];
	            if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) {
	              continue;
	            }
	            var newParts = [j, 1],
	              dfrom = cmp(p.from, m.from),
	              dto = cmp(p.to, m.to);
	            if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) {
	              newParts.push({
	                from: p.from,
	                to: m.from
	              });
	            }
	            if (dto > 0 || !mk.inclusiveRight && !dto) {
	              newParts.push({
	                from: m.to,
	                to: p.to
	              });
	            }
	            parts.splice.apply(parts, newParts);
	            j += newParts.length - 3;
	          }
	        }
	        return parts;
	      }

	      // Connect or disconnect spans from a line.
	      function detachMarkedSpans(line) {
	        var spans = line.markedSpans;
	        if (!spans) {
	          return;
	        }
	        for (var i = 0; i < spans.length; ++i) {
	          spans[i].marker.detachLine(line);
	        }
	        line.markedSpans = null;
	      }
	      function attachMarkedSpans(line, spans) {
	        if (!spans) {
	          return;
	        }
	        for (var i = 0; i < spans.length; ++i) {
	          spans[i].marker.attachLine(line);
	        }
	        line.markedSpans = spans;
	      }

	      // Helpers used when computing which overlapping collapsed span
	      // counts as the larger one.
	      function extraLeft(marker) {
	        return marker.inclusiveLeft ? -1 : 0;
	      }
	      function extraRight(marker) {
	        return marker.inclusiveRight ? 1 : 0;
	      }

	      // Returns a number indicating which of two overlapping collapsed
	      // spans is larger (and thus includes the other). Falls back to
	      // comparing ids when the spans cover exactly the same range.
	      function compareCollapsedMarkers(a, b) {
	        var lenDiff = a.lines.length - b.lines.length;
	        if (lenDiff != 0) {
	          return lenDiff;
	        }
	        var aPos = a.find(),
	          bPos = b.find();
	        var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
	        if (fromCmp) {
	          return -fromCmp;
	        }
	        var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
	        if (toCmp) {
	          return toCmp;
	        }
	        return b.id - a.id;
	      }

	      // Find out whether a line ends or starts in a collapsed span. If
	      // so, return the marker for that span.
	      function collapsedSpanAtSide(line, start) {
	        var sps = sawCollapsedSpans && line.markedSpans,
	          found;
	        if (sps) {
	          for (var sp = void 0, i = 0; i < sps.length; ++i) {
	            sp = sps[i];
	            if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) {
	              found = sp.marker;
	            }
	          }
	        }
	        return found;
	      }
	      function collapsedSpanAtStart(line) {
	        return collapsedSpanAtSide(line, true);
	      }
	      function collapsedSpanAtEnd(line) {
	        return collapsedSpanAtSide(line, false);
	      }
	      function collapsedSpanAround(line, ch) {
	        var sps = sawCollapsedSpans && line.markedSpans,
	          found;
	        if (sps) {
	          for (var i = 0; i < sps.length; ++i) {
	            var sp = sps[i];
	            if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) {
	              found = sp.marker;
	            }
	          }
	        }
	        return found;
	      }

	      // Test whether there exists a collapsed span that partially
	      // overlaps (covers the start or end, but not both) of a new span.
	      // Such overlap is not allowed.
	      function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
	        var line = getLine(doc, lineNo);
	        var sps = sawCollapsedSpans && line.markedSpans;
	        if (sps) {
	          for (var i = 0; i < sps.length; ++i) {
	            var sp = sps[i];
	            if (!sp.marker.collapsed) {
	              continue;
	            }
	            var found = sp.marker.find(0);
	            var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
	            var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
	            if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) {
	              continue;
	            }
	            if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) {
	              return true;
	            }
	          }
	        }
	      }

	      // A visual line is a line as drawn on the screen. Folding, for
	      // example, can cause multiple logical lines to appear on the same
	      // visual line. This finds the start of the visual line that the
	      // given line is part of (usually that is the line itself).
	      function visualLine(line) {
	        var merged;
	        while (merged = collapsedSpanAtStart(line)) {
	          line = merged.find(-1, true).line;
	        }
	        return line;
	      }
	      function visualLineEnd(line) {
	        var merged;
	        while (merged = collapsedSpanAtEnd(line)) {
	          line = merged.find(1, true).line;
	        }
	        return line;
	      }

	      // Returns an array of logical lines that continue the visual line
	      // started by the argument, or undefined if there are no such lines.
	      function visualLineContinued(line) {
	        var merged, lines;
	        while (merged = collapsedSpanAtEnd(line)) {
	          line = merged.find(1, true).line;
	          (lines || (lines = [])).push(line);
	        }
	        return lines;
	      }

	      // Get the line number of the start of the visual line that the
	      // given line number is part of.
	      function visualLineNo(doc, lineN) {
	        var line = getLine(doc, lineN),
	          vis = visualLine(line);
	        if (line == vis) {
	          return lineN;
	        }
	        return lineNo(vis);
	      }

	      // Get the line number of the start of the next visual line after
	      // the given line.
	      function visualLineEndNo(doc, lineN) {
	        if (lineN > doc.lastLine()) {
	          return lineN;
	        }
	        var line = getLine(doc, lineN),
	          merged;
	        if (!lineIsHidden(doc, line)) {
	          return lineN;
	        }
	        while (merged = collapsedSpanAtEnd(line)) {
	          line = merged.find(1, true).line;
	        }
	        return lineNo(line) + 1;
	      }

	      // Compute whether a line is hidden. Lines count as hidden when they
	      // are part of a visual line that starts with another line, or when
	      // they are entirely covered by collapsed, non-widget span.
	      function lineIsHidden(doc, line) {
	        var sps = sawCollapsedSpans && line.markedSpans;
	        if (sps) {
	          for (var sp = void 0, i = 0; i < sps.length; ++i) {
	            sp = sps[i];
	            if (!sp.marker.collapsed) {
	              continue;
	            }
	            if (sp.from == null) {
	              return true;
	            }
	            if (sp.marker.widgetNode) {
	              continue;
	            }
	            if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) {
	              return true;
	            }
	          }
	        }
	      }
	      function lineIsHiddenInner(doc, line, span) {
	        if (span.to == null) {
	          var end = span.marker.find(1, true);
	          return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
	        }
	        if (span.marker.inclusiveRight && span.to == line.text.length) {
	          return true;
	        }
	        for (var sp = void 0, i = 0; i < line.markedSpans.length; ++i) {
	          sp = line.markedSpans[i];
	          if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && (sp.to == null || sp.to != span.from) && (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && lineIsHiddenInner(doc, line, sp)) {
	            return true;
	          }
	        }
	      }

	      // Find the height above the given line.
	      function heightAtLine(lineObj) {
	        lineObj = visualLine(lineObj);
	        var h = 0,
	          chunk = lineObj.parent;
	        for (var i = 0; i < chunk.lines.length; ++i) {
	          var line = chunk.lines[i];
	          if (line == lineObj) {
	            break;
	          } else {
	            h += line.height;
	          }
	        }
	        for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
	          for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
	            var cur = p.children[i$1];
	            if (cur == chunk) {
	              break;
	            } else {
	              h += cur.height;
	            }
	          }
	        }
	        return h;
	      }

	      // Compute the character length of a line, taking into account
	      // collapsed ranges (see markText) that might hide parts, and join
	      // other lines onto it.
	      function lineLength(line) {
	        if (line.height == 0) {
	          return 0;
	        }
	        var len = line.text.length,
	          merged,
	          cur = line;
	        while (merged = collapsedSpanAtStart(cur)) {
	          var found = merged.find(0, true);
	          cur = found.from.line;
	          len += found.from.ch - found.to.ch;
	        }
	        cur = line;
	        while (merged = collapsedSpanAtEnd(cur)) {
	          var found$1 = merged.find(0, true);
	          len -= cur.text.length - found$1.from.ch;
	          cur = found$1.to.line;
	          len += cur.text.length - found$1.to.ch;
	        }
	        return len;
	      }

	      // Find the longest line in the document.
	      function findMaxLine(cm) {
	        var d = cm.display,
	          doc = cm.doc;
	        d.maxLine = getLine(doc, doc.first);
	        d.maxLineLength = lineLength(d.maxLine);
	        d.maxLineChanged = true;
	        doc.iter(function (line) {
	          var len = lineLength(line);
	          if (len > d.maxLineLength) {
	            d.maxLineLength = len;
	            d.maxLine = line;
	          }
	        });
	      }

	      // LINE DATA STRUCTURE

	      // Line objects. These hold state related to a line, including
	      // highlighting info (the styles array).
	      var Line = function (text, markedSpans, estimateHeight) {
	        this.text = text;
	        attachMarkedSpans(this, markedSpans);
	        this.height = estimateHeight ? estimateHeight(this) : 1;
	      };
	      Line.prototype.lineNo = function () {
	        return lineNo(this);
	      };
	      eventMixin(Line);

	      // Change the content (text, markers) of a line. Automatically
	      // invalidates cached information and tries to re-estimate the
	      // line's height.
	      function updateLine(line, text, markedSpans, estimateHeight) {
	        line.text = text;
	        if (line.stateAfter) {
	          line.stateAfter = null;
	        }
	        if (line.styles) {
	          line.styles = null;
	        }
	        if (line.order != null) {
	          line.order = null;
	        }
	        detachMarkedSpans(line);
	        attachMarkedSpans(line, markedSpans);
	        var estHeight = estimateHeight ? estimateHeight(line) : 1;
	        if (estHeight != line.height) {
	          updateLineHeight(line, estHeight);
	        }
	      }

	      // Detach a line from the document tree and its markers.
	      function cleanUpLine(line) {
	        line.parent = null;
	        detachMarkedSpans(line);
	      }

	      // Convert a style as returned by a mode (either null, or a string
	      // containing one or more styles) to a CSS style. This is cached,
	      // and also looks for line-wide styles.
	      var styleToClassCache = {},
	        styleToClassCacheWithMode = {};
	      function interpretTokenStyle(style, options) {
	        if (!style || /^\s*$/.test(style)) {
	          return null;
	        }
	        var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
	        return cache[style] || (cache[style] = style.replace(/\S+/g, "cm-$&"));
	      }

	      // Render the DOM representation of the text of a line. Also builds
	      // up a 'line map', which points at the DOM nodes that represent
	      // specific stretches of text, and is used by the measuring code.
	      // The returned object contains the DOM node, this map, and
	      // information about line-wide styles that were set by the mode.
	      function buildLineContent(cm, lineView) {
	        // The padding-right forces the element to have a 'border', which
	        // is needed on Webkit to be able to get line-level bounding
	        // rectangles for it (in measureChar).
	        var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
	        var builder = {
	          pre: eltP("pre", [content], "CodeMirror-line"),
	          content: content,
	          col: 0,
	          pos: 0,
	          cm: cm,
	          trailingSpace: false,
	          splitSpaces: cm.getOption("lineWrapping")
	        };
	        lineView.measure = {};

	        // Iterate over the logical lines that make up this visual line.
	        for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
	          var line = i ? lineView.rest[i - 1] : lineView.line,
	            order = void 0;
	          builder.pos = 0;
	          builder.addToken = buildToken;
	          // Optionally wire in some hacks into the token-rendering
	          // algorithm, to deal with browser quirks.
	          if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) {
	            builder.addToken = buildTokenBadBidi(builder.addToken, order);
	          }
	          builder.map = [];
	          var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
	          insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
	          if (line.styleClasses) {
	            if (line.styleClasses.bgClass) {
	              builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
	            }
	            if (line.styleClasses.textClass) {
	              builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
	            }
	          }

	          // Ensure at least a single node is present, for measuring.
	          if (builder.map.length == 0) {
	            builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
	          }

	          // Store the map and a cache object for the current logical line
	          if (i == 0) {
	            lineView.measure.map = builder.map;
	            lineView.measure.cache = {};
	          } else {
	            (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
	            (lineView.measure.caches || (lineView.measure.caches = [])).push({});
	          }
	        }

	        // See issue #2901
	        if (webkit) {
	          var last = builder.content.lastChild;
	          if (/\bcm-tab\b/.test(last.className) || last.querySelector && last.querySelector(".cm-tab")) {
	            builder.content.className = "cm-tab-wrap-hack";
	          }
	        }
	        signal(cm, "renderLine", cm, lineView.line, builder.pre);
	        if (builder.pre.className) {
	          builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
	        }
	        return builder;
	      }
	      function defaultSpecialCharPlaceholder(ch) {
	        var token = elt("span", "\u2022", "cm-invalidchar");
	        token.title = "\\u" + ch.charCodeAt(0).toString(16);
	        token.setAttribute("aria-label", token.title);
	        return token;
	      }

	      // Build up the DOM representation for a single token, and add it to
	      // the line map. Takes care to render special characters separately.
	      function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
	        if (!text) {
	          return;
	        }
	        var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
	        var special = builder.cm.state.specialChars,
	          mustWrap = false;
	        var content;
	        if (!special.test(text)) {
	          builder.col += text.length;
	          content = document.createTextNode(displayText);
	          builder.map.push(builder.pos, builder.pos + text.length, content);
	          if (ie && ie_version < 9) {
	            mustWrap = true;
	          }
	          builder.pos += text.length;
	        } else {
	          content = document.createDocumentFragment();
	          var pos = 0;
	          while (true) {
	            special.lastIndex = pos;
	            var m = special.exec(text);
	            var skipped = m ? m.index - pos : text.length - pos;
	            if (skipped) {
	              var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
	              if (ie && ie_version < 9) {
	                content.appendChild(elt("span", [txt]));
	              } else {
	                content.appendChild(txt);
	              }
	              builder.map.push(builder.pos, builder.pos + skipped, txt);
	              builder.col += skipped;
	              builder.pos += skipped;
	            }
	            if (!m) {
	              break;
	            }
	            pos += skipped + 1;
	            var txt$1 = void 0;
	            if (m[0] == "\t") {
	              var tabSize = builder.cm.options.tabSize,
	                tabWidth = tabSize - builder.col % tabSize;
	              txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
	              txt$1.setAttribute("role", "presentation");
	              txt$1.setAttribute("cm-text", "\t");
	              builder.col += tabWidth;
	            } else if (m[0] == "\r" || m[0] == "\n") {
	              txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
	              txt$1.setAttribute("cm-text", m[0]);
	              builder.col += 1;
	            } else {
	              txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
	              txt$1.setAttribute("cm-text", m[0]);
	              if (ie && ie_version < 9) {
	                content.appendChild(elt("span", [txt$1]));
	              } else {
	                content.appendChild(txt$1);
	              }
	              builder.col += 1;
	            }
	            builder.map.push(builder.pos, builder.pos + 1, txt$1);
	            builder.pos++;
	          }
	        }
	        builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
	        if (style || startStyle || endStyle || mustWrap || css || attributes) {
	          var fullStyle = style || "";
	          if (startStyle) {
	            fullStyle += startStyle;
	          }
	          if (endStyle) {
	            fullStyle += endStyle;
	          }
	          var token = elt("span", [content], fullStyle, css);
	          if (attributes) {
	            for (var attr in attributes) {
	              if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class") {
	                token.setAttribute(attr, attributes[attr]);
	              }
	            }
	          }
	          return builder.content.appendChild(token);
	        }
	        builder.content.appendChild(content);
	      }

	      // Change some spaces to NBSP to prevent the browser from collapsing
	      // trailing spaces at the end of a line when rendering text (issue #1362).
	      function splitSpaces(text, trailingBefore) {
	        if (text.length > 1 && !/  /.test(text)) {
	          return text;
	        }
	        var spaceBefore = trailingBefore,
	          result = "";
	        for (var i = 0; i < text.length; i++) {
	          var ch = text.charAt(i);
	          if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) {
	            ch = "\u00a0";
	          }
	          result += ch;
	          spaceBefore = ch == " ";
	        }
	        return result;
	      }

	      // Work around nonsense dimensions being reported for stretches of
	      // right-to-left text.
	      function buildTokenBadBidi(inner, order) {
	        return function (builder, text, style, startStyle, endStyle, css, attributes) {
	          style = style ? style + " cm-force-border" : "cm-force-border";
	          var start = builder.pos,
	            end = start + text.length;
	          for (;;) {
	            // Find the part that overlaps with the start of this text
	            var part = void 0;
	            for (var i = 0; i < order.length; i++) {
	              part = order[i];
	              if (part.to > start && part.from <= start) {
	                break;
	              }
	            }
	            if (part.to >= end) {
	              return inner(builder, text, style, startStyle, endStyle, css, attributes);
	            }
	            inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
	            startStyle = null;
	            text = text.slice(part.to - start);
	            start = part.to;
	          }
	        };
	      }
	      function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
	        var widget = !ignoreWidget && marker.widgetNode;
	        if (widget) {
	          builder.map.push(builder.pos, builder.pos + size, widget);
	        }
	        if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
	          if (!widget) {
	            widget = builder.content.appendChild(document.createElement("span"));
	          }
	          widget.setAttribute("cm-marker", marker.id);
	        }
	        if (widget) {
	          builder.cm.display.input.setUneditable(widget);
	          builder.content.appendChild(widget);
	        }
	        builder.pos += size;
	        builder.trailingSpace = false;
	      }

	      // Outputs a number of spans to make up a line, taking highlighting
	      // and marked text into account.
	      function insertLineContent(line, builder, styles) {
	        var spans = line.markedSpans,
	          allText = line.text,
	          at = 0;
	        if (!spans) {
	          for (var i$1 = 1; i$1 < styles.length; i$1 += 2) {
	            builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1 + 1], builder.cm.options));
	          }
	          return;
	        }
	        var len = allText.length,
	          pos = 0,
	          i = 1,
	          text = "",
	          style,
	          css;
	        var nextChange = 0,
	          spanStyle,
	          spanEndStyle,
	          spanStartStyle,
	          collapsed,
	          attributes;
	        for (;;) {
	          if (nextChange == pos) {
	            // Update current marker set
	            spanStyle = spanEndStyle = spanStartStyle = css = "";
	            attributes = null;
	            collapsed = null;
	            nextChange = Infinity;
	            var foundBookmarks = [],
	              endStyles = void 0;
	            for (var j = 0; j < spans.length; ++j) {
	              var sp = spans[j],
	                m = sp.marker;
	              if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
	                foundBookmarks.push(m);
	              } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
	                if (sp.to != null && sp.to != pos && nextChange > sp.to) {
	                  nextChange = sp.to;
	                  spanEndStyle = "";
	                }
	                if (m.className) {
	                  spanStyle += " " + m.className;
	                }
	                if (m.css) {
	                  css = (css ? css + ";" : "") + m.css;
	                }
	                if (m.startStyle && sp.from == pos) {
	                  spanStartStyle += " " + m.startStyle;
	                }
	                if (m.endStyle && sp.to == nextChange) {
	                  (endStyles || (endStyles = [])).push(m.endStyle, sp.to);
	                }
	                // support for the old title property
	                // https://github.com/codemirror/CodeMirror/pull/5673
	                if (m.title) {
	                  (attributes || (attributes = {})).title = m.title;
	                }
	                if (m.attributes) {
	                  for (var attr in m.attributes) {
	                    (attributes || (attributes = {}))[attr] = m.attributes[attr];
	                  }
	                }
	                if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) {
	                  collapsed = sp;
	                }
	              } else if (sp.from > pos && nextChange > sp.from) {
	                nextChange = sp.from;
	              }
	            }
	            if (endStyles) {
	              for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) {
	                if (endStyles[j$1 + 1] == nextChange) {
	                  spanEndStyle += " " + endStyles[j$1];
	                }
	              }
	            }
	            if (!collapsed || collapsed.from == pos) {
	              for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) {
	                buildCollapsedSpan(builder, 0, foundBookmarks[j$2]);
	              }
	            }
	            if (collapsed && (collapsed.from || 0) == pos) {
	              buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, collapsed.marker, collapsed.from == null);
	              if (collapsed.to == null) {
	                return;
	              }
	              if (collapsed.to == pos) {
	                collapsed = false;
	              }
	            }
	          }
	          if (pos >= len) {
	            break;
	          }
	          var upto = Math.min(len, nextChange);
	          while (true) {
	            if (text) {
	              var end = pos + text.length;
	              if (!collapsed) {
	                var tokenText = end > upto ? text.slice(0, upto - pos) : text;
	                builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
	              }
	              if (end >= upto) {
	                text = text.slice(upto - pos);
	                pos = upto;
	                break;
	              }
	              pos = end;
	              spanStartStyle = "";
	            }
	            text = allText.slice(at, at = styles[i++]);
	            style = interpretTokenStyle(styles[i++], builder.cm.options);
	          }
	        }
	      }

	      // These objects are used to represent the visible (currently drawn)
	      // part of the document. A LineView may correspond to multiple
	      // logical lines, if those are connected by collapsed ranges.
	      function LineView(doc, line, lineN) {
	        // The starting line
	        this.line = line;
	        // Continuing lines, if any
	        this.rest = visualLineContinued(line);
	        // Number of logical lines in this visual line
	        this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
	        this.node = this.text = null;
	        this.hidden = lineIsHidden(doc, line);
	      }

	      // Create a range of LineView objects for the given lines.
	      function buildViewArray(cm, from, to) {
	        var array = [],
	          nextPos;
	        for (var pos = from; pos < to; pos = nextPos) {
	          var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
	          nextPos = pos + view.size;
	          array.push(view);
	        }
	        return array;
	      }
	      var operationGroup = null;
	      function pushOperation(op) {
	        if (operationGroup) {
	          operationGroup.ops.push(op);
	        } else {
	          op.ownsGroup = operationGroup = {
	            ops: [op],
	            delayedCallbacks: []
	          };
	        }
	      }
	      function fireCallbacksForOps(group) {
	        // Calls delayed callbacks and cursorActivity handlers until no
	        // new ones appear
	        var callbacks = group.delayedCallbacks,
	          i = 0;
	        do {
	          for (; i < callbacks.length; i++) {
	            callbacks[i].call(null);
	          }
	          for (var j = 0; j < group.ops.length; j++) {
	            var op = group.ops[j];
	            if (op.cursorActivityHandlers) {
	              while (op.cursorActivityCalled < op.cursorActivityHandlers.length) {
	                op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
	              }
	            }
	          }
	        } while (i < callbacks.length);
	      }
	      function finishOperation(op, endCb) {
	        var group = op.ownsGroup;
	        if (!group) {
	          return;
	        }
	        try {
	          fireCallbacksForOps(group);
	        } finally {
	          operationGroup = null;
	          endCb(group);
	        }
	      }
	      var orphanDelayedCallbacks = null;

	      // Often, we want to signal events at a point where we are in the
	      // middle of some work, but don't want the handler to start calling
	      // other methods on the editor, which might be in an inconsistent
	      // state or simply not expect any other events to happen.
	      // signalLater looks whether there are any handlers, and schedules
	      // them to be executed when the last operation ends, or, if no
	      // operation is active, when a timeout fires.
	      function signalLater(emitter, type /*, values...*/) {
	        var arr = getHandlers(emitter, type);
	        if (!arr.length) {
	          return;
	        }
	        var args = Array.prototype.slice.call(arguments, 2),
	          list;
	        if (operationGroup) {
	          list = operationGroup.delayedCallbacks;
	        } else if (orphanDelayedCallbacks) {
	          list = orphanDelayedCallbacks;
	        } else {
	          list = orphanDelayedCallbacks = [];
	          setTimeout(fireOrphanDelayed, 0);
	        }
	        var loop = function (i) {
	          list.push(function () {
	            return arr[i].apply(null, args);
	          });
	        };
	        for (var i = 0; i < arr.length; ++i) loop(i);
	      }
	      function fireOrphanDelayed() {
	        var delayed = orphanDelayedCallbacks;
	        orphanDelayedCallbacks = null;
	        for (var i = 0; i < delayed.length; ++i) {
	          delayed[i]();
	        }
	      }

	      // When an aspect of a line changes, a string is added to
	      // lineView.changes. This updates the relevant part of the line's
	      // DOM structure.
	      function updateLineForChanges(cm, lineView, lineN, dims) {
	        for (var j = 0; j < lineView.changes.length; j++) {
	          var type = lineView.changes[j];
	          if (type == "text") {
	            updateLineText(cm, lineView);
	          } else if (type == "gutter") {
	            updateLineGutter(cm, lineView, lineN, dims);
	          } else if (type == "class") {
	            updateLineClasses(cm, lineView);
	          } else if (type == "widget") {
	            updateLineWidgets(cm, lineView, dims);
	          }
	        }
	        lineView.changes = null;
	      }

	      // Lines with gutter elements, widgets or a background class need to
	      // be wrapped, and have the extra elements added to the wrapper div
	      function ensureLineWrapped(lineView) {
	        if (lineView.node == lineView.text) {
	          lineView.node = elt("div", null, null, "position: relative");
	          if (lineView.text.parentNode) {
	            lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
	          }
	          lineView.node.appendChild(lineView.text);
	          if (ie && ie_version < 8) {
	            lineView.node.style.zIndex = 2;
	          }
	        }
	        return lineView.node;
	      }
	      function updateLineBackground(cm, lineView) {
	        var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
	        if (cls) {
	          cls += " CodeMirror-linebackground";
	        }
	        if (lineView.background) {
	          if (cls) {
	            lineView.background.className = cls;
	          } else {
	            lineView.background.parentNode.removeChild(lineView.background);
	            lineView.background = null;
	          }
	        } else if (cls) {
	          var wrap = ensureLineWrapped(lineView);
	          lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
	          cm.display.input.setUneditable(lineView.background);
	        }
	      }

	      // Wrapper around buildLineContent which will reuse the structure
	      // in display.externalMeasured when possible.
	      function getLineContent(cm, lineView) {
	        var ext = cm.display.externalMeasured;
	        if (ext && ext.line == lineView.line) {
	          cm.display.externalMeasured = null;
	          lineView.measure = ext.measure;
	          return ext.built;
	        }
	        return buildLineContent(cm, lineView);
	      }

	      // Redraw the line's text. Interacts with the background and text
	      // classes because the mode may output tokens that influence these
	      // classes.
	      function updateLineText(cm, lineView) {
	        var cls = lineView.text.className;
	        var built = getLineContent(cm, lineView);
	        if (lineView.text == lineView.node) {
	          lineView.node = built.pre;
	        }
	        lineView.text.parentNode.replaceChild(built.pre, lineView.text);
	        lineView.text = built.pre;
	        if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
	          lineView.bgClass = built.bgClass;
	          lineView.textClass = built.textClass;
	          updateLineClasses(cm, lineView);
	        } else if (cls) {
	          lineView.text.className = cls;
	        }
	      }
	      function updateLineClasses(cm, lineView) {
	        updateLineBackground(cm, lineView);
	        if (lineView.line.wrapClass) {
	          ensureLineWrapped(lineView).className = lineView.line.wrapClass;
	        } else if (lineView.node != lineView.text) {
	          lineView.node.className = "";
	        }
	        var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
	        lineView.text.className = textClass || "";
	      }
	      function updateLineGutter(cm, lineView, lineN, dims) {
	        if (lineView.gutter) {
	          lineView.node.removeChild(lineView.gutter);
	          lineView.gutter = null;
	        }
	        if (lineView.gutterBackground) {
	          lineView.node.removeChild(lineView.gutterBackground);
	          lineView.gutterBackground = null;
	        }
	        if (lineView.line.gutterClass) {
	          var wrap = ensureLineWrapped(lineView);
	          lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + dims.gutterTotalWidth + "px");
	          cm.display.input.setUneditable(lineView.gutterBackground);
	          wrap.insertBefore(lineView.gutterBackground, lineView.text);
	        }
	        var markers = lineView.line.gutterMarkers;
	        if (cm.options.lineNumbers || markers) {
	          var wrap$1 = ensureLineWrapped(lineView);
	          var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
	          gutterWrap.setAttribute("aria-hidden", "true");
	          cm.display.input.setUneditable(gutterWrap);
	          wrap$1.insertBefore(gutterWrap, lineView.text);
	          if (lineView.line.gutterClass) {
	            gutterWrap.className += " " + lineView.line.gutterClass;
	          }
	          if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) {
	            lineView.lineNumber = gutterWrap.appendChild(elt("div", lineNumberFor(cm.options, lineN), "CodeMirror-linenumber CodeMirror-gutter-elt", "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + cm.display.lineNumInnerWidth + "px"));
	          }
	          if (markers) {
	            for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
	              var id = cm.display.gutterSpecs[k].className,
	                found = markers.hasOwnProperty(id) && markers[id];
	              if (found) {
	                gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
	              }
	            }
	          }
	        }
	      }
	      function updateLineWidgets(cm, lineView, dims) {
	        if (lineView.alignable) {
	          lineView.alignable = null;
	        }
	        var isWidget = classTest("CodeMirror-linewidget");
	        for (var node = lineView.node.firstChild, next = void 0; node; node = next) {
	          next = node.nextSibling;
	          if (isWidget.test(node.className)) {
	            lineView.node.removeChild(node);
	          }
	        }
	        insertLineWidgets(cm, lineView, dims);
	      }

	      // Build a line's DOM representation from scratch
	      function buildLineElement(cm, lineView, lineN, dims) {
	        var built = getLineContent(cm, lineView);
	        lineView.text = lineView.node = built.pre;
	        if (built.bgClass) {
	          lineView.bgClass = built.bgClass;
	        }
	        if (built.textClass) {
	          lineView.textClass = built.textClass;
	        }
	        updateLineClasses(cm, lineView);
	        updateLineGutter(cm, lineView, lineN, dims);
	        insertLineWidgets(cm, lineView, dims);
	        return lineView.node;
	      }

	      // A lineView may contain multiple logical lines (when merged by
	      // collapsed spans). The widgets for all of them need to be drawn.
	      function insertLineWidgets(cm, lineView, dims) {
	        insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
	        if (lineView.rest) {
	          for (var i = 0; i < lineView.rest.length; i++) {
	            insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
	          }
	        }
	      }
	      function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
	        if (!line.widgets) {
	          return;
	        }
	        var wrap = ensureLineWrapped(lineView);
	        for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
	          var widget = ws[i],
	            node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
	          if (!widget.handleMouseEvents) {
	            node.setAttribute("cm-ignore-events", "true");
	          }
	          positionLineWidget(widget, node, lineView, dims);
	          cm.display.input.setUneditable(node);
	          if (allowAbove && widget.above) {
	            wrap.insertBefore(node, lineView.gutter || lineView.text);
	          } else {
	            wrap.appendChild(node);
	          }
	          signalLater(widget, "redraw");
	        }
	      }
	      function positionLineWidget(widget, node, lineView, dims) {
	        if (widget.noHScroll) {
	          (lineView.alignable || (lineView.alignable = [])).push(node);
	          var width = dims.wrapperWidth;
	          node.style.left = dims.fixedPos + "px";
	          if (!widget.coverGutter) {
	            width -= dims.gutterTotalWidth;
	            node.style.paddingLeft = dims.gutterTotalWidth + "px";
	          }
	          node.style.width = width + "px";
	        }
	        if (widget.coverGutter) {
	          node.style.zIndex = 5;
	          node.style.position = "relative";
	          if (!widget.noHScroll) {
	            node.style.marginLeft = -dims.gutterTotalWidth + "px";
	          }
	        }
	      }
	      function widgetHeight(widget) {
	        if (widget.height != null) {
	          return widget.height;
	        }
	        var cm = widget.doc.cm;
	        if (!cm) {
	          return 0;
	        }
	        if (!contains(document.body, widget.node)) {
	          var parentStyle = "position: relative;";
	          if (widget.coverGutter) {
	            parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
	          }
	          if (widget.noHScroll) {
	            parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
	          }
	          removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
	        }
	        return widget.height = widget.node.parentNode.offsetHeight;
	      }

	      // Return true when the given mouse event happened in a widget
	      function eventInWidget(display, e) {
	        for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
	          if (!n || n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true" || n.parentNode == display.sizer && n != display.mover) {
	            return true;
	          }
	        }
	      }

	      // POSITION MEASUREMENT

	      function paddingTop(display) {
	        return display.lineSpace.offsetTop;
	      }
	      function paddingVert(display) {
	        return display.mover.offsetHeight - display.lineSpace.offsetHeight;
	      }
	      function paddingH(display) {
	        if (display.cachedPaddingH) {
	          return display.cachedPaddingH;
	        }
	        var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
	        var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
	        var data = {
	          left: parseInt(style.paddingLeft),
	          right: parseInt(style.paddingRight)
	        };
	        if (!isNaN(data.left) && !isNaN(data.right)) {
	          display.cachedPaddingH = data;
	        }
	        return data;
	      }
	      function scrollGap(cm) {
	        return scrollerGap - cm.display.nativeBarWidth;
	      }
	      function displayWidth(cm) {
	        return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
	      }
	      function displayHeight(cm) {
	        return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
	      }

	      // Ensure the lineView.wrapping.heights array is populated. This is
	      // an array of bottom offsets for the lines that make up a drawn
	      // line. When lineWrapping is on, there might be more than one
	      // height.
	      function ensureLineHeights(cm, lineView, rect) {
	        var wrapping = cm.options.lineWrapping;
	        var curWidth = wrapping && displayWidth(cm);
	        if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
	          var heights = lineView.measure.heights = [];
	          if (wrapping) {
	            lineView.measure.width = curWidth;
	            var rects = lineView.text.firstChild.getClientRects();
	            for (var i = 0; i < rects.length - 1; i++) {
	              var cur = rects[i],
	                next = rects[i + 1];
	              if (Math.abs(cur.bottom - next.bottom) > 2) {
	                heights.push((cur.bottom + next.top) / 2 - rect.top);
	              }
	            }
	          }
	          heights.push(rect.bottom - rect.top);
	        }
	      }

	      // Find a line map (mapping character offsets to text nodes) and a
	      // measurement cache for the given line number. (A line view might
	      // contain multiple lines when collapsed ranges are present.)
	      function mapFromLineView(lineView, line, lineN) {
	        if (lineView.line == line) {
	          return {
	            map: lineView.measure.map,
	            cache: lineView.measure.cache
	          };
	        }
	        if (lineView.rest) {
	          for (var i = 0; i < lineView.rest.length; i++) {
	            if (lineView.rest[i] == line) {
	              return {
	                map: lineView.measure.maps[i],
	                cache: lineView.measure.caches[i]
	              };
	            }
	          }
	          for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) {
	            if (lineNo(lineView.rest[i$1]) > lineN) {
	              return {
	                map: lineView.measure.maps[i$1],
	                cache: lineView.measure.caches[i$1],
	                before: true
	              };
	            }
	          }
	        }
	      }

	      // Render a line into the hidden node display.externalMeasured. Used
	      // when measurement is needed for a line that's not in the viewport.
	      function updateExternalMeasurement(cm, line) {
	        line = visualLine(line);
	        var lineN = lineNo(line);
	        var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
	        view.lineN = lineN;
	        var built = view.built = buildLineContent(cm, view);
	        view.text = built.pre;
	        removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
	        return view;
	      }

	      // Get a {top, bottom, left, right} box (in line-local coordinates)
	      // for a given character.
	      function measureChar(cm, line, ch, bias) {
	        return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
	      }

	      // Find a line view that corresponds to the given line number.
	      function findViewForLine(cm, lineN) {
	        if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) {
	          return cm.display.view[findViewIndex(cm, lineN)];
	        }
	        var ext = cm.display.externalMeasured;
	        if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) {
	          return ext;
	        }
	      }

	      // Measurement can be split in two steps, the set-up work that
	      // applies to the whole line, and the measurement of the actual
	      // character. Functions like coordsChar, that need to do a lot of
	      // measurements in a row, can thus ensure that the set-up work is
	      // only done once.
	      function prepareMeasureForLine(cm, line) {
	        var lineN = lineNo(line);
	        var view = findViewForLine(cm, lineN);
	        if (view && !view.text) {
	          view = null;
	        } else if (view && view.changes) {
	          updateLineForChanges(cm, view, lineN, getDimensions(cm));
	          cm.curOp.forceUpdate = true;
	        }
	        if (!view) {
	          view = updateExternalMeasurement(cm, line);
	        }
	        var info = mapFromLineView(view, line, lineN);
	        return {
	          line: line,
	          view: view,
	          rect: null,
	          map: info.map,
	          cache: info.cache,
	          before: info.before,
	          hasHeights: false
	        };
	      }

	      // Given a prepared measurement object, measures the position of an
	      // actual character (or fetches it from the cache).
	      function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
	        if (prepared.before) {
	          ch = -1;
	        }
	        var key = ch + (bias || ""),
	          found;
	        if (prepared.cache.hasOwnProperty(key)) {
	          found = prepared.cache[key];
	        } else {
	          if (!prepared.rect) {
	            prepared.rect = prepared.view.text.getBoundingClientRect();
	          }
	          if (!prepared.hasHeights) {
	            ensureLineHeights(cm, prepared.view, prepared.rect);
	            prepared.hasHeights = true;
	          }
	          found = measureCharInner(cm, prepared, ch, bias);
	          if (!found.bogus) {
	            prepared.cache[key] = found;
	          }
	        }
	        return {
	          left: found.left,
	          right: found.right,
	          top: varHeight ? found.rtop : found.top,
	          bottom: varHeight ? found.rbottom : found.bottom
	        };
	      }
	      var nullRect = {
	        left: 0,
	        right: 0,
	        top: 0,
	        bottom: 0
	      };
	      function nodeAndOffsetInLineMap(map, ch, bias) {
	        var node, start, end, collapse, mStart, mEnd;
	        // First, search the line map for the text node corresponding to,
	        // or closest to, the target character.
	        for (var i = 0; i < map.length; i += 3) {
	          mStart = map[i];
	          mEnd = map[i + 1];
	          if (ch < mStart) {
	            start = 0;
	            end = 1;
	            collapse = "left";
	          } else if (ch < mEnd) {
	            start = ch - mStart;
	            end = start + 1;
	          } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
	            end = mEnd - mStart;
	            start = end - 1;
	            if (ch >= mEnd) {
	              collapse = "right";
	            }
	          }
	          if (start != null) {
	            node = map[i + 2];
	            if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) {
	              collapse = bias;
	            }
	            if (bias == "left" && start == 0) {
	              while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
	                node = map[(i -= 3) + 2];
	                collapse = "left";
	              }
	            }
	            if (bias == "right" && start == mEnd - mStart) {
	              while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
	                node = map[(i += 3) + 2];
	                collapse = "right";
	              }
	            }
	            break;
	          }
	        }
	        return {
	          node: node,
	          start: start,
	          end: end,
	          collapse: collapse,
	          coverStart: mStart,
	          coverEnd: mEnd
	        };
	      }
	      function getUsefulRect(rects, bias) {
	        var rect = nullRect;
	        if (bias == "left") {
	          for (var i = 0; i < rects.length; i++) {
	            if ((rect = rects[i]).left != rect.right) {
	              break;
	            }
	          }
	        } else {
	          for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
	            if ((rect = rects[i$1]).left != rect.right) {
	              break;
	            }
	          }
	        }
	        return rect;
	      }
	      function measureCharInner(cm, prepared, ch, bias) {
	        var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
	        var node = place.node,
	          start = place.start,
	          end = place.end,
	          collapse = place.collapse;
	        var rect;
	        if (node.nodeType == 3) {
	          // If it is a text node, use a range to retrieve the coordinates.
	          for (var i$1 = 0; i$1 < 4; i$1++) {
	            // Retry a maximum of 4 times when nonsense rectangles are returned
	            while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) {
	              --start;
	            }
	            while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) {
	              ++end;
	            }
	            if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
	              rect = node.parentNode.getBoundingClientRect();
	            } else {
	              rect = getUsefulRect(range(node, start, end).getClientRects(), bias);
	            }
	            if (rect.left || rect.right || start == 0) {
	              break;
	            }
	            end = start;
	            start = start - 1;
	            collapse = "right";
	          }
	          if (ie && ie_version < 11) {
	            rect = maybeUpdateRectForZooming(cm.display.measure, rect);
	          }
	        } else {
	          // If it is a widget, simply get the box for the whole widget.
	          if (start > 0) {
	            collapse = bias = "right";
	          }
	          var rects;
	          if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) {
	            rect = rects[bias == "right" ? rects.length - 1 : 0];
	          } else {
	            rect = node.getBoundingClientRect();
	          }
	        }
	        if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
	          var rSpan = node.parentNode.getClientRects()[0];
	          if (rSpan) {
	            rect = {
	              left: rSpan.left,
	              right: rSpan.left + charWidth(cm.display),
	              top: rSpan.top,
	              bottom: rSpan.bottom
	            };
	          } else {
	            rect = nullRect;
	          }
	        }
	        var rtop = rect.top - prepared.rect.top,
	          rbot = rect.bottom - prepared.rect.top;
	        var mid = (rtop + rbot) / 2;
	        var heights = prepared.view.measure.heights;
	        var i = 0;
	        for (; i < heights.length - 1; i++) {
	          if (mid < heights[i]) {
	            break;
	          }
	        }
	        var top = i ? heights[i - 1] : 0,
	          bot = heights[i];
	        var result = {
	          left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
	          right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
	          top: top,
	          bottom: bot
	        };
	        if (!rect.left && !rect.right) {
	          result.bogus = true;
	        }
	        if (!cm.options.singleCursorHeightPerLine) {
	          result.rtop = rtop;
	          result.rbottom = rbot;
	        }
	        return result;
	      }

	      // Work around problem with bounding client rects on ranges being
	      // returned incorrectly when zoomed on IE10 and below.
	      function maybeUpdateRectForZooming(measure, rect) {
	        if (!window.screen || screen.logicalXDPI == null || screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) {
	          return rect;
	        }
	        var scaleX = screen.logicalXDPI / screen.deviceXDPI;
	        var scaleY = screen.logicalYDPI / screen.deviceYDPI;
	        return {
	          left: rect.left * scaleX,
	          right: rect.right * scaleX,
	          top: rect.top * scaleY,
	          bottom: rect.bottom * scaleY
	        };
	      }
	      function clearLineMeasurementCacheFor(lineView) {
	        if (lineView.measure) {
	          lineView.measure.cache = {};
	          lineView.measure.heights = null;
	          if (lineView.rest) {
	            for (var i = 0; i < lineView.rest.length; i++) {
	              lineView.measure.caches[i] = {};
	            }
	          }
	        }
	      }
	      function clearLineMeasurementCache(cm) {
	        cm.display.externalMeasure = null;
	        removeChildren(cm.display.lineMeasure);
	        for (var i = 0; i < cm.display.view.length; i++) {
	          clearLineMeasurementCacheFor(cm.display.view[i]);
	        }
	      }
	      function clearCaches(cm) {
	        clearLineMeasurementCache(cm);
	        cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
	        if (!cm.options.lineWrapping) {
	          cm.display.maxLineChanged = true;
	        }
	        cm.display.lineNumChars = null;
	      }
	      function pageScrollX(doc) {
	        // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
	        // which causes page_Offset and bounding client rects to use
	        // different reference viewports and invalidate our calculations.
	        if (chrome && android) {
	          return -(doc.body.getBoundingClientRect().left - parseInt(getComputedStyle(doc.body).marginLeft));
	        }
	        return doc.defaultView.pageXOffset || (doc.documentElement || doc.body).scrollLeft;
	      }
	      function pageScrollY(doc) {
	        if (chrome && android) {
	          return -(doc.body.getBoundingClientRect().top - parseInt(getComputedStyle(doc.body).marginTop));
	        }
	        return doc.defaultView.pageYOffset || (doc.documentElement || doc.body).scrollTop;
	      }
	      function widgetTopHeight(lineObj) {
	        var ref = visualLine(lineObj);
	        var widgets = ref.widgets;
	        var height = 0;
	        if (widgets) {
	          for (var i = 0; i < widgets.length; ++i) {
	            if (widgets[i].above) {
	              height += widgetHeight(widgets[i]);
	            }
	          }
	        }
	        return height;
	      }

	      // Converts a {top, bottom, left, right} box from line-local
	      // coordinates into another coordinate system. Context may be one of
	      // "line", "div" (display.lineDiv), "local"./null (editor), "window",
	      // or "page".
	      function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
	        if (!includeWidgets) {
	          var height = widgetTopHeight(lineObj);
	          rect.top += height;
	          rect.bottom += height;
	        }
	        if (context == "line") {
	          return rect;
	        }
	        if (!context) {
	          context = "local";
	        }
	        var yOff = heightAtLine(lineObj);
	        if (context == "local") {
	          yOff += paddingTop(cm.display);
	        } else {
	          yOff -= cm.display.viewOffset;
	        }
	        if (context == "page" || context == "window") {
	          var lOff = cm.display.lineSpace.getBoundingClientRect();
	          yOff += lOff.top + (context == "window" ? 0 : pageScrollY(doc(cm)));
	          var xOff = lOff.left + (context == "window" ? 0 : pageScrollX(doc(cm)));
	          rect.left += xOff;
	          rect.right += xOff;
	        }
	        rect.top += yOff;
	        rect.bottom += yOff;
	        return rect;
	      }

	      // Coverts a box from "div" coords to another coordinate system.
	      // Context may be "window", "page", "div", or "local"./null.
	      function fromCoordSystem(cm, coords, context) {
	        if (context == "div") {
	          return coords;
	        }
	        var left = coords.left,
	          top = coords.top;
	        // First move into "page" coordinate system
	        if (context == "page") {
	          left -= pageScrollX(doc(cm));
	          top -= pageScrollY(doc(cm));
	        } else if (context == "local" || !context) {
	          var localBox = cm.display.sizer.getBoundingClientRect();
	          left += localBox.left;
	          top += localBox.top;
	        }
	        var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
	        return {
	          left: left - lineSpaceBox.left,
	          top: top - lineSpaceBox.top
	        };
	      }
	      function charCoords(cm, pos, context, lineObj, bias) {
	        if (!lineObj) {
	          lineObj = getLine(cm.doc, pos.line);
	        }
	        return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
	      }

	      // Returns a box for a given cursor position, which may have an
	      // 'other' property containing the position of the secondary cursor
	      // on a bidi boundary.
	      // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
	      // and after `char - 1` in writing order of `char - 1`
	      // A cursor Pos(line, char, "after") is on the same visual line as `char`
	      // and before `char` in writing order of `char`
	      // Examples (upper-case letters are RTL, lower-case are LTR):
	      //     Pos(0, 1, ...)
	      //     before   after
	      // ab     a|b     a|b
	      // aB     a|B     aB|
	      // Ab     |Ab     A|b
	      // AB     B|A     B|A
	      // Every position after the last character on a line is considered to stick
	      // to the last character on the line.
	      function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
	        lineObj = lineObj || getLine(cm.doc, pos.line);
	        if (!preparedMeasure) {
	          preparedMeasure = prepareMeasureForLine(cm, lineObj);
	        }
	        function get(ch, right) {
	          var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
	          if (right) {
	            m.left = m.right;
	          } else {
	            m.right = m.left;
	          }
	          return intoCoordSystem(cm, lineObj, m, context);
	        }
	        var order = getOrder(lineObj, cm.doc.direction),
	          ch = pos.ch,
	          sticky = pos.sticky;
	        if (ch >= lineObj.text.length) {
	          ch = lineObj.text.length;
	          sticky = "before";
	        } else if (ch <= 0) {
	          ch = 0;
	          sticky = "after";
	        }
	        if (!order) {
	          return get(sticky == "before" ? ch - 1 : ch, sticky == "before");
	        }
	        function getBidi(ch, partPos, invert) {
	          var part = order[partPos],
	            right = part.level == 1;
	          return get(invert ? ch - 1 : ch, right != invert);
	        }
	        var partPos = getBidiPartAt(order, ch, sticky);
	        var other = bidiOther;
	        var val = getBidi(ch, partPos, sticky == "before");
	        if (other != null) {
	          val.other = getBidi(ch, other, sticky != "before");
	        }
	        return val;
	      }

	      // Used to cheaply estimate the coordinates for a position. Used for
	      // intermediate scroll updates.
	      function estimateCoords(cm, pos) {
	        var left = 0;
	        pos = clipPos(cm.doc, pos);
	        if (!cm.options.lineWrapping) {
	          left = charWidth(cm.display) * pos.ch;
	        }
	        var lineObj = getLine(cm.doc, pos.line);
	        var top = heightAtLine(lineObj) + paddingTop(cm.display);
	        return {
	          left: left,
	          right: left,
	          top: top,
	          bottom: top + lineObj.height
	        };
	      }

	      // Positions returned by coordsChar contain some extra information.
	      // xRel is the relative x position of the input coordinates compared
	      // to the found position (so xRel > 0 means the coordinates are to
	      // the right of the character position, for example). When outside
	      // is true, that means the coordinates lie outside the line's
	      // vertical range.
	      function PosWithInfo(line, ch, sticky, outside, xRel) {
	        var pos = Pos(line, ch, sticky);
	        pos.xRel = xRel;
	        if (outside) {
	          pos.outside = outside;
	        }
	        return pos;
	      }

	      // Compute the character position closest to the given coordinates.
	      // Input must be lineSpace-local ("div" coordinate system).
	      function coordsChar(cm, x, y) {
	        var doc = cm.doc;
	        y += cm.display.viewOffset;
	        if (y < 0) {
	          return PosWithInfo(doc.first, 0, null, -1, -1);
	        }
	        var lineN = lineAtHeight(doc, y),
	          last = doc.first + doc.size - 1;
	        if (lineN > last) {
	          return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1);
	        }
	        if (x < 0) {
	          x = 0;
	        }
	        var lineObj = getLine(doc, lineN);
	        for (;;) {
	          var found = coordsCharInner(cm, lineObj, lineN, x, y);
	          var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
	          if (!collapsed) {
	            return found;
	          }
	          var rangeEnd = collapsed.find(1);
	          if (rangeEnd.line == lineN) {
	            return rangeEnd;
	          }
	          lineObj = getLine(doc, lineN = rangeEnd.line);
	        }
	      }
	      function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
	        y -= widgetTopHeight(lineObj);
	        var end = lineObj.text.length;
	        var begin = findFirst(function (ch) {
	          return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y;
	        }, end, 0);
	        end = findFirst(function (ch) {
	          return measureCharPrepared(cm, preparedMeasure, ch).top > y;
	        }, begin, end);
	        return {
	          begin: begin,
	          end: end
	        };
	      }
	      function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
	        if (!preparedMeasure) {
	          preparedMeasure = prepareMeasureForLine(cm, lineObj);
	        }
	        var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
	        return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop);
	      }

	      // Returns true if the given side of a box is after the given
	      // coordinates, in top-to-bottom, left-to-right order.
	      function boxIsAfter(box, x, y, left) {
	        return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x;
	      }
	      function coordsCharInner(cm, lineObj, lineNo, x, y) {
	        // Move y into line-local coordinate space
	        y -= heightAtLine(lineObj);
	        var preparedMeasure = prepareMeasureForLine(cm, lineObj);
	        // When directly calling `measureCharPrepared`, we have to adjust
	        // for the widgets at this line.
	        var widgetHeight = widgetTopHeight(lineObj);
	        var begin = 0,
	          end = lineObj.text.length,
	          ltr = true;
	        var order = getOrder(lineObj, cm.doc.direction);
	        // If the line isn't plain left-to-right text, first figure out
	        // which bidi section the coordinates fall into.
	        if (order) {
	          var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)(cm, lineObj, lineNo, preparedMeasure, order, x, y);
	          ltr = part.level != 1;
	          // The awkward -1 offsets are needed because findFirst (called
	          // on these below) will treat its first bound as inclusive,
	          // second as exclusive, but we want to actually address the
	          // characters in the part's range
	          begin = ltr ? part.from : part.to - 1;
	          end = ltr ? part.to : part.from - 1;
	        }

	        // A binary search to find the first character whose bounding box
	        // starts after the coordinates. If we run across any whose box wrap
	        // the coordinates, store that.
	        var chAround = null,
	          boxAround = null;
	        var ch = findFirst(function (ch) {
	          var box = measureCharPrepared(cm, preparedMeasure, ch);
	          box.top += widgetHeight;
	          box.bottom += widgetHeight;
	          if (!boxIsAfter(box, x, y, false)) {
	            return false;
	          }
	          if (box.top <= y && box.left <= x) {
	            chAround = ch;
	            boxAround = box;
	          }
	          return true;
	        }, begin, end);
	        var baseX,
	          sticky,
	          outside = false;
	        // If a box around the coordinates was found, use that
	        if (boxAround) {
	          // Distinguish coordinates nearer to the left or right side of the box
	          var atLeft = x - boxAround.left < boxAround.right - x,
	            atStart = atLeft == ltr;
	          ch = chAround + (atStart ? 0 : 1);
	          sticky = atStart ? "after" : "before";
	          baseX = atLeft ? boxAround.left : boxAround.right;
	        } else {
	          // (Adjust for extended bound, if necessary.)
	          if (!ltr && (ch == end || ch == begin)) {
	            ch++;
	          }
	          // To determine which side to associate with, get the box to the
	          // left of the character and compare it's vertical position to the
	          // coordinates
	          sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y == ltr ? "after" : "before";
	          // Now get accurate coordinates for this place, in order to get a
	          // base X position
	          var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
	          baseX = coords.left;
	          outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
	        }
	        ch = skipExtendingChars(lineObj.text, ch, 1);
	        return PosWithInfo(lineNo, ch, sticky, outside, x - baseX);
	      }
	      function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
	        // Bidi parts are sorted left-to-right, and in a non-line-wrapping
	        // situation, we can take this ordering to correspond to the visual
	        // ordering. This finds the first part whose end is after the given
	        // coordinates.
	        var index = findFirst(function (i) {
	          var part = order[i],
	            ltr = part.level != 1;
	          return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"), "line", lineObj, preparedMeasure), x, y, true);
	        }, 0, order.length - 1);
	        var part = order[index];
	        // If this isn't the first part, the part's start is also after
	        // the coordinates, and the coordinates aren't on the same line as
	        // that start, move one part back.
	        if (index > 0) {
	          var ltr = part.level != 1;
	          var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"), "line", lineObj, preparedMeasure);
	          if (boxIsAfter(start, x, y, true) && start.top > y) {
	            part = order[index - 1];
	          }
	        }
	        return part;
	      }
	      function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
	        // In a wrapped line, rtl text on wrapping boundaries can do things
	        // that don't correspond to the ordering in our `order` array at
	        // all, so a binary search doesn't work, and we want to return a
	        // part that only spans one line so that the binary search in
	        // coordsCharInner is safe. As such, we first find the extent of the
	        // wrapped line, and then do a flat search in which we discard any
	        // spans that aren't on the line.
	        var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
	        var begin = ref.begin;
	        var end = ref.end;
	        if (/\s/.test(lineObj.text.charAt(end - 1))) {
	          end--;
	        }
	        var part = null,
	          closestDist = null;
	        for (var i = 0; i < order.length; i++) {
	          var p = order[i];
	          if (p.from >= end || p.to <= begin) {
	            continue;
	          }
	          var ltr = p.level != 1;
	          var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
	          // Weigh against spans ending before this, so that they are only
	          // picked if nothing ends after
	          var dist = endX < x ? x - endX + 1e9 : endX - x;
	          if (!part || closestDist > dist) {
	            part = p;
	            closestDist = dist;
	          }
	        }
	        if (!part) {
	          part = order[order.length - 1];
	        }
	        // Clip the part to the wrapped line.
	        if (part.from < begin) {
	          part = {
	            from: begin,
	            to: part.to,
	            level: part.level
	          };
	        }
	        if (part.to > end) {
	          part = {
	            from: part.from,
	            to: end,
	            level: part.level
	          };
	        }
	        return part;
	      }
	      var measureText;
	      // Compute the default text height.
	      function textHeight(display) {
	        if (display.cachedTextHeight != null) {
	          return display.cachedTextHeight;
	        }
	        if (measureText == null) {
	          measureText = elt("pre", null, "CodeMirror-line-like");
	          // Measure a bunch of lines, for browsers that compute
	          // fractional heights.
	          for (var i = 0; i < 49; ++i) {
	            measureText.appendChild(document.createTextNode("x"));
	            measureText.appendChild(elt("br"));
	          }
	          measureText.appendChild(document.createTextNode("x"));
	        }
	        removeChildrenAndAdd(display.measure, measureText);
	        var height = measureText.offsetHeight / 50;
	        if (height > 3) {
	          display.cachedTextHeight = height;
	        }
	        removeChildren(display.measure);
	        return height || 1;
	      }

	      // Compute the default character width.
	      function charWidth(display) {
	        if (display.cachedCharWidth != null) {
	          return display.cachedCharWidth;
	        }
	        var anchor = elt("span", "xxxxxxxxxx");
	        var pre = elt("pre", [anchor], "CodeMirror-line-like");
	        removeChildrenAndAdd(display.measure, pre);
	        var rect = anchor.getBoundingClientRect(),
	          width = (rect.right - rect.left) / 10;
	        if (width > 2) {
	          display.cachedCharWidth = width;
	        }
	        return width || 10;
	      }

	      // Do a bulk-read of the DOM positions and sizes needed to draw the
	      // view, so that we don't interleave reading and writing to the DOM.
	      function getDimensions(cm) {
	        var d = cm.display,
	          left = {},
	          width = {};
	        var gutterLeft = d.gutters.clientLeft;
	        for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
	          var id = cm.display.gutterSpecs[i].className;
	          left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
	          width[id] = n.clientWidth;
	        }
	        return {
	          fixedPos: compensateForHScroll(d),
	          gutterTotalWidth: d.gutters.offsetWidth,
	          gutterLeft: left,
	          gutterWidth: width,
	          wrapperWidth: d.wrapper.clientWidth
	        };
	      }

	      // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
	      // but using getBoundingClientRect to get a sub-pixel-accurate
	      // result.
	      function compensateForHScroll(display) {
	        return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
	      }

	      // Returns a function that estimates the height of a line, to use as
	      // first approximation until the line becomes visible (and is thus
	      // properly measurable).
	      function estimateHeight(cm) {
	        var th = textHeight(cm.display),
	          wrapping = cm.options.lineWrapping;
	        var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
	        return function (line) {
	          if (lineIsHidden(cm.doc, line)) {
	            return 0;
	          }
	          var widgetsHeight = 0;
	          if (line.widgets) {
	            for (var i = 0; i < line.widgets.length; i++) {
	              if (line.widgets[i].height) {
	                widgetsHeight += line.widgets[i].height;
	              }
	            }
	          }
	          if (wrapping) {
	            return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
	          } else {
	            return widgetsHeight + th;
	          }
	        };
	      }
	      function estimateLineHeights(cm) {
	        var doc = cm.doc,
	          est = estimateHeight(cm);
	        doc.iter(function (line) {
	          var estHeight = est(line);
	          if (estHeight != line.height) {
	            updateLineHeight(line, estHeight);
	          }
	        });
	      }

	      // Given a mouse event, find the corresponding position. If liberal
	      // is false, it checks whether a gutter or scrollbar was clicked,
	      // and returns null if it was. forRect is used by rectangular
	      // selections, and tries to estimate a character position even for
	      // coordinates beyond the right of the text.
	      function posFromMouse(cm, e, liberal, forRect) {
	        var display = cm.display;
	        if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") {
	          return null;
	        }
	        var x,
	          y,
	          space = display.lineSpace.getBoundingClientRect();
	        // Fails unpredictably on IE[67] when mouse is dragged around quickly.
	        try {
	          x = e.clientX - space.left;
	          y = e.clientY - space.top;
	        } catch (e$1) {
	          return null;
	        }
	        var coords = coordsChar(cm, x, y),
	          line;
	        if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
	          var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
	          coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
	        }
	        return coords;
	      }

	      // Find the view element corresponding to a given line. Return null
	      // when the line isn't visible.
	      function findViewIndex(cm, n) {
	        if (n >= cm.display.viewTo) {
	          return null;
	        }
	        n -= cm.display.viewFrom;
	        if (n < 0) {
	          return null;
	        }
	        var view = cm.display.view;
	        for (var i = 0; i < view.length; i++) {
	          n -= view[i].size;
	          if (n < 0) {
	            return i;
	          }
	        }
	      }

	      // Updates the display.view data structure for a given change to the
	      // document. From and to are in pre-change coordinates. Lendiff is
	      // the amount of lines added or subtracted by the change. This is
	      // used for changes that span multiple lines, or change the way
	      // lines are divided into visual lines. regLineChange (below)
	      // registers single-line changes.
	      function regChange(cm, from, to, lendiff) {
	        if (from == null) {
	          from = cm.doc.first;
	        }
	        if (to == null) {
	          to = cm.doc.first + cm.doc.size;
	        }
	        if (!lendiff) {
	          lendiff = 0;
	        }
	        var display = cm.display;
	        if (lendiff && to < display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers > from)) {
	          display.updateLineNumbers = from;
	        }
	        cm.curOp.viewChanged = true;
	        if (from >= display.viewTo) {
	          // Change after
	          if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) {
	            resetView(cm);
	          }
	        } else if (to <= display.viewFrom) {
	          // Change before
	          if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
	            resetView(cm);
	          } else {
	            display.viewFrom += lendiff;
	            display.viewTo += lendiff;
	          }
	        } else if (from <= display.viewFrom && to >= display.viewTo) {
	          // Full overlap
	          resetView(cm);
	        } else if (from <= display.viewFrom) {
	          // Top overlap
	          var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
	          if (cut) {
	            display.view = display.view.slice(cut.index);
	            display.viewFrom = cut.lineN;
	            display.viewTo += lendiff;
	          } else {
	            resetView(cm);
	          }
	        } else if (to >= display.viewTo) {
	          // Bottom overlap
	          var cut$1 = viewCuttingPoint(cm, from, from, -1);
	          if (cut$1) {
	            display.view = display.view.slice(0, cut$1.index);
	            display.viewTo = cut$1.lineN;
	          } else {
	            resetView(cm);
	          }
	        } else {
	          // Gap in the middle
	          var cutTop = viewCuttingPoint(cm, from, from, -1);
	          var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
	          if (cutTop && cutBot) {
	            display.view = display.view.slice(0, cutTop.index).concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)).concat(display.view.slice(cutBot.index));
	            display.viewTo += lendiff;
	          } else {
	            resetView(cm);
	          }
	        }
	        var ext = display.externalMeasured;
	        if (ext) {
	          if (to < ext.lineN) {
	            ext.lineN += lendiff;
	          } else if (from < ext.lineN + ext.size) {
	            display.externalMeasured = null;
	          }
	        }
	      }

	      // Register a change to a single line. Type must be one of "text",
	      // "gutter", "class", "widget"
	      function regLineChange(cm, line, type) {
	        cm.curOp.viewChanged = true;
	        var display = cm.display,
	          ext = cm.display.externalMeasured;
	        if (ext && line >= ext.lineN && line < ext.lineN + ext.size) {
	          display.externalMeasured = null;
	        }
	        if (line < display.viewFrom || line >= display.viewTo) {
	          return;
	        }
	        var lineView = display.view[findViewIndex(cm, line)];
	        if (lineView.node == null) {
	          return;
	        }
	        var arr = lineView.changes || (lineView.changes = []);
	        if (indexOf(arr, type) == -1) {
	          arr.push(type);
	        }
	      }

	      // Clear the view.
	      function resetView(cm) {
	        cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
	        cm.display.view = [];
	        cm.display.viewOffset = 0;
	      }
	      function viewCuttingPoint(cm, oldN, newN, dir) {
	        var index = findViewIndex(cm, oldN),
	          diff,
	          view = cm.display.view;
	        if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) {
	          return {
	            index: index,
	            lineN: newN
	          };
	        }
	        var n = cm.display.viewFrom;
	        for (var i = 0; i < index; i++) {
	          n += view[i].size;
	        }
	        if (n != oldN) {
	          if (dir > 0) {
	            if (index == view.length - 1) {
	              return null;
	            }
	            diff = n + view[index].size - oldN;
	            index++;
	          } else {
	            diff = n - oldN;
	          }
	          oldN += diff;
	          newN += diff;
	        }
	        while (visualLineNo(cm.doc, newN) != newN) {
	          if (index == (dir < 0 ? 0 : view.length - 1)) {
	            return null;
	          }
	          newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
	          index += dir;
	        }
	        return {
	          index: index,
	          lineN: newN
	        };
	      }

	      // Force the view to cover a given range, adding empty view element
	      // or clipping off existing ones as needed.
	      function adjustView(cm, from, to) {
	        var display = cm.display,
	          view = display.view;
	        if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
	          display.view = buildViewArray(cm, from, to);
	          display.viewFrom = from;
	        } else {
	          if (display.viewFrom > from) {
	            display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
	          } else if (display.viewFrom < from) {
	            display.view = display.view.slice(findViewIndex(cm, from));
	          }
	          display.viewFrom = from;
	          if (display.viewTo < to) {
	            display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
	          } else if (display.viewTo > to) {
	            display.view = display.view.slice(0, findViewIndex(cm, to));
	          }
	        }
	        display.viewTo = to;
	      }

	      // Count the number of lines in the view whose DOM representation is
	      // out of date (or nonexistent).
	      function countDirtyView(cm) {
	        var view = cm.display.view,
	          dirty = 0;
	        for (var i = 0; i < view.length; i++) {
	          var lineView = view[i];
	          if (!lineView.hidden && (!lineView.node || lineView.changes)) {
	            ++dirty;
	          }
	        }
	        return dirty;
	      }
	      function updateSelection(cm) {
	        cm.display.input.showSelection(cm.display.input.prepareSelection());
	      }
	      function prepareSelection(cm, primary) {
	        if (primary === void 0) primary = true;
	        var doc = cm.doc,
	          result = {};
	        var curFragment = result.cursors = document.createDocumentFragment();
	        var selFragment = result.selection = document.createDocumentFragment();
	        var customCursor = cm.options.$customCursor;
	        if (customCursor) {
	          primary = true;
	        }
	        for (var i = 0; i < doc.sel.ranges.length; i++) {
	          if (!primary && i == doc.sel.primIndex) {
	            continue;
	          }
	          var range = doc.sel.ranges[i];
	          if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) {
	            continue;
	          }
	          var collapsed = range.empty();
	          if (customCursor) {
	            var head = customCursor(cm, range);
	            if (head) {
	              drawSelectionCursor(cm, head, curFragment);
	            }
	          } else if (collapsed || cm.options.showCursorWhenSelecting) {
	            drawSelectionCursor(cm, range.head, curFragment);
	          }
	          if (!collapsed) {
	            drawSelectionRange(cm, range, selFragment);
	          }
	        }
	        return result;
	      }

	      // Draws a cursor for the given range
	      function drawSelectionCursor(cm, head, output) {
	        var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
	        var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
	        cursor.style.left = pos.left + "px";
	        cursor.style.top = pos.top + "px";
	        cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
	        if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) {
	          var charPos = charCoords(cm, head, "div", null, null);
	          var width = charPos.right - charPos.left;
	          cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px";
	        }
	        if (pos.other) {
	          // Secondary cursor, shown when on a 'jump' in bi-directional text
	          var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
	          otherCursor.style.display = "";
	          otherCursor.style.left = pos.other.left + "px";
	          otherCursor.style.top = pos.other.top + "px";
	          otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
	        }
	      }
	      function cmpCoords(a, b) {
	        return a.top - b.top || a.left - b.left;
	      }

	      // Draws the given range as a highlighted selection
	      function drawSelectionRange(cm, range, output) {
	        var display = cm.display,
	          doc = cm.doc;
	        var fragment = document.createDocumentFragment();
	        var padding = paddingH(cm.display),
	          leftSide = padding.left;
	        var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
	        var docLTR = doc.direction == "ltr";
	        function add(left, top, width, bottom) {
	          if (top < 0) {
	            top = 0;
	          }
	          top = Math.round(top);
	          bottom = Math.round(bottom);
	          fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + "px;\n                             top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n                             height: " + (bottom - top) + "px"));
	        }
	        function drawForLine(line, fromArg, toArg) {
	          var lineObj = getLine(doc, line);
	          var lineLen = lineObj.text.length;
	          var start, end;
	          function coords(ch, bias) {
	            return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
	          }
	          function wrapX(pos, dir, side) {
	            var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
	            var prop = dir == "ltr" == (side == "after") ? "left" : "right";
	            var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
	            return coords(ch, prop)[prop];
	          }
	          var order = getOrder(lineObj, doc.direction);
	          iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
	            var ltr = dir == "ltr";
	            var fromPos = coords(from, ltr ? "left" : "right");
	            var toPos = coords(to - 1, ltr ? "right" : "left");
	            var openStart = fromArg == null && from == 0,
	              openEnd = toArg == null && to == lineLen;
	            var first = i == 0,
	              last = !order || i == order.length - 1;
	            if (toPos.top - fromPos.top <= 3) {
	              // Single line
	              var openLeft = (docLTR ? openStart : openEnd) && first;
	              var openRight = (docLTR ? openEnd : openStart) && last;
	              var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
	              var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
	              add(left, fromPos.top, right - left, fromPos.bottom);
	            } else {
	              // Multiple lines
	              var topLeft, topRight, botLeft, botRight;
	              if (ltr) {
	                topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
	                topRight = docLTR ? rightSide : wrapX(from, dir, "before");
	                botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
	                botRight = docLTR && openEnd && last ? rightSide : toPos.right;
	              } else {
	                topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
	                topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
	                botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
	                botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
	              }
	              add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
	              if (fromPos.bottom < toPos.top) {
	                add(leftSide, fromPos.bottom, null, toPos.top);
	              }
	              add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
	            }
	            if (!start || cmpCoords(fromPos, start) < 0) {
	              start = fromPos;
	            }
	            if (cmpCoords(toPos, start) < 0) {
	              start = toPos;
	            }
	            if (!end || cmpCoords(fromPos, end) < 0) {
	              end = fromPos;
	            }
	            if (cmpCoords(toPos, end) < 0) {
	              end = toPos;
	            }
	          });
	          return {
	            start: start,
	            end: end
	          };
	        }
	        var sFrom = range.from(),
	          sTo = range.to();
	        if (sFrom.line == sTo.line) {
	          drawForLine(sFrom.line, sFrom.ch, sTo.ch);
	        } else {
	          var fromLine = getLine(doc, sFrom.line),
	            toLine = getLine(doc, sTo.line);
	          var singleVLine = visualLine(fromLine) == visualLine(toLine);
	          var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
	          var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
	          if (singleVLine) {
	            if (leftEnd.top < rightStart.top - 2) {
	              add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
	              add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
	            } else {
	              add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
	            }
	          }
	          if (leftEnd.bottom < rightStart.top) {
	            add(leftSide, leftEnd.bottom, null, rightStart.top);
	          }
	        }
	        output.appendChild(fragment);
	      }

	      // Cursor-blinking
	      function restartBlink(cm) {
	        if (!cm.state.focused) {
	          return;
	        }
	        var display = cm.display;
	        clearInterval(display.blinker);
	        var on = true;
	        display.cursorDiv.style.visibility = "";
	        if (cm.options.cursorBlinkRate > 0) {
	          display.blinker = setInterval(function () {
	            if (!cm.hasFocus()) {
	              onBlur(cm);
	            }
	            display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
	          }, cm.options.cursorBlinkRate);
	        } else if (cm.options.cursorBlinkRate < 0) {
	          display.cursorDiv.style.visibility = "hidden";
	        }
	      }
	      function ensureFocus(cm) {
	        if (!cm.hasFocus()) {
	          cm.display.input.focus();
	          if (!cm.state.focused) {
	            onFocus(cm);
	          }
	        }
	      }
	      function delayBlurEvent(cm) {
	        cm.state.delayingBlurEvent = true;
	        setTimeout(function () {
	          if (cm.state.delayingBlurEvent) {
	            cm.state.delayingBlurEvent = false;
	            if (cm.state.focused) {
	              onBlur(cm);
	            }
	          }
	        }, 100);
	      }
	      function onFocus(cm, e) {
	        if (cm.state.delayingBlurEvent && !cm.state.draggingText) {
	          cm.state.delayingBlurEvent = false;
	        }
	        if (cm.options.readOnly == "nocursor") {
	          return;
	        }
	        if (!cm.state.focused) {
	          signal(cm, "focus", cm, e);
	          cm.state.focused = true;
	          addClass(cm.display.wrapper, "CodeMirror-focused");
	          // This test prevents this from firing when a context
	          // menu is closed (since the input reset would kill the
	          // select-all detection hack)
	          if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
	            cm.display.input.reset();
	            if (webkit) {
	              setTimeout(function () {
	                return cm.display.input.reset(true);
	              }, 20);
	            } // Issue #1730
	          }
	          cm.display.input.receivedFocus();
	        }
	        restartBlink(cm);
	      }
	      function onBlur(cm, e) {
	        if (cm.state.delayingBlurEvent) {
	          return;
	        }
	        if (cm.state.focused) {
	          signal(cm, "blur", cm, e);
	          cm.state.focused = false;
	          rmClass(cm.display.wrapper, "CodeMirror-focused");
	        }
	        clearInterval(cm.display.blinker);
	        setTimeout(function () {
	          if (!cm.state.focused) {
	            cm.display.shift = false;
	          }
	        }, 150);
	      }

	      // Read the actual heights of the rendered lines, and update their
	      // stored heights to match.
	      function updateHeightsInViewport(cm) {
	        var display = cm.display;
	        var prevBottom = display.lineDiv.offsetTop;
	        var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top);
	        var oldHeight = display.lineDiv.getBoundingClientRect().top;
	        var mustScroll = 0;
	        for (var i = 0; i < display.view.length; i++) {
	          var cur = display.view[i],
	            wrapping = cm.options.lineWrapping;
	          var height = void 0,
	            width = 0;
	          if (cur.hidden) {
	            continue;
	          }
	          oldHeight += cur.line.height;
	          if (ie && ie_version < 8) {
	            var bot = cur.node.offsetTop + cur.node.offsetHeight;
	            height = bot - prevBottom;
	            prevBottom = bot;
	          } else {
	            var box = cur.node.getBoundingClientRect();
	            height = box.bottom - box.top;
	            // Check that lines don't extend past the right of the current
	            // editor width
	            if (!wrapping && cur.text.firstChild) {
	              width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1;
	            }
	          }
	          var diff = cur.line.height - height;
	          if (diff > .005 || diff < -5e-3) {
	            if (oldHeight < viewTop) {
	              mustScroll -= diff;
	            }
	            updateLineHeight(cur.line, height);
	            updateWidgetHeight(cur.line);
	            if (cur.rest) {
	              for (var j = 0; j < cur.rest.length; j++) {
	                updateWidgetHeight(cur.rest[j]);
	              }
	            }
	          }
	          if (width > cm.display.sizerWidth) {
	            var chWidth = Math.ceil(width / charWidth(cm.display));
	            if (chWidth > cm.display.maxLineLength) {
	              cm.display.maxLineLength = chWidth;
	              cm.display.maxLine = cur.line;
	              cm.display.maxLineChanged = true;
	            }
	          }
	        }
	        if (Math.abs(mustScroll) > 2) {
	          display.scroller.scrollTop += mustScroll;
	        }
	      }

	      // Read and store the height of line widgets associated with the
	      // given line.
	      function updateWidgetHeight(line) {
	        if (line.widgets) {
	          for (var i = 0; i < line.widgets.length; ++i) {
	            var w = line.widgets[i],
	              parent = w.node.parentNode;
	            if (parent) {
	              w.height = parent.offsetHeight;
	            }
	          }
	        }
	      }

	      // Compute the lines that are visible in a given viewport (defaults
	      // the current scroll position). viewport may contain top,
	      // height, and ensure (see op.scrollToPos) properties.
	      function visibleLines(display, doc, viewport) {
	        var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
	        top = Math.floor(top - paddingTop(display));
	        var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
	        var from = lineAtHeight(doc, top),
	          to = lineAtHeight(doc, bottom);
	        // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
	        // forces those lines into the viewport (if possible).
	        if (viewport && viewport.ensure) {
	          var ensureFrom = viewport.ensure.from.line,
	            ensureTo = viewport.ensure.to.line;
	          if (ensureFrom < from) {
	            from = ensureFrom;
	            to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
	          } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
	            from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
	            to = ensureTo;
	          }
	        }
	        return {
	          from: from,
	          to: Math.max(to, from + 1)
	        };
	      }

	      // SCROLLING THINGS INTO VIEW

	      // If an editor sits on the top or bottom of the window, partially
	      // scrolled out of view, this ensures that the cursor is visible.
	      function maybeScrollWindow(cm, rect) {
	        if (signalDOMEvent(cm, "scrollCursorIntoView")) {
	          return;
	        }
	        var display = cm.display,
	          box = display.sizer.getBoundingClientRect(),
	          doScroll = null;
	        var doc = display.wrapper.ownerDocument;
	        if (rect.top + box.top < 0) {
	          doScroll = true;
	        } else if (rect.bottom + box.top > (doc.defaultView.innerHeight || doc.documentElement.clientHeight)) {
	          doScroll = false;
	        }
	        if (doScroll != null && !phantom) {
	          var scrollNode = elt("div", "\u200b", null, "position: absolute;\n                         top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n                         height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n                         left: " + rect.left + "px; width: " + Math.max(2, rect.right - rect.left) + "px;");
	          cm.display.lineSpace.appendChild(scrollNode);
	          scrollNode.scrollIntoView(doScroll);
	          cm.display.lineSpace.removeChild(scrollNode);
	        }
	      }

	      // Scroll a given position into view (immediately), verifying that
	      // it actually became visible (as line heights are accurately
	      // measured, the position of something may 'drift' during drawing).
	      function scrollPosIntoView(cm, pos, end, margin) {
	        if (margin == null) {
	          margin = 0;
	        }
	        var rect;
	        if (!cm.options.lineWrapping && pos == end) {
	          // Set pos and end to the cursor positions around the character pos sticks to
	          // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
	          // If pos == Pos(_, 0, "before"), pos and end are unchanged
	          end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
	          pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
	        }
	        for (var limit = 0; limit < 5; limit++) {
	          var changed = false;
	          var coords = cursorCoords(cm, pos);
	          var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
	          rect = {
	            left: Math.min(coords.left, endCoords.left),
	            top: Math.min(coords.top, endCoords.top) - margin,
	            right: Math.max(coords.left, endCoords.left),
	            bottom: Math.max(coords.bottom, endCoords.bottom) + margin
	          };
	          var scrollPos = calculateScrollPos(cm, rect);
	          var startTop = cm.doc.scrollTop,
	            startLeft = cm.doc.scrollLeft;
	          if (scrollPos.scrollTop != null) {
	            updateScrollTop(cm, scrollPos.scrollTop);
	            if (Math.abs(cm.doc.scrollTop - startTop) > 1) {
	              changed = true;
	            }
	          }
	          if (scrollPos.scrollLeft != null) {
	            setScrollLeft(cm, scrollPos.scrollLeft);
	            if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) {
	              changed = true;
	            }
	          }
	          if (!changed) {
	            break;
	          }
	        }
	        return rect;
	      }

	      // Scroll a given set of coordinates into view (immediately).
	      function scrollIntoView(cm, rect) {
	        var scrollPos = calculateScrollPos(cm, rect);
	        if (scrollPos.scrollTop != null) {
	          updateScrollTop(cm, scrollPos.scrollTop);
	        }
	        if (scrollPos.scrollLeft != null) {
	          setScrollLeft(cm, scrollPos.scrollLeft);
	        }
	      }

	      // Calculate a new scroll position needed to scroll the given
	      // rectangle into view. Returns an object with scrollTop and
	      // scrollLeft properties. When these are undefined, the
	      // vertical/horizontal position does not need to be adjusted.
	      function calculateScrollPos(cm, rect) {
	        var display = cm.display,
	          snapMargin = textHeight(cm.display);
	        if (rect.top < 0) {
	          rect.top = 0;
	        }
	        var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
	        var screen = displayHeight(cm),
	          result = {};
	        if (rect.bottom - rect.top > screen) {
	          rect.bottom = rect.top + screen;
	        }
	        var docBottom = cm.doc.height + paddingVert(display);
	        var atTop = rect.top < snapMargin,
	          atBottom = rect.bottom > docBottom - snapMargin;
	        if (rect.top < screentop) {
	          result.scrollTop = atTop ? 0 : rect.top;
	        } else if (rect.bottom > screentop + screen) {
	          var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
	          if (newTop != screentop) {
	            result.scrollTop = newTop;
	          }
	        }
	        var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
	        var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
	        var screenw = displayWidth(cm) - display.gutters.offsetWidth;
	        var tooWide = rect.right - rect.left > screenw;
	        if (tooWide) {
	          rect.right = rect.left + screenw;
	        }
	        if (rect.left < 10) {
	          result.scrollLeft = 0;
	        } else if (rect.left < screenleft) {
	          result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10));
	        } else if (rect.right > screenw + screenleft - 3) {
	          result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw;
	        }
	        return result;
	      }

	      // Store a relative adjustment to the scroll position in the current
	      // operation (to be applied when the operation finishes).
	      function addToScrollTop(cm, top) {
	        if (top == null) {
	          return;
	        }
	        resolveScrollToPos(cm);
	        cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
	      }

	      // Make sure that at the end of the operation the current cursor is
	      // shown.
	      function ensureCursorVisible(cm) {
	        resolveScrollToPos(cm);
	        var cur = cm.getCursor();
	        cm.curOp.scrollToPos = {
	          from: cur,
	          to: cur,
	          margin: cm.options.cursorScrollMargin
	        };
	      }
	      function scrollToCoords(cm, x, y) {
	        if (x != null || y != null) {
	          resolveScrollToPos(cm);
	        }
	        if (x != null) {
	          cm.curOp.scrollLeft = x;
	        }
	        if (y != null) {
	          cm.curOp.scrollTop = y;
	        }
	      }
	      function scrollToRange(cm, range) {
	        resolveScrollToPos(cm);
	        cm.curOp.scrollToPos = range;
	      }

	      // When an operation has its scrollToPos property set, and another
	      // scroll action is applied before the end of the operation, this
	      // 'simulates' scrolling that position into view in a cheap way, so
	      // that the effect of intermediate scroll commands is not ignored.
	      function resolveScrollToPos(cm) {
	        var range = cm.curOp.scrollToPos;
	        if (range) {
	          cm.curOp.scrollToPos = null;
	          var from = estimateCoords(cm, range.from),
	            to = estimateCoords(cm, range.to);
	          scrollToCoordsRange(cm, from, to, range.margin);
	        }
	      }
	      function scrollToCoordsRange(cm, from, to, margin) {
	        var sPos = calculateScrollPos(cm, {
	          left: Math.min(from.left, to.left),
	          top: Math.min(from.top, to.top) - margin,
	          right: Math.max(from.right, to.right),
	          bottom: Math.max(from.bottom, to.bottom) + margin
	        });
	        scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
	      }

	      // Sync the scrollable area and scrollbars, ensure the viewport
	      // covers the visible area.
	      function updateScrollTop(cm, val) {
	        if (Math.abs(cm.doc.scrollTop - val) < 2) {
	          return;
	        }
	        if (!gecko) {
	          updateDisplaySimple(cm, {
	            top: val
	          });
	        }
	        setScrollTop(cm, val, true);
	        if (gecko) {
	          updateDisplaySimple(cm);
	        }
	        startWorker(cm, 100);
	      }
	      function setScrollTop(cm, val, forceScroll) {
	        val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
	        if (cm.display.scroller.scrollTop == val && !forceScroll) {
	          return;
	        }
	        cm.doc.scrollTop = val;
	        cm.display.scrollbars.setScrollTop(val);
	        if (cm.display.scroller.scrollTop != val) {
	          cm.display.scroller.scrollTop = val;
	        }
	      }

	      // Sync scroller and scrollbar, ensure the gutter elements are
	      // aligned.
	      function setScrollLeft(cm, val, isScroller, forceScroll) {
	        val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
	        if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) {
	          return;
	        }
	        cm.doc.scrollLeft = val;
	        alignHorizontally(cm);
	        if (cm.display.scroller.scrollLeft != val) {
	          cm.display.scroller.scrollLeft = val;
	        }
	        cm.display.scrollbars.setScrollLeft(val);
	      }

	      // SCROLLBARS

	      // Prepare DOM reads needed to update the scrollbars. Done in one
	      // shot to minimize update/measure roundtrips.
	      function measureForScrollbars(cm) {
	        var d = cm.display,
	          gutterW = d.gutters.offsetWidth;
	        var docH = Math.round(cm.doc.height + paddingVert(cm.display));
	        return {
	          clientHeight: d.scroller.clientHeight,
	          viewHeight: d.wrapper.clientHeight,
	          scrollWidth: d.scroller.scrollWidth,
	          clientWidth: d.scroller.clientWidth,
	          viewWidth: d.wrapper.clientWidth,
	          barLeft: cm.options.fixedGutter ? gutterW : 0,
	          docHeight: docH,
	          scrollHeight: docH + scrollGap(cm) + d.barHeight,
	          nativeBarWidth: d.nativeBarWidth,
	          gutterWidth: gutterW
	        };
	      }
	      var NativeScrollbars = function (place, scroll, cm) {
	        this.cm = cm;
	        var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
	        var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
	        vert.tabIndex = horiz.tabIndex = -1;
	        place(vert);
	        place(horiz);
	        on(vert, "scroll", function () {
	          if (vert.clientHeight) {
	            scroll(vert.scrollTop, "vertical");
	          }
	        });
	        on(horiz, "scroll", function () {
	          if (horiz.clientWidth) {
	            scroll(horiz.scrollLeft, "horizontal");
	          }
	        });
	        this.checkedZeroWidth = false;
	        // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
	        if (ie && ie_version < 8) {
	          this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
	        }
	      };
	      NativeScrollbars.prototype.update = function (measure) {
	        var needsH = measure.scrollWidth > measure.clientWidth + 1;
	        var needsV = measure.scrollHeight > measure.clientHeight + 1;
	        var sWidth = measure.nativeBarWidth;
	        if (needsV) {
	          this.vert.style.display = "block";
	          this.vert.style.bottom = needsH ? sWidth + "px" : "0";
	          var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
	          // A bug in IE8 can cause this value to be negative, so guard it.
	          this.vert.firstChild.style.height = Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
	        } else {
	          this.vert.scrollTop = 0;
	          this.vert.style.display = "";
	          this.vert.firstChild.style.height = "0";
	        }
	        if (needsH) {
	          this.horiz.style.display = "block";
	          this.horiz.style.right = needsV ? sWidth + "px" : "0";
	          this.horiz.style.left = measure.barLeft + "px";
	          var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
	          this.horiz.firstChild.style.width = Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
	        } else {
	          this.horiz.style.display = "";
	          this.horiz.firstChild.style.width = "0";
	        }
	        if (!this.checkedZeroWidth && measure.clientHeight > 0) {
	          if (sWidth == 0) {
	            this.zeroWidthHack();
	          }
	          this.checkedZeroWidth = true;
	        }
	        return {
	          right: needsV ? sWidth : 0,
	          bottom: needsH ? sWidth : 0
	        };
	      };
	      NativeScrollbars.prototype.setScrollLeft = function (pos) {
	        if (this.horiz.scrollLeft != pos) {
	          this.horiz.scrollLeft = pos;
	        }
	        if (this.disableHoriz) {
	          this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz");
	        }
	      };
	      NativeScrollbars.prototype.setScrollTop = function (pos) {
	        if (this.vert.scrollTop != pos) {
	          this.vert.scrollTop = pos;
	        }
	        if (this.disableVert) {
	          this.enableZeroWidthBar(this.vert, this.disableVert, "vert");
	        }
	      };
	      NativeScrollbars.prototype.zeroWidthHack = function () {
	        var w = mac && !mac_geMountainLion ? "12px" : "18px";
	        this.horiz.style.height = this.vert.style.width = w;
	        this.horiz.style.visibility = this.vert.style.visibility = "hidden";
	        this.disableHoriz = new Delayed();
	        this.disableVert = new Delayed();
	      };
	      NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
	        bar.style.visibility = "";
	        function maybeDisable() {
	          // To find out whether the scrollbar is still visible, we
	          // check whether the element under the pixel in the bottom
	          // right corner of the scrollbar box is the scrollbar box
	          // itself (when the bar is still visible) or its filler child
	          // (when the bar is hidden). If it is still visible, we keep
	          // it enabled, if it's hidden, we disable pointer events.
	          var box = bar.getBoundingClientRect();
	          var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
	          if (elt != bar) {
	            bar.style.visibility = "hidden";
	          } else {
	            delay.set(1000, maybeDisable);
	          }
	        }
	        delay.set(1000, maybeDisable);
	      };
	      NativeScrollbars.prototype.clear = function () {
	        var parent = this.horiz.parentNode;
	        parent.removeChild(this.horiz);
	        parent.removeChild(this.vert);
	      };
	      var NullScrollbars = function () {};
	      NullScrollbars.prototype.update = function () {
	        return {
	          bottom: 0,
	          right: 0
	        };
	      };
	      NullScrollbars.prototype.setScrollLeft = function () {};
	      NullScrollbars.prototype.setScrollTop = function () {};
	      NullScrollbars.prototype.clear = function () {};
	      function updateScrollbars(cm, measure) {
	        if (!measure) {
	          measure = measureForScrollbars(cm);
	        }
	        var startWidth = cm.display.barWidth,
	          startHeight = cm.display.barHeight;
	        updateScrollbarsInner(cm, measure);
	        for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
	          if (startWidth != cm.display.barWidth && cm.options.lineWrapping) {
	            updateHeightsInViewport(cm);
	          }
	          updateScrollbarsInner(cm, measureForScrollbars(cm));
	          startWidth = cm.display.barWidth;
	          startHeight = cm.display.barHeight;
	        }
	      }

	      // Re-synchronize the fake scrollbars with the actual size of the
	      // content.
	      function updateScrollbarsInner(cm, measure) {
	        var d = cm.display;
	        var sizes = d.scrollbars.update(measure);
	        d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
	        d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
	        d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
	        if (sizes.right && sizes.bottom) {
	          d.scrollbarFiller.style.display = "block";
	          d.scrollbarFiller.style.height = sizes.bottom + "px";
	          d.scrollbarFiller.style.width = sizes.right + "px";
	        } else {
	          d.scrollbarFiller.style.display = "";
	        }
	        if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
	          d.gutterFiller.style.display = "block";
	          d.gutterFiller.style.height = sizes.bottom + "px";
	          d.gutterFiller.style.width = measure.gutterWidth + "px";
	        } else {
	          d.gutterFiller.style.display = "";
	        }
	      }
	      var scrollbarModel = {
	        "native": NativeScrollbars,
	        "null": NullScrollbars
	      };
	      function initScrollbars(cm) {
	        if (cm.display.scrollbars) {
	          cm.display.scrollbars.clear();
	          if (cm.display.scrollbars.addClass) {
	            rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
	          }
	        }
	        cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
	          cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
	          // Prevent clicks in the scrollbars from killing focus
	          on(node, "mousedown", function () {
	            if (cm.state.focused) {
	              setTimeout(function () {
	                return cm.display.input.focus();
	              }, 0);
	            }
	          });
	          node.setAttribute("cm-not-content", "true");
	        }, function (pos, axis) {
	          if (axis == "horizontal") {
	            setScrollLeft(cm, pos);
	          } else {
	            updateScrollTop(cm, pos);
	          }
	        }, cm);
	        if (cm.display.scrollbars.addClass) {
	          addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
	        }
	      }

	      // Operations are used to wrap a series of changes to the editor
	      // state in such a way that each change won't have to update the
	      // cursor and display (which would be awkward, slow, and
	      // error-prone). Instead, display updates are batched and then all
	      // combined and executed at once.

	      var nextOpId = 0;
	      // Start a new operation.
	      function startOperation(cm) {
	        cm.curOp = {
	          cm: cm,
	          viewChanged: false,
	          // Flag that indicates that lines might need to be redrawn
	          startHeight: cm.doc.height,
	          // Used to detect need to update scrollbar
	          forceUpdate: false,
	          // Used to force a redraw
	          updateInput: 0,
	          // Whether to reset the input textarea
	          typing: false,
	          // Whether this reset should be careful to leave existing text (for compositing)
	          changeObjs: null,
	          // Accumulated changes, for firing change events
	          cursorActivityHandlers: null,
	          // Set of handlers to fire cursorActivity on
	          cursorActivityCalled: 0,
	          // Tracks which cursorActivity handlers have been called already
	          selectionChanged: false,
	          // Whether the selection needs to be redrawn
	          updateMaxLine: false,
	          // Set when the widest line needs to be determined anew
	          scrollLeft: null,
	          scrollTop: null,
	          // Intermediate scroll position, not pushed to DOM yet
	          scrollToPos: null,
	          // Used to scroll to a specific position
	          focus: false,
	          id: ++nextOpId,
	          // Unique ID
	          markArrays: null // Used by addMarkedSpan
	        };
	        pushOperation(cm.curOp);
	      }

	      // Finish an operation, updating the display and signalling delayed events
	      function endOperation(cm) {
	        var op = cm.curOp;
	        if (op) {
	          finishOperation(op, function (group) {
	            for (var i = 0; i < group.ops.length; i++) {
	              group.ops[i].cm.curOp = null;
	            }
	            endOperations(group);
	          });
	        }
	      }

	      // The DOM updates done when an operation finishes are batched so
	      // that the minimum number of relayouts are required.
	      function endOperations(group) {
	        var ops = group.ops;
	        for (var i = 0; i < ops.length; i++)
	        // Read DOM
	        {
	          endOperation_R1(ops[i]);
	        }
	        for (var i$1 = 0; i$1 < ops.length; i$1++)
	        // Write DOM (maybe)
	        {
	          endOperation_W1(ops[i$1]);
	        }
	        for (var i$2 = 0; i$2 < ops.length; i$2++)
	        // Read DOM
	        {
	          endOperation_R2(ops[i$2]);
	        }
	        for (var i$3 = 0; i$3 < ops.length; i$3++)
	        // Write DOM (maybe)
	        {
	          endOperation_W2(ops[i$3]);
	        }
	        for (var i$4 = 0; i$4 < ops.length; i$4++)
	        // Read DOM
	        {
	          endOperation_finish(ops[i$4]);
	        }
	      }
	      function endOperation_R1(op) {
	        var cm = op.cm,
	          display = cm.display;
	        maybeClipScrollbars(cm);
	        if (op.updateMaxLine) {
	          findMaxLine(cm);
	        }
	        op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || op.scrollToPos.to.line >= display.viewTo) || display.maxLineChanged && cm.options.lineWrapping;
	        op.update = op.mustUpdate && new DisplayUpdate(cm, op.mustUpdate && {
	          top: op.scrollTop,
	          ensure: op.scrollToPos
	        }, op.forceUpdate);
	      }
	      function endOperation_W1(op) {
	        op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
	      }
	      function endOperation_R2(op) {
	        var cm = op.cm,
	          display = cm.display;
	        if (op.updatedDisplay) {
	          updateHeightsInViewport(cm);
	        }
	        op.barMeasure = measureForScrollbars(cm);

	        // If the max line changed since it was last measured, measure it,
	        // and ensure the document's width matches it.
	        // updateDisplay_W2 will use these properties to do the actual resizing
	        if (display.maxLineChanged && !cm.options.lineWrapping) {
	          op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
	          cm.display.sizerWidth = op.adjustWidthTo;
	          op.barMeasure.scrollWidth = Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
	          op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
	        }
	        if (op.updatedDisplay || op.selectionChanged) {
	          op.preparedSelection = display.input.prepareSelection();
	        }
	      }
	      function endOperation_W2(op) {
	        var cm = op.cm;
	        if (op.adjustWidthTo != null) {
	          cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
	          if (op.maxScrollLeft < cm.doc.scrollLeft) {
	            setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
	          }
	          cm.display.maxLineChanged = false;
	        }
	        var takeFocus = op.focus && op.focus == activeElt(root(cm));
	        if (op.preparedSelection) {
	          cm.display.input.showSelection(op.preparedSelection, takeFocus);
	        }
	        if (op.updatedDisplay || op.startHeight != cm.doc.height) {
	          updateScrollbars(cm, op.barMeasure);
	        }
	        if (op.updatedDisplay) {
	          setDocumentHeight(cm, op.barMeasure);
	        }
	        if (op.selectionChanged) {
	          restartBlink(cm);
	        }
	        if (cm.state.focused && op.updateInput) {
	          cm.display.input.reset(op.typing);
	        }
	        if (takeFocus) {
	          ensureFocus(op.cm);
	        }
	      }
	      function endOperation_finish(op) {
	        var cm = op.cm,
	          display = cm.display,
	          doc = cm.doc;
	        if (op.updatedDisplay) {
	          postUpdateDisplay(cm, op.update);
	        }

	        // Abort mouse wheel delta measurement, when scrolling explicitly
	        if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) {
	          display.wheelStartX = display.wheelStartY = null;
	        }

	        // Propagate the scroll position to the actual DOM scroller
	        if (op.scrollTop != null) {
	          setScrollTop(cm, op.scrollTop, op.forceScroll);
	        }
	        if (op.scrollLeft != null) {
	          setScrollLeft(cm, op.scrollLeft, true, true);
	        }
	        // If we need to scroll a specific position into view, do so.
	        if (op.scrollToPos) {
	          var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
	          maybeScrollWindow(cm, rect);
	        }

	        // Fire events for markers that are hidden/unidden by editing or
	        // undoing
	        var hidden = op.maybeHiddenMarkers,
	          unhidden = op.maybeUnhiddenMarkers;
	        if (hidden) {
	          for (var i = 0; i < hidden.length; ++i) {
	            if (!hidden[i].lines.length) {
	              signal(hidden[i], "hide");
	            }
	          }
	        }
	        if (unhidden) {
	          for (var i$1 = 0; i$1 < unhidden.length; ++i$1) {
	            if (unhidden[i$1].lines.length) {
	              signal(unhidden[i$1], "unhide");
	            }
	          }
	        }
	        if (display.wrapper.offsetHeight) {
	          doc.scrollTop = cm.display.scroller.scrollTop;
	        }

	        // Fire change events, and delayed event handlers
	        if (op.changeObjs) {
	          signal(cm, "changes", cm, op.changeObjs);
	        }
	        if (op.update) {
	          op.update.finish();
	        }
	      }

	      // Run the given function in an operation
	      function runInOp(cm, f) {
	        if (cm.curOp) {
	          return f();
	        }
	        startOperation(cm);
	        try {
	          return f();
	        } finally {
	          endOperation(cm);
	        }
	      }
	      // Wraps a function in an operation. Returns the wrapped function.
	      function operation(cm, f) {
	        return function () {
	          if (cm.curOp) {
	            return f.apply(cm, arguments);
	          }
	          startOperation(cm);
	          try {
	            return f.apply(cm, arguments);
	          } finally {
	            endOperation(cm);
	          }
	        };
	      }
	      // Used to add methods to editor and doc instances, wrapping them in
	      // operations.
	      function methodOp(f) {
	        return function () {
	          if (this.curOp) {
	            return f.apply(this, arguments);
	          }
	          startOperation(this);
	          try {
	            return f.apply(this, arguments);
	          } finally {
	            endOperation(this);
	          }
	        };
	      }
	      function docMethodOp(f) {
	        return function () {
	          var cm = this.cm;
	          if (!cm || cm.curOp) {
	            return f.apply(this, arguments);
	          }
	          startOperation(cm);
	          try {
	            return f.apply(this, arguments);
	          } finally {
	            endOperation(cm);
	          }
	        };
	      }

	      // HIGHLIGHT WORKER

	      function startWorker(cm, time) {
	        if (cm.doc.highlightFrontier < cm.display.viewTo) {
	          cm.state.highlight.set(time, bind(highlightWorker, cm));
	        }
	      }
	      function highlightWorker(cm) {
	        var doc = cm.doc;
	        if (doc.highlightFrontier >= cm.display.viewTo) {
	          return;
	        }
	        var end = +new Date() + cm.options.workTime;
	        var context = getContextBefore(cm, doc.highlightFrontier);
	        var changedLines = [];
	        doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
	          if (context.line >= cm.display.viewFrom) {
	            // Visible
	            var oldStyles = line.styles;
	            var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
	            var highlighted = highlightLine(cm, line, context, true);
	            if (resetState) {
	              context.state = resetState;
	            }
	            line.styles = highlighted.styles;
	            var oldCls = line.styleClasses,
	              newCls = highlighted.classes;
	            if (newCls) {
	              line.styleClasses = newCls;
	            } else if (oldCls) {
	              line.styleClasses = null;
	            }
	            var ischange = !oldStyles || oldStyles.length != line.styles.length || oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
	            for (var i = 0; !ischange && i < oldStyles.length; ++i) {
	              ischange = oldStyles[i] != line.styles[i];
	            }
	            if (ischange) {
	              changedLines.push(context.line);
	            }
	            line.stateAfter = context.save();
	            context.nextLine();
	          } else {
	            if (line.text.length <= cm.options.maxHighlightLength) {
	              processLine(cm, line.text, context);
	            }
	            line.stateAfter = context.line % 5 == 0 ? context.save() : null;
	            context.nextLine();
	          }
	          if (+new Date() > end) {
	            startWorker(cm, cm.options.workDelay);
	            return true;
	          }
	        });
	        doc.highlightFrontier = context.line;
	        doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
	        if (changedLines.length) {
	          runInOp(cm, function () {
	            for (var i = 0; i < changedLines.length; i++) {
	              regLineChange(cm, changedLines[i], "text");
	            }
	          });
	        }
	      }

	      // DISPLAY DRAWING

	      var DisplayUpdate = function (cm, viewport, force) {
	        var display = cm.display;
	        this.viewport = viewport;
	        // Store some values that we'll need later (but don't want to force a relayout for)
	        this.visible = visibleLines(display, cm.doc, viewport);
	        this.editorIsHidden = !display.wrapper.offsetWidth;
	        this.wrapperHeight = display.wrapper.clientHeight;
	        this.wrapperWidth = display.wrapper.clientWidth;
	        this.oldDisplayWidth = displayWidth(cm);
	        this.force = force;
	        this.dims = getDimensions(cm);
	        this.events = [];
	      };
	      DisplayUpdate.prototype.signal = function (emitter, type) {
	        if (hasHandler(emitter, type)) {
	          this.events.push(arguments);
	        }
	      };
	      DisplayUpdate.prototype.finish = function () {
	        for (var i = 0; i < this.events.length; i++) {
	          signal.apply(null, this.events[i]);
	        }
	      };
	      function maybeClipScrollbars(cm) {
	        var display = cm.display;
	        if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
	          display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
	          display.heightForcer.style.height = scrollGap(cm) + "px";
	          display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
	          display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
	          display.scrollbarsClipped = true;
	        }
	      }
	      function selectionSnapshot(cm) {
	        if (cm.hasFocus()) {
	          return null;
	        }
	        var active = activeElt(root(cm));
	        if (!active || !contains(cm.display.lineDiv, active)) {
	          return null;
	        }
	        var result = {
	          activeElt: active
	        };
	        if (window.getSelection) {
	          var sel = win(cm).getSelection();
	          if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
	            result.anchorNode = sel.anchorNode;
	            result.anchorOffset = sel.anchorOffset;
	            result.focusNode = sel.focusNode;
	            result.focusOffset = sel.focusOffset;
	          }
	        }
	        return result;
	      }
	      function restoreSelection(snapshot) {
	        if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt(rootNode(snapshot.activeElt))) {
	          return;
	        }
	        snapshot.activeElt.focus();
	        if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) && snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
	          var doc = snapshot.activeElt.ownerDocument;
	          var sel = doc.defaultView.getSelection(),
	            range = doc.createRange();
	          range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
	          range.collapse(false);
	          sel.removeAllRanges();
	          sel.addRange(range);
	          sel.extend(snapshot.focusNode, snapshot.focusOffset);
	        }
	      }

	      // Does the actual updating of the line display. Bails out
	      // (returning false) when there is nothing to be done and forced is
	      // false.
	      function updateDisplayIfNeeded(cm, update) {
	        var display = cm.display,
	          doc = cm.doc;
	        if (update.editorIsHidden) {
	          resetView(cm);
	          return false;
	        }

	        // Bail out if the visible area is already rendered and nothing changed.
	        if (!update.force && update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && display.renderedView == display.view && countDirtyView(cm) == 0) {
	          return false;
	        }
	        if (maybeUpdateLineNumberWidth(cm)) {
	          resetView(cm);
	          update.dims = getDimensions(cm);
	        }

	        // Compute a suitable new viewport (from & to)
	        var end = doc.first + doc.size;
	        var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
	        var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
	        if (display.viewFrom < from && from - display.viewFrom < 20) {
	          from = Math.max(doc.first, display.viewFrom);
	        }
	        if (display.viewTo > to && display.viewTo - to < 20) {
	          to = Math.min(end, display.viewTo);
	        }
	        if (sawCollapsedSpans) {
	          from = visualLineNo(cm.doc, from);
	          to = visualLineEndNo(cm.doc, to);
	        }
	        var different = from != display.viewFrom || to != display.viewTo || display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
	        adjustView(cm, from, to);
	        display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
	        // Position the mover div to align with the current scroll position
	        cm.display.mover.style.top = display.viewOffset + "px";
	        var toUpdate = countDirtyView(cm);
	        if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) {
	          return false;
	        }

	        // For big changes, we hide the enclosing element during the
	        // update, since that speeds up the operations on most browsers.
	        var selSnapshot = selectionSnapshot(cm);
	        if (toUpdate > 4) {
	          display.lineDiv.style.display = "none";
	        }
	        patchDisplay(cm, display.updateLineNumbers, update.dims);
	        if (toUpdate > 4) {
	          display.lineDiv.style.display = "";
	        }
	        display.renderedView = display.view;
	        // There might have been a widget with a focused element that got
	        // hidden or updated, if so re-focus it.
	        restoreSelection(selSnapshot);

	        // Prevent selection and cursors from interfering with the scroll
	        // width and height.
	        removeChildren(display.cursorDiv);
	        removeChildren(display.selectionDiv);
	        display.gutters.style.height = display.sizer.style.minHeight = 0;
	        if (different) {
	          display.lastWrapHeight = update.wrapperHeight;
	          display.lastWrapWidth = update.wrapperWidth;
	          startWorker(cm, 400);
	        }
	        display.updateLineNumbers = null;
	        return true;
	      }
	      function postUpdateDisplay(cm, update) {
	        var viewport = update.viewport;
	        for (var first = true;; first = false) {
	          if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
	            // Clip forced viewport to actual scrollable area.
	            if (viewport && viewport.top != null) {
	              viewport = {
	                top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)
	              };
	            }
	            // Updated line heights might result in the drawn area not
	            // actually covering the viewport. Keep looping until it does.
	            update.visible = visibleLines(cm.display, cm.doc, viewport);
	            if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) {
	              break;
	            }
	          } else if (first) {
	            update.visible = visibleLines(cm.display, cm.doc, viewport);
	          }
	          if (!updateDisplayIfNeeded(cm, update)) {
	            break;
	          }
	          updateHeightsInViewport(cm);
	          var barMeasure = measureForScrollbars(cm);
	          updateSelection(cm);
	          updateScrollbars(cm, barMeasure);
	          setDocumentHeight(cm, barMeasure);
	          update.force = false;
	        }
	        update.signal(cm, "update", cm);
	        if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
	          update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
	          cm.display.reportedViewFrom = cm.display.viewFrom;
	          cm.display.reportedViewTo = cm.display.viewTo;
	        }
	      }
	      function updateDisplaySimple(cm, viewport) {
	        var update = new DisplayUpdate(cm, viewport);
	        if (updateDisplayIfNeeded(cm, update)) {
	          updateHeightsInViewport(cm);
	          postUpdateDisplay(cm, update);
	          var barMeasure = measureForScrollbars(cm);
	          updateSelection(cm);
	          updateScrollbars(cm, barMeasure);
	          setDocumentHeight(cm, barMeasure);
	          update.finish();
	        }
	      }

	      // Sync the actual display DOM structure with display.view, removing
	      // nodes for lines that are no longer in view, and creating the ones
	      // that are not there yet, and updating the ones that are out of
	      // date.
	      function patchDisplay(cm, updateNumbersFrom, dims) {
	        var display = cm.display,
	          lineNumbers = cm.options.lineNumbers;
	        var container = display.lineDiv,
	          cur = container.firstChild;
	        function rm(node) {
	          var next = node.nextSibling;
	          // Works around a throw-scroll bug in OS X Webkit
	          if (webkit && mac && cm.display.currentWheelTarget == node) {
	            node.style.display = "none";
	          } else {
	            node.parentNode.removeChild(node);
	          }
	          return next;
	        }
	        var view = display.view,
	          lineN = display.viewFrom;
	        // Loop over the elements in the view, syncing cur (the DOM nodes
	        // in display.lineDiv) with the view as we go.
	        for (var i = 0; i < view.length; i++) {
	          var lineView = view[i];
	          if (lineView.hidden) ;else if (!lineView.node || lineView.node.parentNode != container) {
	            // Not drawn yet
	            var node = buildLineElement(cm, lineView, lineN, dims);
	            container.insertBefore(node, cur);
	          } else {
	            // Already drawn
	            while (cur != lineView.node) {
	              cur = rm(cur);
	            }
	            var updateNumber = lineNumbers && updateNumbersFrom != null && updateNumbersFrom <= lineN && lineView.lineNumber;
	            if (lineView.changes) {
	              if (indexOf(lineView.changes, "gutter") > -1) {
	                updateNumber = false;
	              }
	              updateLineForChanges(cm, lineView, lineN, dims);
	            }
	            if (updateNumber) {
	              removeChildren(lineView.lineNumber);
	              lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
	            }
	            cur = lineView.node.nextSibling;
	          }
	          lineN += lineView.size;
	        }
	        while (cur) {
	          cur = rm(cur);
	        }
	      }
	      function updateGutterSpace(display) {
	        var width = display.gutters.offsetWidth;
	        display.sizer.style.marginLeft = width + "px";
	        // Send an event to consumers responding to changes in gutter width.
	        signalLater(display, "gutterChanged", display);
	      }
	      function setDocumentHeight(cm, measure) {
	        cm.display.sizer.style.minHeight = measure.docHeight + "px";
	        cm.display.heightForcer.style.top = measure.docHeight + "px";
	        cm.display.gutters.style.height = measure.docHeight + cm.display.barHeight + scrollGap(cm) + "px";
	      }

	      // Re-align line numbers and gutter marks to compensate for
	      // horizontal scrolling.
	      function alignHorizontally(cm) {
	        var display = cm.display,
	          view = display.view;
	        if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) {
	          return;
	        }
	        var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
	        var gutterW = display.gutters.offsetWidth,
	          left = comp + "px";
	        for (var i = 0; i < view.length; i++) {
	          if (!view[i].hidden) {
	            if (cm.options.fixedGutter) {
	              if (view[i].gutter) {
	                view[i].gutter.style.left = left;
	              }
	              if (view[i].gutterBackground) {
	                view[i].gutterBackground.style.left = left;
	              }
	            }
	            var align = view[i].alignable;
	            if (align) {
	              for (var j = 0; j < align.length; j++) {
	                align[j].style.left = left;
	              }
	            }
	          }
	        }
	        if (cm.options.fixedGutter) {
	          display.gutters.style.left = comp + gutterW + "px";
	        }
	      }

	      // Used to ensure that the line number gutter is still the right
	      // size for the current document size. Returns true when an update
	      // is needed.
	      function maybeUpdateLineNumberWidth(cm) {
	        if (!cm.options.lineNumbers) {
	          return false;
	        }
	        var doc = cm.doc,
	          last = lineNumberFor(cm.options, doc.first + doc.size - 1),
	          display = cm.display;
	        if (last.length != display.lineNumChars) {
	          var test = display.measure.appendChild(elt("div", [elt("div", last)], "CodeMirror-linenumber CodeMirror-gutter-elt"));
	          var innerW = test.firstChild.offsetWidth,
	            padding = test.offsetWidth - innerW;
	          display.lineGutter.style.width = "";
	          display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
	          display.lineNumWidth = display.lineNumInnerWidth + padding;
	          display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
	          display.lineGutter.style.width = display.lineNumWidth + "px";
	          updateGutterSpace(cm.display);
	          return true;
	        }
	        return false;
	      }
	      function getGutters(gutters, lineNumbers) {
	        var result = [],
	          sawLineNumbers = false;
	        for (var i = 0; i < gutters.length; i++) {
	          var name = gutters[i],
	            style = null;
	          if (typeof name != "string") {
	            style = name.style;
	            name = name.className;
	          }
	          if (name == "CodeMirror-linenumbers") {
	            if (!lineNumbers) {
	              continue;
	            } else {
	              sawLineNumbers = true;
	            }
	          }
	          result.push({
	            className: name,
	            style: style
	          });
	        }
	        if (lineNumbers && !sawLineNumbers) {
	          result.push({
	            className: "CodeMirror-linenumbers",
	            style: null
	          });
	        }
	        return result;
	      }

	      // Rebuild the gutter elements, ensure the margin to the left of the
	      // code matches their width.
	      function renderGutters(display) {
	        var gutters = display.gutters,
	          specs = display.gutterSpecs;
	        removeChildren(gutters);
	        display.lineGutter = null;
	        for (var i = 0; i < specs.length; ++i) {
	          var ref = specs[i];
	          var className = ref.className;
	          var style = ref.style;
	          var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
	          if (style) {
	            gElt.style.cssText = style;
	          }
	          if (className == "CodeMirror-linenumbers") {
	            display.lineGutter = gElt;
	            gElt.style.width = (display.lineNumWidth || 1) + "px";
	          }
	        }
	        gutters.style.display = specs.length ? "" : "none";
	        updateGutterSpace(display);
	      }
	      function updateGutters(cm) {
	        renderGutters(cm.display);
	        regChange(cm);
	        alignHorizontally(cm);
	      }

	      // The display handles the DOM integration, both for input reading
	      // and content drawing. It holds references to DOM nodes and
	      // display-related state.

	      function Display(place, doc, input, options) {
	        var d = this;
	        this.input = input;

	        // Covers bottom-right square when both scrollbars are present.
	        d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
	        d.scrollbarFiller.setAttribute("cm-not-content", "true");
	        // Covers bottom of gutter when coverGutterNextToScrollbar is on
	        // and h scrollbar is present.
	        d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
	        d.gutterFiller.setAttribute("cm-not-content", "true");
	        // Will contain the actual code, positioned to cover the viewport.
	        d.lineDiv = eltP("div", null, "CodeMirror-code");
	        // Elements are added to these to represent selection and cursors.
	        d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
	        d.cursorDiv = elt("div", null, "CodeMirror-cursors");
	        // A visibility: hidden element used to find the size of things.
	        d.measure = elt("div", null, "CodeMirror-measure");
	        // When lines outside of the viewport are measured, they are drawn in this.
	        d.lineMeasure = elt("div", null, "CodeMirror-measure");
	        // Wraps everything that needs to exist inside the vertically-padded coordinate system
	        d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], null, "position: relative; outline: none");
	        var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
	        // Moved around its parent to cover visible view.
	        d.mover = elt("div", [lines], null, "position: relative");
	        // Set to the height of the document, allowing scrolling.
	        d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
	        d.sizerWidth = null;
	        // Behavior of elts with overflow: auto and padding is
	        // inconsistent across browsers. This is used to ensure the
	        // scrollable area is big enough.
	        d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
	        // Will contain the gutters, if any.
	        d.gutters = elt("div", null, "CodeMirror-gutters");
	        d.lineGutter = null;
	        // Actual scrollable element.
	        d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
	        d.scroller.setAttribute("tabIndex", "-1");
	        // The element in which the editor lives.
	        d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
	        // See #6982. FIXME remove when this has been fixed for a while in Chrome
	        if (chrome && chrome_version === 105) {
	          d.wrapper.style.clipPath = "inset(0px)";
	        }

	        // This attribute is respected by automatic translation systems such as Google Translate,
	        // and may also be respected by tools used by human translators.
	        d.wrapper.setAttribute('translate', 'no');

	        // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
	        if (ie && ie_version < 8) {
	          d.gutters.style.zIndex = -1;
	          d.scroller.style.paddingRight = 0;
	        }
	        if (!webkit && !(gecko && mobile)) {
	          d.scroller.draggable = true;
	        }
	        if (place) {
	          if (place.appendChild) {
	            place.appendChild(d.wrapper);
	          } else {
	            place(d.wrapper);
	          }
	        }

	        // Current rendered range (may be bigger than the view window).
	        d.viewFrom = d.viewTo = doc.first;
	        d.reportedViewFrom = d.reportedViewTo = doc.first;
	        // Information about the rendered lines.
	        d.view = [];
	        d.renderedView = null;
	        // Holds info about a single rendered line when it was rendered
	        // for measurement, while not in view.
	        d.externalMeasured = null;
	        // Empty space (in pixels) above the view
	        d.viewOffset = 0;
	        d.lastWrapHeight = d.lastWrapWidth = 0;
	        d.updateLineNumbers = null;
	        d.nativeBarWidth = d.barHeight = d.barWidth = 0;
	        d.scrollbarsClipped = false;

	        // Used to only resize the line number gutter when necessary (when
	        // the amount of lines crosses a boundary that makes its width change)
	        d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
	        // Set to true when a non-horizontal-scrolling line widget is
	        // added. As an optimization, line widget aligning is skipped when
	        // this is false.
	        d.alignWidgets = false;
	        d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;

	        // Tracks the maximum line length so that the horizontal scrollbar
	        // can be kept static when scrolling.
	        d.maxLine = null;
	        d.maxLineLength = 0;
	        d.maxLineChanged = false;

	        // Used for measuring wheel scrolling granularity
	        d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;

	        // True when shift is held down.
	        d.shift = false;

	        // Used to track whether anything happened since the context menu
	        // was opened.
	        d.selForContextMenu = null;
	        d.activeTouch = null;
	        d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
	        renderGutters(d);
	        input.init(d);
	      }

	      // Since the delta values reported on mouse wheel events are
	      // unstandardized between browsers and even browser versions, and
	      // generally horribly unpredictable, this code starts by measuring
	      // the scroll effect that the first few mouse wheel events have,
	      // and, from that, detects the way it can convert deltas to pixel
	      // offsets afterwards.
	      //
	      // The reason we want to know the amount a wheel event will scroll
	      // is that it gives us a chance to update the display before the
	      // actual scrolling happens, reducing flickering.

	      var wheelSamples = 0,
	        wheelPixelsPerUnit = null;
	      // Fill in a browser-detected starting value on browsers where we
	      // know one. These don't have to be accurate -- the result of them
	      // being wrong would just be a slight flicker on the first wheel
	      // scroll (if it is large enough).
	      if (ie) {
	        wheelPixelsPerUnit = -0.53;
	      } else if (gecko) {
	        wheelPixelsPerUnit = 15;
	      } else if (chrome) {
	        wheelPixelsPerUnit = -0.7;
	      } else if (safari) {
	        wheelPixelsPerUnit = -1 / 3;
	      }
	      function wheelEventDelta(e) {
	        var dx = e.wheelDeltaX,
	          dy = e.wheelDeltaY;
	        if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) {
	          dx = e.detail;
	        }
	        if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) {
	          dy = e.detail;
	        } else if (dy == null) {
	          dy = e.wheelDelta;
	        }
	        return {
	          x: dx,
	          y: dy
	        };
	      }
	      function wheelEventPixels(e) {
	        var delta = wheelEventDelta(e);
	        delta.x *= wheelPixelsPerUnit;
	        delta.y *= wheelPixelsPerUnit;
	        return delta;
	      }
	      function onScrollWheel(cm, e) {
	        // On Chrome 102, viewport updates somehow stop wheel-based
	        // scrolling. Turning off pointer events during the scroll seems
	        // to avoid the issue.
	        if (chrome && chrome_version == 102) {
	          if (cm.display.chromeScrollHack == null) {
	            cm.display.sizer.style.pointerEvents = "none";
	          } else {
	            clearTimeout(cm.display.chromeScrollHack);
	          }
	          cm.display.chromeScrollHack = setTimeout(function () {
	            cm.display.chromeScrollHack = null;
	            cm.display.sizer.style.pointerEvents = "";
	          }, 100);
	        }
	        var delta = wheelEventDelta(e),
	          dx = delta.x,
	          dy = delta.y;
	        var pixelsPerUnit = wheelPixelsPerUnit;
	        if (e.deltaMode === 0) {
	          dx = e.deltaX;
	          dy = e.deltaY;
	          pixelsPerUnit = 1;
	        }
	        var display = cm.display,
	          scroll = display.scroller;
	        // Quit if there's nothing to scroll here
	        var canScrollX = scroll.scrollWidth > scroll.clientWidth;
	        var canScrollY = scroll.scrollHeight > scroll.clientHeight;
	        if (!(dx && canScrollX || dy && canScrollY)) {
	          return;
	        }

	        // Webkit browsers on OS X abort momentum scrolls when the target
	        // of the scroll event is removed from the scrollable element.
	        // This hack (see related code in patchDisplay) makes sure the
	        // element is kept around.
	        if (dy && mac && webkit) {
	          outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
	            for (var i = 0; i < view.length; i++) {
	              if (view[i].node == cur) {
	                cm.display.currentWheelTarget = cur;
	                break outer;
	              }
	            }
	          }
	        }

	        // On some browsers, horizontal scrolling will cause redraws to
	        // happen before the gutter has been realigned, causing it to
	        // wriggle around in a most unseemly way. When we have an
	        // estimated pixels/delta value, we just handle horizontal
	        // scrolling entirely here. It'll be slightly off from native, but
	        // better than glitching out.
	        if (dx && !gecko && !presto && pixelsPerUnit != null) {
	          if (dy && canScrollY) {
	            updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit));
	          }
	          setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit));
	          // Only prevent default scrolling if vertical scrolling is
	          // actually possible. Otherwise, it causes vertical scroll
	          // jitter on OSX trackpads when deltaX is small and deltaY
	          // is large (issue #3579)
	          if (!dy || dy && canScrollY) {
	            e_preventDefault(e);
	          }
	          display.wheelStartX = null; // Abort measurement, if in progress
	          return;
	        }

	        // 'Project' the visible viewport to cover the area that is being
	        // scrolled into view (if we know enough to estimate it).
	        if (dy && pixelsPerUnit != null) {
	          var pixels = dy * pixelsPerUnit;
	          var top = cm.doc.scrollTop,
	            bot = top + display.wrapper.clientHeight;
	          if (pixels < 0) {
	            top = Math.max(0, top + pixels - 50);
	          } else {
	            bot = Math.min(cm.doc.height, bot + pixels + 50);
	          }
	          updateDisplaySimple(cm, {
	            top: top,
	            bottom: bot
	          });
	        }
	        if (wheelSamples < 20 && e.deltaMode !== 0) {
	          if (display.wheelStartX == null) {
	            display.wheelStartX = scroll.scrollLeft;
	            display.wheelStartY = scroll.scrollTop;
	            display.wheelDX = dx;
	            display.wheelDY = dy;
	            setTimeout(function () {
	              if (display.wheelStartX == null) {
	                return;
	              }
	              var movedX = scroll.scrollLeft - display.wheelStartX;
	              var movedY = scroll.scrollTop - display.wheelStartY;
	              var sample = movedY && display.wheelDY && movedY / display.wheelDY || movedX && display.wheelDX && movedX / display.wheelDX;
	              display.wheelStartX = display.wheelStartY = null;
	              if (!sample) {
	                return;
	              }
	              wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
	              ++wheelSamples;
	            }, 200);
	          } else {
	            display.wheelDX += dx;
	            display.wheelDY += dy;
	          }
	        }
	      }

	      // Selection objects are immutable. A new one is created every time
	      // the selection changes. A selection is one or more non-overlapping
	      // (and non-touching) ranges, sorted, and an integer that indicates
	      // which one is the primary selection (the one that's scrolled into
	      // view, that getCursor returns, etc).
	      var Selection = function (ranges, primIndex) {
	        this.ranges = ranges;
	        this.primIndex = primIndex;
	      };
	      Selection.prototype.primary = function () {
	        return this.ranges[this.primIndex];
	      };
	      Selection.prototype.equals = function (other) {
	        if (other == this) {
	          return true;
	        }
	        if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) {
	          return false;
	        }
	        for (var i = 0; i < this.ranges.length; i++) {
	          var here = this.ranges[i],
	            there = other.ranges[i];
	          if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) {
	            return false;
	          }
	        }
	        return true;
	      };
	      Selection.prototype.deepCopy = function () {
	        var out = [];
	        for (var i = 0; i < this.ranges.length; i++) {
	          out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
	        }
	        return new Selection(out, this.primIndex);
	      };
	      Selection.prototype.somethingSelected = function () {
	        for (var i = 0; i < this.ranges.length; i++) {
	          if (!this.ranges[i].empty()) {
	            return true;
	          }
	        }
	        return false;
	      };
	      Selection.prototype.contains = function (pos, end) {
	        if (!end) {
	          end = pos;
	        }
	        for (var i = 0; i < this.ranges.length; i++) {
	          var range = this.ranges[i];
	          if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) {
	            return i;
	          }
	        }
	        return -1;
	      };
	      var Range = function (anchor, head) {
	        this.anchor = anchor;
	        this.head = head;
	      };
	      Range.prototype.from = function () {
	        return minPos(this.anchor, this.head);
	      };
	      Range.prototype.to = function () {
	        return maxPos(this.anchor, this.head);
	      };
	      Range.prototype.empty = function () {
	        return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
	      };

	      // Take an unsorted, potentially overlapping set of ranges, and
	      // build a selection out of it. 'Consumes' ranges array (modifying
	      // it).
	      function normalizeSelection(cm, ranges, primIndex) {
	        var mayTouch = cm && cm.options.selectionsMayTouch;
	        var prim = ranges[primIndex];
	        ranges.sort(function (a, b) {
	          return cmp(a.from(), b.from());
	        });
	        primIndex = indexOf(ranges, prim);
	        for (var i = 1; i < ranges.length; i++) {
	          var cur = ranges[i],
	            prev = ranges[i - 1];
	          var diff = cmp(prev.to(), cur.from());
	          if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
	            var from = minPos(prev.from(), cur.from()),
	              to = maxPos(prev.to(), cur.to());
	            var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
	            if (i <= primIndex) {
	              --primIndex;
	            }
	            ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
	          }
	        }
	        return new Selection(ranges, primIndex);
	      }
	      function simpleSelection(anchor, head) {
	        return new Selection([new Range(anchor, head || anchor)], 0);
	      }

	      // Compute the position of the end of a change (its 'to' property
	      // refers to the pre-change end).
	      function changeEnd(change) {
	        if (!change.text) {
	          return change.to;
	        }
	        return Pos(change.from.line + change.text.length - 1, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
	      }

	      // Adjust a position to refer to the post-change position of the
	      // same text, or the end of the change if the change covers it.
	      function adjustForChange(pos, change) {
	        if (cmp(pos, change.from) < 0) {
	          return pos;
	        }
	        if (cmp(pos, change.to) <= 0) {
	          return changeEnd(change);
	        }
	        var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1,
	          ch = pos.ch;
	        if (pos.line == change.to.line) {
	          ch += changeEnd(change).ch - change.to.ch;
	        }
	        return Pos(line, ch);
	      }
	      function computeSelAfterChange(doc, change) {
	        var out = [];
	        for (var i = 0; i < doc.sel.ranges.length; i++) {
	          var range = doc.sel.ranges[i];
	          out.push(new Range(adjustForChange(range.anchor, change), adjustForChange(range.head, change)));
	        }
	        return normalizeSelection(doc.cm, out, doc.sel.primIndex);
	      }
	      function offsetPos(pos, old, nw) {
	        if (pos.line == old.line) {
	          return Pos(nw.line, pos.ch - old.ch + nw.ch);
	        } else {
	          return Pos(nw.line + (pos.line - old.line), pos.ch);
	        }
	      }

	      // Used by replaceSelections to allow moving the selection to the
	      // start or around the replaced test. Hint may be "start" or "around".
	      function computeReplacedSel(doc, changes, hint) {
	        var out = [];
	        var oldPrev = Pos(doc.first, 0),
	          newPrev = oldPrev;
	        for (var i = 0; i < changes.length; i++) {
	          var change = changes[i];
	          var from = offsetPos(change.from, oldPrev, newPrev);
	          var to = offsetPos(changeEnd(change), oldPrev, newPrev);
	          oldPrev = change.to;
	          newPrev = to;
	          if (hint == "around") {
	            var range = doc.sel.ranges[i],
	              inv = cmp(range.head, range.anchor) < 0;
	            out[i] = new Range(inv ? to : from, inv ? from : to);
	          } else {
	            out[i] = new Range(from, from);
	          }
	        }
	        return new Selection(out, doc.sel.primIndex);
	      }

	      // Used to get the editor into a consistent state again when options change.

	      function loadMode(cm) {
	        cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
	        resetModeState(cm);
	      }
	      function resetModeState(cm) {
	        cm.doc.iter(function (line) {
	          if (line.stateAfter) {
	            line.stateAfter = null;
	          }
	          if (line.styles) {
	            line.styles = null;
	          }
	        });
	        cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
	        startWorker(cm, 100);
	        cm.state.modeGen++;
	        if (cm.curOp) {
	          regChange(cm);
	        }
	      }

	      // DOCUMENT DATA STRUCTURE

	      // By default, updates that start and end at the beginning of a line
	      // are treated specially, in order to make the association of line
	      // widgets and marker elements with the text behave more intuitive.
	      function isWholeLineUpdate(doc, change) {
	        return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
	      }

	      // Perform a change on the document data structure.
	      function updateDoc(doc, change, markedSpans, estimateHeight) {
	        function spansFor(n) {
	          return markedSpans ? markedSpans[n] : null;
	        }
	        function update(line, text, spans) {
	          updateLine(line, text, spans, estimateHeight);
	          signalLater(line, "change", line, change);
	        }
	        function linesFor(start, end) {
	          var result = [];
	          for (var i = start; i < end; ++i) {
	            result.push(new Line(text[i], spansFor(i), estimateHeight));
	          }
	          return result;
	        }
	        var from = change.from,
	          to = change.to,
	          text = change.text;
	        var firstLine = getLine(doc, from.line),
	          lastLine = getLine(doc, to.line);
	        var lastText = lst(text),
	          lastSpans = spansFor(text.length - 1),
	          nlines = to.line - from.line;

	        // Adjust the line structure
	        if (change.full) {
	          doc.insert(0, linesFor(0, text.length));
	          doc.remove(text.length, doc.size - text.length);
	        } else if (isWholeLineUpdate(doc, change)) {
	          // This is a whole-line replace. Treated specially to make
	          // sure line objects move the way they are supposed to.
	          var added = linesFor(0, text.length - 1);
	          update(lastLine, lastLine.text, lastSpans);
	          if (nlines) {
	            doc.remove(from.line, nlines);
	          }
	          if (added.length) {
	            doc.insert(from.line, added);
	          }
	        } else if (firstLine == lastLine) {
	          if (text.length == 1) {
	            update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
	          } else {
	            var added$1 = linesFor(1, text.length - 1);
	            added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
	            update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
	            doc.insert(from.line + 1, added$1);
	          }
	        } else if (text.length == 1) {
	          update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
	          doc.remove(from.line + 1, nlines);
	        } else {
	          update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
	          update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
	          var added$2 = linesFor(1, text.length - 1);
	          if (nlines > 1) {
	            doc.remove(from.line + 1, nlines - 1);
	          }
	          doc.insert(from.line + 1, added$2);
	        }
	        signalLater(doc, "change", doc, change);
	      }

	      // Call f for all linked documents.
	      function linkedDocs(doc, f, sharedHistOnly) {
	        function propagate(doc, skip, sharedHist) {
	          if (doc.linked) {
	            for (var i = 0; i < doc.linked.length; ++i) {
	              var rel = doc.linked[i];
	              if (rel.doc == skip) {
	                continue;
	              }
	              var shared = sharedHist && rel.sharedHist;
	              if (sharedHistOnly && !shared) {
	                continue;
	              }
	              f(rel.doc, shared);
	              propagate(rel.doc, doc, shared);
	            }
	          }
	        }
	        propagate(doc, null, true);
	      }

	      // Attach a document to an editor.
	      function attachDoc(cm, doc) {
	        if (doc.cm) {
	          throw new Error("This document is already in use.");
	        }
	        cm.doc = doc;
	        doc.cm = cm;
	        estimateLineHeights(cm);
	        loadMode(cm);
	        setDirectionClass(cm);
	        cm.options.direction = doc.direction;
	        if (!cm.options.lineWrapping) {
	          findMaxLine(cm);
	        }
	        cm.options.mode = doc.modeOption;
	        regChange(cm);
	      }
	      function setDirectionClass(cm) {
	        (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
	      }
	      function directionChanged(cm) {
	        runInOp(cm, function () {
	          setDirectionClass(cm);
	          regChange(cm);
	        });
	      }
	      function History(prev) {
	        // Arrays of change events and selections. Doing something adds an
	        // event to done and clears undo. Undoing moves events from done
	        // to undone, redoing moves them in the other direction.
	        this.done = [];
	        this.undone = [];
	        this.undoDepth = prev ? prev.undoDepth : Infinity;
	        // Used to track when changes can be merged into a single undo
	        // event
	        this.lastModTime = this.lastSelTime = 0;
	        this.lastOp = this.lastSelOp = null;
	        this.lastOrigin = this.lastSelOrigin = null;
	        // Used by the isClean() method
	        this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1;
	      }

	      // Create a history change event from an updateDoc-style change
	      // object.
	      function historyChangeFromChange(doc, change) {
	        var histChange = {
	          from: copyPos(change.from),
	          to: changeEnd(change),
	          text: getBetween(doc, change.from, change.to)
	        };
	        attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
	        linkedDocs(doc, function (doc) {
	          return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
	        }, true);
	        return histChange;
	      }

	      // Pop all selection events off the end of a history array. Stop at
	      // a change event.
	      function clearSelectionEvents(array) {
	        while (array.length) {
	          var last = lst(array);
	          if (last.ranges) {
	            array.pop();
	          } else {
	            break;
	          }
	        }
	      }

	      // Find the top change event in the history. Pop off selection
	      // events that are in the way.
	      function lastChangeEvent(hist, force) {
	        if (force) {
	          clearSelectionEvents(hist.done);
	          return lst(hist.done);
	        } else if (hist.done.length && !lst(hist.done).ranges) {
	          return lst(hist.done);
	        } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
	          hist.done.pop();
	          return lst(hist.done);
	        }
	      }

	      // Register a change in the history. Merges changes that are within
	      // a single operation, or are close together with an origin that
	      // allows merging (starting with "+") into a single event.
	      function addChangeToHistory(doc, change, selAfter, opId) {
	        var hist = doc.history;
	        hist.undone.length = 0;
	        var time = +new Date(),
	          cur;
	        var last;
	        if ((hist.lastOp == opId || hist.lastOrigin == change.origin && change.origin && (change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500) || change.origin.charAt(0) == "*")) && (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
	          // Merge this change into the last event
	          last = lst(cur.changes);
	          if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
	            // Optimized case for simple insertion -- don't want to add
	            // new changesets for every character typed
	            last.to = changeEnd(change);
	          } else {
	            // Add new sub-event
	            cur.changes.push(historyChangeFromChange(doc, change));
	          }
	        } else {
	          // Can not be merged, start a new event.
	          var before = lst(hist.done);
	          if (!before || !before.ranges) {
	            pushSelectionToHistory(doc.sel, hist.done);
	          }
	          cur = {
	            changes: [historyChangeFromChange(doc, change)],
	            generation: hist.generation
	          };
	          hist.done.push(cur);
	          while (hist.done.length > hist.undoDepth) {
	            hist.done.shift();
	            if (!hist.done[0].ranges) {
	              hist.done.shift();
	            }
	          }
	        }
	        hist.done.push(selAfter);
	        hist.generation = ++hist.maxGeneration;
	        hist.lastModTime = hist.lastSelTime = time;
	        hist.lastOp = hist.lastSelOp = opId;
	        hist.lastOrigin = hist.lastSelOrigin = change.origin;
	        if (!last) {
	          signal(doc, "historyAdded");
	        }
	      }
	      function selectionEventCanBeMerged(doc, origin, prev, sel) {
	        var ch = origin.charAt(0);
	        return ch == "*" || ch == "+" && prev.ranges.length == sel.ranges.length && prev.somethingSelected() == sel.somethingSelected() && new Date() - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
	      }

	      // Called whenever the selection changes, sets the new selection as
	      // the pending selection in the history, and pushes the old pending
	      // selection into the 'done' array when it was significantly
	      // different (in number of selected ranges, emptiness, or time).
	      function addSelectionToHistory(doc, sel, opId, options) {
	        var hist = doc.history,
	          origin = options && options.origin;

	        // A new event is started when the previous origin does not match
	        // the current, or the origins don't allow matching. Origins
	        // starting with * are always merged, those starting with + are
	        // merged when similar and close together in time.
	        if (opId == hist.lastSelOp || origin && hist.lastSelOrigin == origin && (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))) {
	          hist.done[hist.done.length - 1] = sel;
	        } else {
	          pushSelectionToHistory(sel, hist.done);
	        }
	        hist.lastSelTime = +new Date();
	        hist.lastSelOrigin = origin;
	        hist.lastSelOp = opId;
	        if (options && options.clearRedo !== false) {
	          clearSelectionEvents(hist.undone);
	        }
	      }
	      function pushSelectionToHistory(sel, dest) {
	        var top = lst(dest);
	        if (!(top && top.ranges && top.equals(sel))) {
	          dest.push(sel);
	        }
	      }

	      // Used to store marked span information in the history.
	      function attachLocalSpans(doc, change, from, to) {
	        var existing = change["spans_" + doc.id],
	          n = 0;
	        doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
	          if (line.markedSpans) {
	            (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
	          }
	          ++n;
	        });
	      }

	      // When un/re-doing restores text containing marked spans, those
	      // that have been explicitly cleared should not be restored.
	      function removeClearedSpans(spans) {
	        if (!spans) {
	          return null;
	        }
	        var out;
	        for (var i = 0; i < spans.length; ++i) {
	          if (spans[i].marker.explicitlyCleared) {
	            if (!out) {
	              out = spans.slice(0, i);
	            }
	          } else if (out) {
	            out.push(spans[i]);
	          }
	        }
	        return !out ? spans : out.length ? out : null;
	      }

	      // Retrieve and filter the old marked spans stored in a change event.
	      function getOldSpans(doc, change) {
	        var found = change["spans_" + doc.id];
	        if (!found) {
	          return null;
	        }
	        var nw = [];
	        for (var i = 0; i < change.text.length; ++i) {
	          nw.push(removeClearedSpans(found[i]));
	        }
	        return nw;
	      }

	      // Used for un/re-doing changes from the history. Combines the
	      // result of computing the existing spans with the set of spans that
	      // existed in the history (so that deleting around a span and then
	      // undoing brings back the span).
	      function mergeOldSpans(doc, change) {
	        var old = getOldSpans(doc, change);
	        var stretched = stretchSpansOverChange(doc, change);
	        if (!old) {
	          return stretched;
	        }
	        if (!stretched) {
	          return old;
	        }
	        for (var i = 0; i < old.length; ++i) {
	          var oldCur = old[i],
	            stretchCur = stretched[i];
	          if (oldCur && stretchCur) {
	            spans: for (var j = 0; j < stretchCur.length; ++j) {
	              var span = stretchCur[j];
	              for (var k = 0; k < oldCur.length; ++k) {
	                if (oldCur[k].marker == span.marker) {
	                  continue spans;
	                }
	              }
	              oldCur.push(span);
	            }
	          } else if (stretchCur) {
	            old[i] = stretchCur;
	          }
	        }
	        return old;
	      }

	      // Used both to provide a JSON-safe object in .getHistory, and, when
	      // detaching a document, to split the history in two
	      function copyHistoryArray(events, newGroup, instantiateSel) {
	        var copy = [];
	        for (var i = 0; i < events.length; ++i) {
	          var event = events[i];
	          if (event.ranges) {
	            copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
	            continue;
	          }
	          var changes = event.changes,
	            newChanges = [];
	          copy.push({
	            changes: newChanges
	          });
	          for (var j = 0; j < changes.length; ++j) {
	            var change = changes[j],
	              m = void 0;
	            newChanges.push({
	              from: change.from,
	              to: change.to,
	              text: change.text
	            });
	            if (newGroup) {
	              for (var prop in change) {
	                if (m = prop.match(/^spans_(\d+)$/)) {
	                  if (indexOf(newGroup, Number(m[1])) > -1) {
	                    lst(newChanges)[prop] = change[prop];
	                    delete change[prop];
	                  }
	                }
	              }
	            }
	          }
	        }
	        return copy;
	      }

	      // The 'scroll' parameter given to many of these indicated whether
	      // the new cursor position should be scrolled into view after
	      // modifying the selection.

	      // If shift is held or the extend flag is set, extends a range to
	      // include a given position (and optionally a second position).
	      // Otherwise, simply returns the range between the given positions.
	      // Used for cursor motion and such.
	      function extendRange(range, head, other, extend) {
	        if (extend) {
	          var anchor = range.anchor;
	          if (other) {
	            var posBefore = cmp(head, anchor) < 0;
	            if (posBefore != cmp(other, anchor) < 0) {
	              anchor = head;
	              head = other;
	            } else if (posBefore != cmp(head, other) < 0) {
	              head = other;
	            }
	          }
	          return new Range(anchor, head);
	        } else {
	          return new Range(other || head, head);
	        }
	      }

	      // Extend the primary selection range, discard the rest.
	      function extendSelection(doc, head, other, options, extend) {
	        if (extend == null) {
	          extend = doc.cm && (doc.cm.display.shift || doc.extend);
	        }
	        setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
	      }

	      // Extend all selections (pos is an array of selections with length
	      // equal the number of selections)
	      function extendSelections(doc, heads, options) {
	        var out = [];
	        var extend = doc.cm && (doc.cm.display.shift || doc.extend);
	        for (var i = 0; i < doc.sel.ranges.length; i++) {
	          out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend);
	        }
	        var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
	        setSelection(doc, newSel, options);
	      }

	      // Updates a single range in the selection.
	      function replaceOneSelection(doc, i, range, options) {
	        var ranges = doc.sel.ranges.slice(0);
	        ranges[i] = range;
	        setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
	      }

	      // Reset the selection to a single range.
	      function setSimpleSelection(doc, anchor, head, options) {
	        setSelection(doc, simpleSelection(anchor, head), options);
	      }

	      // Give beforeSelectionChange handlers a change to influence a
	      // selection update.
	      function filterSelectionChange(doc, sel, options) {
	        var obj = {
	          ranges: sel.ranges,
	          update: function (ranges) {
	            this.ranges = [];
	            for (var i = 0; i < ranges.length; i++) {
	              this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), clipPos(doc, ranges[i].head));
	            }
	          },
	          origin: options && options.origin
	        };
	        signal(doc, "beforeSelectionChange", doc, obj);
	        if (doc.cm) {
	          signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
	        }
	        if (obj.ranges != sel.ranges) {
	          return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1);
	        } else {
	          return sel;
	        }
	      }
	      function setSelectionReplaceHistory(doc, sel, options) {
	        var done = doc.history.done,
	          last = lst(done);
	        if (last && last.ranges) {
	          done[done.length - 1] = sel;
	          setSelectionNoUndo(doc, sel, options);
	        } else {
	          setSelection(doc, sel, options);
	        }
	      }

	      // Set a new selection.
	      function setSelection(doc, sel, options) {
	        setSelectionNoUndo(doc, sel, options);
	        addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
	      }
	      function setSelectionNoUndo(doc, sel, options) {
	        if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) {
	          sel = filterSelectionChange(doc, sel, options);
	        }
	        var bias = options && options.bias || (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
	        setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
	        if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor") {
	          ensureCursorVisible(doc.cm);
	        }
	      }
	      function setSelectionInner(doc, sel) {
	        if (sel.equals(doc.sel)) {
	          return;
	        }
	        doc.sel = sel;
	        if (doc.cm) {
	          doc.cm.curOp.updateInput = 1;
	          doc.cm.curOp.selectionChanged = true;
	          signalCursorActivity(doc.cm);
	        }
	        signalLater(doc, "cursorActivity", doc);
	      }

	      // Verify that the selection does not partially select any atomic
	      // marked ranges.
	      function reCheckSelection(doc) {
	        setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
	      }

	      // Return a selection that does not partially select any atomic
	      // ranges.
	      function skipAtomicInSelection(doc, sel, bias, mayClear) {
	        var out;
	        for (var i = 0; i < sel.ranges.length; i++) {
	          var range = sel.ranges[i];
	          var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
	          var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
	          var newHead = range.head == range.anchor ? newAnchor : skipAtomic(doc, range.head, old && old.head, bias, mayClear);
	          if (out || newAnchor != range.anchor || newHead != range.head) {
	            if (!out) {
	              out = sel.ranges.slice(0, i);
	            }
	            out[i] = new Range(newAnchor, newHead);
	          }
	        }
	        return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel;
	      }
	      function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
	        var line = getLine(doc, pos.line);
	        if (line.markedSpans) {
	          for (var i = 0; i < line.markedSpans.length; ++i) {
	            var sp = line.markedSpans[i],
	              m = sp.marker;

	            // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
	            // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
	            // is with selectLeft/Right
	            var preventCursorLeft = "selectLeft" in m ? !m.selectLeft : m.inclusiveLeft;
	            var preventCursorRight = "selectRight" in m ? !m.selectRight : m.inclusiveRight;
	            if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
	              if (mayClear) {
	                signal(m, "beforeCursorEnter");
	                if (m.explicitlyCleared) {
	                  if (!line.markedSpans) {
	                    break;
	                  } else {
	                    --i;
	                    continue;
	                  }
	                }
	              }
	              if (!m.atomic) {
	                continue;
	              }
	              if (oldPos) {
	                var near = m.find(dir < 0 ? 1 : -1),
	                  diff = void 0;
	                if (dir < 0 ? preventCursorRight : preventCursorLeft) {
	                  near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null);
	                }
	                if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) {
	                  return skipAtomicInner(doc, near, pos, dir, mayClear);
	                }
	              }
	              var far = m.find(dir < 0 ? -1 : 1);
	              if (dir < 0 ? preventCursorLeft : preventCursorRight) {
	                far = movePos(doc, far, dir, far.line == pos.line ? line : null);
	              }
	              return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null;
	            }
	          }
	        }
	        return pos;
	      }

	      // Ensure a given position is not inside an atomic range.
	      function skipAtomic(doc, pos, oldPos, bias, mayClear) {
	        var dir = bias || 1;
	        var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || !mayClear && skipAtomicInner(doc, pos, oldPos, dir, true) || skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || !mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true);
	        if (!found) {
	          doc.cantEdit = true;
	          return Pos(doc.first, 0);
	        }
	        return found;
	      }
	      function movePos(doc, pos, dir, line) {
	        if (dir < 0 && pos.ch == 0) {
	          if (pos.line > doc.first) {
	            return clipPos(doc, Pos(pos.line - 1));
	          } else {
	            return null;
	          }
	        } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
	          if (pos.line < doc.first + doc.size - 1) {
	            return Pos(pos.line + 1, 0);
	          } else {
	            return null;
	          }
	        } else {
	          return new Pos(pos.line, pos.ch + dir);
	        }
	      }
	      function selectAll(cm) {
	        cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
	      }

	      // UPDATING

	      // Allow "beforeChange" event handlers to influence a change
	      function filterChange(doc, change, update) {
	        var obj = {
	          canceled: false,
	          from: change.from,
	          to: change.to,
	          text: change.text,
	          origin: change.origin,
	          cancel: function () {
	            return obj.canceled = true;
	          }
	        };
	        if (update) {
	          obj.update = function (from, to, text, origin) {
	            if (from) {
	              obj.from = clipPos(doc, from);
	            }
	            if (to) {
	              obj.to = clipPos(doc, to);
	            }
	            if (text) {
	              obj.text = text;
	            }
	            if (origin !== undefined) {
	              obj.origin = origin;
	            }
	          };
	        }
	        signal(doc, "beforeChange", doc, obj);
	        if (doc.cm) {
	          signal(doc.cm, "beforeChange", doc.cm, obj);
	        }
	        if (obj.canceled) {
	          if (doc.cm) {
	            doc.cm.curOp.updateInput = 2;
	          }
	          return null;
	        }
	        return {
	          from: obj.from,
	          to: obj.to,
	          text: obj.text,
	          origin: obj.origin
	        };
	      }

	      // Apply a change to a document, and add it to the document's
	      // history, and propagating it to all linked documents.
	      function makeChange(doc, change, ignoreReadOnly) {
	        if (doc.cm) {
	          if (!doc.cm.curOp) {
	            return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
	          }
	          if (doc.cm.state.suppressEdits) {
	            return;
	          }
	        }
	        if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
	          change = filterChange(doc, change, true);
	          if (!change) {
	            return;
	          }
	        }

	        // Possibly split or suppress the update based on the presence
	        // of read-only spans in its range.
	        var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
	        if (split) {
	          for (var i = split.length - 1; i >= 0; --i) {
	            makeChangeInner(doc, {
	              from: split[i].from,
	              to: split[i].to,
	              text: i ? [""] : change.text,
	              origin: change.origin
	            });
	          }
	        } else {
	          makeChangeInner(doc, change);
	        }
	      }
	      function makeChangeInner(doc, change) {
	        if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) {
	          return;
	        }
	        var selAfter = computeSelAfterChange(doc, change);
	        addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
	        makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
	        var rebased = [];
	        linkedDocs(doc, function (doc, sharedHist) {
	          if (!sharedHist && indexOf(rebased, doc.history) == -1) {
	            rebaseHist(doc.history, change);
	            rebased.push(doc.history);
	          }
	          makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
	        });
	      }

	      // Revert a change stored in a document's history.
	      function makeChangeFromHistory(doc, type, allowSelectionOnly) {
	        var suppress = doc.cm && doc.cm.state.suppressEdits;
	        if (suppress && !allowSelectionOnly) {
	          return;
	        }
	        var hist = doc.history,
	          event,
	          selAfter = doc.sel;
	        var source = type == "undo" ? hist.done : hist.undone,
	          dest = type == "undo" ? hist.undone : hist.done;

	        // Verify that there is a useable event (so that ctrl-z won't
	        // needlessly clear selection events)
	        var i = 0;
	        for (; i < source.length; i++) {
	          event = source[i];
	          if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) {
	            break;
	          }
	        }
	        if (i == source.length) {
	          return;
	        }
	        hist.lastOrigin = hist.lastSelOrigin = null;
	        for (;;) {
	          event = source.pop();
	          if (event.ranges) {
	            pushSelectionToHistory(event, dest);
	            if (allowSelectionOnly && !event.equals(doc.sel)) {
	              setSelection(doc, event, {
	                clearRedo: false
	              });
	              return;
	            }
	            selAfter = event;
	          } else if (suppress) {
	            source.push(event);
	            return;
	          } else {
	            break;
	          }
	        }

	        // Build up a reverse change object to add to the opposite history
	        // stack (redo when undoing, and vice versa).
	        var antiChanges = [];
	        pushSelectionToHistory(selAfter, dest);
	        dest.push({
	          changes: antiChanges,
	          generation: hist.generation
	        });
	        hist.generation = event.generation || ++hist.maxGeneration;
	        var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
	        var loop = function (i) {
	          var change = event.changes[i];
	          change.origin = type;
	          if (filter && !filterChange(doc, change, false)) {
	            source.length = 0;
	            return {};
	          }
	          antiChanges.push(historyChangeFromChange(doc, change));
	          var after = i ? computeSelAfterChange(doc, change) : lst(source);
	          makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
	          if (!i && doc.cm) {
	            doc.cm.scrollIntoView({
	              from: change.from,
	              to: changeEnd(change)
	            });
	          }
	          var rebased = [];

	          // Propagate to the linked documents
	          linkedDocs(doc, function (doc, sharedHist) {
	            if (!sharedHist && indexOf(rebased, doc.history) == -1) {
	              rebaseHist(doc.history, change);
	              rebased.push(doc.history);
	            }
	            makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
	          });
	        };
	        for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
	          var returned = loop(i$1);
	          if (returned) return returned.v;
	        }
	      }

	      // Sub-views need their line numbers shifted when text is added
	      // above or below them in the parent document.
	      function shiftDoc(doc, distance) {
	        if (distance == 0) {
	          return;
	        }
	        doc.first += distance;
	        doc.sel = new Selection(map(doc.sel.ranges, function (range) {
	          return new Range(Pos(range.anchor.line + distance, range.anchor.ch), Pos(range.head.line + distance, range.head.ch));
	        }), doc.sel.primIndex);
	        if (doc.cm) {
	          regChange(doc.cm, doc.first, doc.first - distance, distance);
	          for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) {
	            regLineChange(doc.cm, l, "gutter");
	          }
	        }
	      }

	      // More lower-level change function, handling only a single document
	      // (not linked ones).
	      function makeChangeSingleDoc(doc, change, selAfter, spans) {
	        if (doc.cm && !doc.cm.curOp) {
	          return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
	        }
	        if (change.to.line < doc.first) {
	          shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
	          return;
	        }
	        if (change.from.line > doc.lastLine()) {
	          return;
	        }

	        // Clip the change to the size of this doc
	        if (change.from.line < doc.first) {
	          var shift = change.text.length - 1 - (doc.first - change.from.line);
	          shiftDoc(doc, shift);
	          change = {
	            from: Pos(doc.first, 0),
	            to: Pos(change.to.line + shift, change.to.ch),
	            text: [lst(change.text)],
	            origin: change.origin
	          };
	        }
	        var last = doc.lastLine();
	        if (change.to.line > last) {
	          change = {
	            from: change.from,
	            to: Pos(last, getLine(doc, last).text.length),
	            text: [change.text[0]],
	            origin: change.origin
	          };
	        }
	        change.removed = getBetween(doc, change.from, change.to);
	        if (!selAfter) {
	          selAfter = computeSelAfterChange(doc, change);
	        }
	        if (doc.cm) {
	          makeChangeSingleDocInEditor(doc.cm, change, spans);
	        } else {
	          updateDoc(doc, change, spans);
	        }
	        setSelectionNoUndo(doc, selAfter, sel_dontScroll);
	        if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0))) {
	          doc.cantEdit = false;
	        }
	      }

	      // Handle the interaction of a change to a document with the editor
	      // that this document is part of.
	      function makeChangeSingleDocInEditor(cm, change, spans) {
	        var doc = cm.doc,
	          display = cm.display,
	          from = change.from,
	          to = change.to;
	        var recomputeMaxLength = false,
	          checkWidthStart = from.line;
	        if (!cm.options.lineWrapping) {
	          checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
	          doc.iter(checkWidthStart, to.line + 1, function (line) {
	            if (line == display.maxLine) {
	              recomputeMaxLength = true;
	              return true;
	            }
	          });
	        }
	        if (doc.sel.contains(change.from, change.to) > -1) {
	          signalCursorActivity(cm);
	        }
	        updateDoc(doc, change, spans, estimateHeight(cm));
	        if (!cm.options.lineWrapping) {
	          doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
	            var len = lineLength(line);
	            if (len > display.maxLineLength) {
	              display.maxLine = line;
	              display.maxLineLength = len;
	              display.maxLineChanged = true;
	              recomputeMaxLength = false;
	            }
	          });
	          if (recomputeMaxLength) {
	            cm.curOp.updateMaxLine = true;
	          }
	        }
	        retreatFrontier(doc, from.line);
	        startWorker(cm, 400);
	        var lendiff = change.text.length - (to.line - from.line) - 1;
	        // Remember that these lines changed, for updating the display
	        if (change.full) {
	          regChange(cm);
	        } else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) {
	          regLineChange(cm, from.line, "text");
	        } else {
	          regChange(cm, from.line, to.line + 1, lendiff);
	        }
	        var changesHandler = hasHandler(cm, "changes"),
	          changeHandler = hasHandler(cm, "change");
	        if (changeHandler || changesHandler) {
	          var obj = {
	            from: from,
	            to: to,
	            text: change.text,
	            removed: change.removed,
	            origin: change.origin
	          };
	          if (changeHandler) {
	            signalLater(cm, "change", cm, obj);
	          }
	          if (changesHandler) {
	            (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
	          }
	        }
	        cm.display.selForContextMenu = null;
	      }
	      function replaceRange(doc, code, from, to, origin) {
	        var assign;
	        if (!to) {
	          to = from;
	        }
	        if (cmp(to, from) < 0) {
	          assign = [to, from], from = assign[0], to = assign[1];
	        }
	        if (typeof code == "string") {
	          code = doc.splitLines(code);
	        }
	        makeChange(doc, {
	          from: from,
	          to: to,
	          text: code,
	          origin: origin
	        });
	      }

	      // Rebasing/resetting history to deal with externally-sourced changes

	      function rebaseHistSelSingle(pos, from, to, diff) {
	        if (to < pos.line) {
	          pos.line += diff;
	        } else if (from < pos.line) {
	          pos.line = from;
	          pos.ch = 0;
	        }
	      }

	      // Tries to rebase an array of history events given a change in the
	      // document. If the change touches the same lines as the event, the
	      // event, and everything 'behind' it, is discarded. If the change is
	      // before the event, the event's positions are updated. Uses a
	      // copy-on-write scheme for the positions, to avoid having to
	      // reallocate them all on every rebase, but also avoid problems with
	      // shared position objects being unsafely updated.
	      function rebaseHistArray(array, from, to, diff) {
	        for (var i = 0; i < array.length; ++i) {
	          var sub = array[i],
	            ok = true;
	          if (sub.ranges) {
	            if (!sub.copied) {
	              sub = array[i] = sub.deepCopy();
	              sub.copied = true;
	            }
	            for (var j = 0; j < sub.ranges.length; j++) {
	              rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
	              rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
	            }
	            continue;
	          }
	          for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
	            var cur = sub.changes[j$1];
	            if (to < cur.from.line) {
	              cur.from = Pos(cur.from.line + diff, cur.from.ch);
	              cur.to = Pos(cur.to.line + diff, cur.to.ch);
	            } else if (from <= cur.to.line) {
	              ok = false;
	              break;
	            }
	          }
	          if (!ok) {
	            array.splice(0, i + 1);
	            i = 0;
	          }
	        }
	      }
	      function rebaseHist(hist, change) {
	        var from = change.from.line,
	          to = change.to.line,
	          diff = change.text.length - (to - from) - 1;
	        rebaseHistArray(hist.done, from, to, diff);
	        rebaseHistArray(hist.undone, from, to, diff);
	      }

	      // Utility for applying a change to a line by handle or number,
	      // returning the number and optionally registering the line as
	      // changed.
	      function changeLine(doc, handle, changeType, op) {
	        var no = handle,
	          line = handle;
	        if (typeof handle == "number") {
	          line = getLine(doc, clipLine(doc, handle));
	        } else {
	          no = lineNo(handle);
	        }
	        if (no == null) {
	          return null;
	        }
	        if (op(line, no) && doc.cm) {
	          regLineChange(doc.cm, no, changeType);
	        }
	        return line;
	      }

	      // The document is represented as a BTree consisting of leaves, with
	      // chunk of lines in them, and branches, with up to ten leaves or
	      // other branch nodes below them. The top node is always a branch
	      // node, and is the document object itself (meaning it has
	      // additional methods and properties).
	      //
	      // All nodes have parent links. The tree is used both to go from
	      // line numbers to line objects, and to go from objects to numbers.
	      // It also indexes by height, and is used to convert between height
	      // and line object, and to find the total height of the document.
	      //
	      // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html

	      function LeafChunk(lines) {
	        this.lines = lines;
	        this.parent = null;
	        var height = 0;
	        for (var i = 0; i < lines.length; ++i) {
	          lines[i].parent = this;
	          height += lines[i].height;
	        }
	        this.height = height;
	      }
	      LeafChunk.prototype = {
	        chunkSize: function () {
	          return this.lines.length;
	        },
	        // Remove the n lines at offset 'at'.
	        removeInner: function (at, n) {
	          for (var i = at, e = at + n; i < e; ++i) {
	            var line = this.lines[i];
	            this.height -= line.height;
	            cleanUpLine(line);
	            signalLater(line, "delete");
	          }
	          this.lines.splice(at, n);
	        },
	        // Helper used to collapse a small branch into a single leaf.
	        collapse: function (lines) {
	          lines.push.apply(lines, this.lines);
	        },
	        // Insert the given array of lines at offset 'at', count them as
	        // having the given height.
	        insertInner: function (at, lines, height) {
	          this.height += height;
	          this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
	          for (var i = 0; i < lines.length; ++i) {
	            lines[i].parent = this;
	          }
	        },
	        // Used to iterate over a part of the tree.
	        iterN: function (at, n, op) {
	          for (var e = at + n; at < e; ++at) {
	            if (op(this.lines[at])) {
	              return true;
	            }
	          }
	        }
	      };
	      function BranchChunk(children) {
	        this.children = children;
	        var size = 0,
	          height = 0;
	        for (var i = 0; i < children.length; ++i) {
	          var ch = children[i];
	          size += ch.chunkSize();
	          height += ch.height;
	          ch.parent = this;
	        }
	        this.size = size;
	        this.height = height;
	        this.parent = null;
	      }
	      BranchChunk.prototype = {
	        chunkSize: function () {
	          return this.size;
	        },
	        removeInner: function (at, n) {
	          this.size -= n;
	          for (var i = 0; i < this.children.length; ++i) {
	            var child = this.children[i],
	              sz = child.chunkSize();
	            if (at < sz) {
	              var rm = Math.min(n, sz - at),
	                oldHeight = child.height;
	              child.removeInner(at, rm);
	              this.height -= oldHeight - child.height;
	              if (sz == rm) {
	                this.children.splice(i--, 1);
	                child.parent = null;
	              }
	              if ((n -= rm) == 0) {
	                break;
	              }
	              at = 0;
	            } else {
	              at -= sz;
	            }
	          }
	          // If the result is smaller than 25 lines, ensure that it is a
	          // single leaf node.
	          if (this.size - n < 25 && (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
	            var lines = [];
	            this.collapse(lines);
	            this.children = [new LeafChunk(lines)];
	            this.children[0].parent = this;
	          }
	        },
	        collapse: function (lines) {
	          for (var i = 0; i < this.children.length; ++i) {
	            this.children[i].collapse(lines);
	          }
	        },
	        insertInner: function (at, lines, height) {
	          this.size += lines.length;
	          this.height += height;
	          for (var i = 0; i < this.children.length; ++i) {
	            var child = this.children[i],
	              sz = child.chunkSize();
	            if (at <= sz) {
	              child.insertInner(at, lines, height);
	              if (child.lines && child.lines.length > 50) {
	                // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
	                // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
	                var remaining = child.lines.length % 25 + 25;
	                for (var pos = remaining; pos < child.lines.length;) {
	                  var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
	                  child.height -= leaf.height;
	                  this.children.splice(++i, 0, leaf);
	                  leaf.parent = this;
	                }
	                child.lines = child.lines.slice(0, remaining);
	                this.maybeSpill();
	              }
	              break;
	            }
	            at -= sz;
	          }
	        },
	        // When a node has grown, check whether it should be split.
	        maybeSpill: function () {
	          if (this.children.length <= 10) {
	            return;
	          }
	          var me = this;
	          do {
	            var spilled = me.children.splice(me.children.length - 5, 5);
	            var sibling = new BranchChunk(spilled);
	            if (!me.parent) {
	              // Become the parent node
	              var copy = new BranchChunk(me.children);
	              copy.parent = me;
	              me.children = [copy, sibling];
	              me = copy;
	            } else {
	              me.size -= sibling.size;
	              me.height -= sibling.height;
	              var myIndex = indexOf(me.parent.children, me);
	              me.parent.children.splice(myIndex + 1, 0, sibling);
	            }
	            sibling.parent = me.parent;
	          } while (me.children.length > 10);
	          me.parent.maybeSpill();
	        },
	        iterN: function (at, n, op) {
	          for (var i = 0; i < this.children.length; ++i) {
	            var child = this.children[i],
	              sz = child.chunkSize();
	            if (at < sz) {
	              var used = Math.min(n, sz - at);
	              if (child.iterN(at, used, op)) {
	                return true;
	              }
	              if ((n -= used) == 0) {
	                break;
	              }
	              at = 0;
	            } else {
	              at -= sz;
	            }
	          }
	        }
	      };

	      // Line widgets are block elements displayed above or below a line.

	      var LineWidget = function (doc, node, options) {
	        if (options) {
	          for (var opt in options) {
	            if (options.hasOwnProperty(opt)) {
	              this[opt] = options[opt];
	            }
	          }
	        }
	        this.doc = doc;
	        this.node = node;
	      };
	      LineWidget.prototype.clear = function () {
	        var cm = this.doc.cm,
	          ws = this.line.widgets,
	          line = this.line,
	          no = lineNo(line);
	        if (no == null || !ws) {
	          return;
	        }
	        for (var i = 0; i < ws.length; ++i) {
	          if (ws[i] == this) {
	            ws.splice(i--, 1);
	          }
	        }
	        if (!ws.length) {
	          line.widgets = null;
	        }
	        var height = widgetHeight(this);
	        updateLineHeight(line, Math.max(0, line.height - height));
	        if (cm) {
	          runInOp(cm, function () {
	            adjustScrollWhenAboveVisible(cm, line, -height);
	            regLineChange(cm, no, "widget");
	          });
	          signalLater(cm, "lineWidgetCleared", cm, this, no);
	        }
	      };
	      LineWidget.prototype.changed = function () {
	        var this$1$1 = this;
	        var oldH = this.height,
	          cm = this.doc.cm,
	          line = this.line;
	        this.height = null;
	        var diff = widgetHeight(this) - oldH;
	        if (!diff) {
	          return;
	        }
	        if (!lineIsHidden(this.doc, line)) {
	          updateLineHeight(line, line.height + diff);
	        }
	        if (cm) {
	          runInOp(cm, function () {
	            cm.curOp.forceUpdate = true;
	            adjustScrollWhenAboveVisible(cm, line, diff);
	            signalLater(cm, "lineWidgetChanged", cm, this$1$1, lineNo(line));
	          });
	        }
	      };
	      eventMixin(LineWidget);
	      function adjustScrollWhenAboveVisible(cm, line, diff) {
	        if (heightAtLine(line) < (cm.curOp && cm.curOp.scrollTop || cm.doc.scrollTop)) {
	          addToScrollTop(cm, diff);
	        }
	      }
	      function addLineWidget(doc, handle, node, options) {
	        var widget = new LineWidget(doc, node, options);
	        var cm = doc.cm;
	        if (cm && widget.noHScroll) {
	          cm.display.alignWidgets = true;
	        }
	        changeLine(doc, handle, "widget", function (line) {
	          var widgets = line.widgets || (line.widgets = []);
	          if (widget.insertAt == null) {
	            widgets.push(widget);
	          } else {
	            widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget);
	          }
	          widget.line = line;
	          if (cm && !lineIsHidden(doc, line)) {
	            var aboveVisible = heightAtLine(line) < doc.scrollTop;
	            updateLineHeight(line, line.height + widgetHeight(widget));
	            if (aboveVisible) {
	              addToScrollTop(cm, widget.height);
	            }
	            cm.curOp.forceUpdate = true;
	          }
	          return true;
	        });
	        if (cm) {
	          signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle));
	        }
	        return widget;
	      }

	      // TEXTMARKERS

	      // Created with markText and setBookmark methods. A TextMarker is a
	      // handle that can be used to clear or find a marked position in the
	      // document. Line objects hold arrays (markedSpans) containing
	      // {from, to, marker} object pointing to such marker objects, and
	      // indicating that such a marker is present on that line. Multiple
	      // lines may point to the same marker when it spans across lines.
	      // The spans will have null for their from/to properties when the
	      // marker continues beyond the start/end of the line. Markers have
	      // links back to the lines they currently touch.

	      // Collapsed markers have unique ids, in order to be able to order
	      // them, which is needed for uniquely determining an outer marker
	      // when they overlap (they may nest, but not partially overlap).
	      var nextMarkerId = 0;
	      var TextMarker = function (doc, type) {
	        this.lines = [];
	        this.type = type;
	        this.doc = doc;
	        this.id = ++nextMarkerId;
	      };

	      // Clear the marker.
	      TextMarker.prototype.clear = function () {
	        if (this.explicitlyCleared) {
	          return;
	        }
	        var cm = this.doc.cm,
	          withOp = cm && !cm.curOp;
	        if (withOp) {
	          startOperation(cm);
	        }
	        if (hasHandler(this, "clear")) {
	          var found = this.find();
	          if (found) {
	            signalLater(this, "clear", found.from, found.to);
	          }
	        }
	        var min = null,
	          max = null;
	        for (var i = 0; i < this.lines.length; ++i) {
	          var line = this.lines[i];
	          var span = getMarkedSpanFor(line.markedSpans, this);
	          if (cm && !this.collapsed) {
	            regLineChange(cm, lineNo(line), "text");
	          } else if (cm) {
	            if (span.to != null) {
	              max = lineNo(line);
	            }
	            if (span.from != null) {
	              min = lineNo(line);
	            }
	          }
	          line.markedSpans = removeMarkedSpan(line.markedSpans, span);
	          if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) {
	            updateLineHeight(line, textHeight(cm.display));
	          }
	        }
	        if (cm && this.collapsed && !cm.options.lineWrapping) {
	          for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
	            var visual = visualLine(this.lines[i$1]),
	              len = lineLength(visual);
	            if (len > cm.display.maxLineLength) {
	              cm.display.maxLine = visual;
	              cm.display.maxLineLength = len;
	              cm.display.maxLineChanged = true;
	            }
	          }
	        }
	        if (min != null && cm && this.collapsed) {
	          regChange(cm, min, max + 1);
	        }
	        this.lines.length = 0;
	        this.explicitlyCleared = true;
	        if (this.atomic && this.doc.cantEdit) {
	          this.doc.cantEdit = false;
	          if (cm) {
	            reCheckSelection(cm.doc);
	          }
	        }
	        if (cm) {
	          signalLater(cm, "markerCleared", cm, this, min, max);
	        }
	        if (withOp) {
	          endOperation(cm);
	        }
	        if (this.parent) {
	          this.parent.clear();
	        }
	      };

	      // Find the position of the marker in the document. Returns a {from,
	      // to} object by default. Side can be passed to get a specific side
	      // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
	      // Pos objects returned contain a line object, rather than a line
	      // number (used to prevent looking up the same line twice).
	      TextMarker.prototype.find = function (side, lineObj) {
	        if (side == null && this.type == "bookmark") {
	          side = 1;
	        }
	        var from, to;
	        for (var i = 0; i < this.lines.length; ++i) {
	          var line = this.lines[i];
	          var span = getMarkedSpanFor(line.markedSpans, this);
	          if (span.from != null) {
	            from = Pos(lineObj ? line : lineNo(line), span.from);
	            if (side == -1) {
	              return from;
	            }
	          }
	          if (span.to != null) {
	            to = Pos(lineObj ? line : lineNo(line), span.to);
	            if (side == 1) {
	              return to;
	            }
	          }
	        }
	        return from && {
	          from: from,
	          to: to
	        };
	      };

	      // Signals that the marker's widget changed, and surrounding layout
	      // should be recomputed.
	      TextMarker.prototype.changed = function () {
	        var this$1$1 = this;
	        var pos = this.find(-1, true),
	          widget = this,
	          cm = this.doc.cm;
	        if (!pos || !cm) {
	          return;
	        }
	        runInOp(cm, function () {
	          var line = pos.line,
	            lineN = lineNo(pos.line);
	          var view = findViewForLine(cm, lineN);
	          if (view) {
	            clearLineMeasurementCacheFor(view);
	            cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
	          }
	          cm.curOp.updateMaxLine = true;
	          if (!lineIsHidden(widget.doc, line) && widget.height != null) {
	            var oldHeight = widget.height;
	            widget.height = null;
	            var dHeight = widgetHeight(widget) - oldHeight;
	            if (dHeight) {
	              updateLineHeight(line, line.height + dHeight);
	            }
	          }
	          signalLater(cm, "markerChanged", cm, this$1$1);
	        });
	      };
	      TextMarker.prototype.attachLine = function (line) {
	        if (!this.lines.length && this.doc.cm) {
	          var op = this.doc.cm.curOp;
	          if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) {
	            (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
	          }
	        }
	        this.lines.push(line);
	      };
	      TextMarker.prototype.detachLine = function (line) {
	        this.lines.splice(indexOf(this.lines, line), 1);
	        if (!this.lines.length && this.doc.cm) {
	          var op = this.doc.cm.curOp;
	          (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
	        }
	      };
	      eventMixin(TextMarker);

	      // Create a marker, wire it up to the right lines, and
	      function markText(doc, from, to, options, type) {
	        // Shared markers (across linked documents) are handled separately
	        // (markTextShared will call out to this again, once per
	        // document).
	        if (options && options.shared) {
	          return markTextShared(doc, from, to, options, type);
	        }
	        // Ensure we are in an operation.
	        if (doc.cm && !doc.cm.curOp) {
	          return operation(doc.cm, markText)(doc, from, to, options, type);
	        }
	        var marker = new TextMarker(doc, type),
	          diff = cmp(from, to);
	        if (options) {
	          copyObj(options, marker, false);
	        }
	        // Don't connect empty markers unless clearWhenEmpty is false
	        if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) {
	          return marker;
	        }
	        if (marker.replacedWith) {
	          // Showing up as a widget implies collapsed (widget replaces text)
	          marker.collapsed = true;
	          marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
	          if (!options.handleMouseEvents) {
	            marker.widgetNode.setAttribute("cm-ignore-events", "true");
	          }
	          if (options.insertLeft) {
	            marker.widgetNode.insertLeft = true;
	          }
	        }
	        if (marker.collapsed) {
	          if (conflictingCollapsedRange(doc, from.line, from, to, marker) || from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) {
	            throw new Error("Inserting collapsed marker partially overlapping an existing one");
	          }
	          seeCollapsedSpans();
	        }
	        if (marker.addToHistory) {
	          addChangeToHistory(doc, {
	            from: from,
	            to: to,
	            origin: "markText"
	          }, doc.sel, NaN);
	        }
	        var curLine = from.line,
	          cm = doc.cm,
	          updateMaxLine;
	        doc.iter(curLine, to.line + 1, function (line) {
	          if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) {
	            updateMaxLine = true;
	          }
	          if (marker.collapsed && curLine != from.line) {
	            updateLineHeight(line, 0);
	          }
	          addMarkedSpan(line, new MarkedSpan(marker, curLine == from.line ? from.ch : null, curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp);
	          ++curLine;
	        });
	        // lineIsHidden depends on the presence of the spans, so needs a second pass
	        if (marker.collapsed) {
	          doc.iter(from.line, to.line + 1, function (line) {
	            if (lineIsHidden(doc, line)) {
	              updateLineHeight(line, 0);
	            }
	          });
	        }
	        if (marker.clearOnEnter) {
	          on(marker, "beforeCursorEnter", function () {
	            return marker.clear();
	          });
	        }
	        if (marker.readOnly) {
	          seeReadOnlySpans();
	          if (doc.history.done.length || doc.history.undone.length) {
	            doc.clearHistory();
	          }
	        }
	        if (marker.collapsed) {
	          marker.id = ++nextMarkerId;
	          marker.atomic = true;
	        }
	        if (cm) {
	          // Sync editor state
	          if (updateMaxLine) {
	            cm.curOp.updateMaxLine = true;
	          }
	          if (marker.collapsed) {
	            regChange(cm, from.line, to.line + 1);
	          } else if (marker.className || marker.startStyle || marker.endStyle || marker.css || marker.attributes || marker.title) {
	            for (var i = from.line; i <= to.line; i++) {
	              regLineChange(cm, i, "text");
	            }
	          }
	          if (marker.atomic) {
	            reCheckSelection(cm.doc);
	          }
	          signalLater(cm, "markerAdded", cm, marker);
	        }
	        return marker;
	      }

	      // SHARED TEXTMARKERS

	      // A shared marker spans multiple linked documents. It is
	      // implemented as a meta-marker-object controlling multiple normal
	      // markers.
	      var SharedTextMarker = function (markers, primary) {
	        this.markers = markers;
	        this.primary = primary;
	        for (var i = 0; i < markers.length; ++i) {
	          markers[i].parent = this;
	        }
	      };
	      SharedTextMarker.prototype.clear = function () {
	        if (this.explicitlyCleared) {
	          return;
	        }
	        this.explicitlyCleared = true;
	        for (var i = 0; i < this.markers.length; ++i) {
	          this.markers[i].clear();
	        }
	        signalLater(this, "clear");
	      };
	      SharedTextMarker.prototype.find = function (side, lineObj) {
	        return this.primary.find(side, lineObj);
	      };
	      eventMixin(SharedTextMarker);
	      function markTextShared(doc, from, to, options, type) {
	        options = copyObj(options);
	        options.shared = false;
	        var markers = [markText(doc, from, to, options, type)],
	          primary = markers[0];
	        var widget = options.widgetNode;
	        linkedDocs(doc, function (doc) {
	          if (widget) {
	            options.widgetNode = widget.cloneNode(true);
	          }
	          markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
	          for (var i = 0; i < doc.linked.length; ++i) {
	            if (doc.linked[i].isParent) {
	              return;
	            }
	          }
	          primary = lst(markers);
	        });
	        return new SharedTextMarker(markers, primary);
	      }
	      function findSharedMarkers(doc) {
	        return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) {
	          return m.parent;
	        });
	      }
	      function copySharedMarkers(doc, markers) {
	        for (var i = 0; i < markers.length; i++) {
	          var marker = markers[i],
	            pos = marker.find();
	          var mFrom = doc.clipPos(pos.from),
	            mTo = doc.clipPos(pos.to);
	          if (cmp(mFrom, mTo)) {
	            var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
	            marker.markers.push(subMark);
	            subMark.parent = marker;
	          }
	        }
	      }
	      function detachSharedMarkers(markers) {
	        var loop = function (i) {
	          var marker = markers[i],
	            linked = [marker.primary.doc];
	          linkedDocs(marker.primary.doc, function (d) {
	            return linked.push(d);
	          });
	          for (var j = 0; j < marker.markers.length; j++) {
	            var subMarker = marker.markers[j];
	            if (indexOf(linked, subMarker.doc) == -1) {
	              subMarker.parent = null;
	              marker.markers.splice(j--, 1);
	            }
	          }
	        };
	        for (var i = 0; i < markers.length; i++) loop(i);
	      }
	      var nextDocId = 0;
	      var Doc = function (text, mode, firstLine, lineSep, direction) {
	        if (!(this instanceof Doc)) {
	          return new Doc(text, mode, firstLine, lineSep, direction);
	        }
	        if (firstLine == null) {
	          firstLine = 0;
	        }
	        BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
	        this.first = firstLine;
	        this.scrollTop = this.scrollLeft = 0;
	        this.cantEdit = false;
	        this.cleanGeneration = 1;
	        this.modeFrontier = this.highlightFrontier = firstLine;
	        var start = Pos(firstLine, 0);
	        this.sel = simpleSelection(start);
	        this.history = new History(null);
	        this.id = ++nextDocId;
	        this.modeOption = mode;
	        this.lineSep = lineSep;
	        this.direction = direction == "rtl" ? "rtl" : "ltr";
	        this.extend = false;
	        if (typeof text == "string") {
	          text = this.splitLines(text);
	        }
	        updateDoc(this, {
	          from: start,
	          to: start,
	          text: text
	        });
	        setSelection(this, simpleSelection(start), sel_dontScroll);
	      };
	      Doc.prototype = createObj(BranchChunk.prototype, {
	        constructor: Doc,
	        // Iterate over the document. Supports two forms -- with only one
	        // argument, it calls that for each line in the document. With
	        // three, it iterates over the range given by the first two (with
	        // the second being non-inclusive).
	        iter: function (from, to, op) {
	          if (op) {
	            this.iterN(from - this.first, to - from, op);
	          } else {
	            this.iterN(this.first, this.first + this.size, from);
	          }
	        },
	        // Non-public interface for adding and removing lines.
	        insert: function (at, lines) {
	          var height = 0;
	          for (var i = 0; i < lines.length; ++i) {
	            height += lines[i].height;
	          }
	          this.insertInner(at - this.first, lines, height);
	        },
	        remove: function (at, n) {
	          this.removeInner(at - this.first, n);
	        },
	        // From here, the methods are part of the public interface. Most
	        // are also available from CodeMirror (editor) instances.

	        getValue: function (lineSep) {
	          var lines = getLines(this, this.first, this.first + this.size);
	          if (lineSep === false) {
	            return lines;
	          }
	          return lines.join(lineSep || this.lineSeparator());
	        },
	        setValue: docMethodOp(function (code) {
	          var top = Pos(this.first, 0),
	            last = this.first + this.size - 1;
	          makeChange(this, {
	            from: top,
	            to: Pos(last, getLine(this, last).text.length),
	            text: this.splitLines(code),
	            origin: "setValue",
	            full: true
	          }, true);
	          if (this.cm) {
	            scrollToCoords(this.cm, 0, 0);
	          }
	          setSelection(this, simpleSelection(top), sel_dontScroll);
	        }),
	        replaceRange: function (code, from, to, origin) {
	          from = clipPos(this, from);
	          to = to ? clipPos(this, to) : from;
	          replaceRange(this, code, from, to, origin);
	        },
	        getRange: function (from, to, lineSep) {
	          var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
	          if (lineSep === false) {
	            return lines;
	          }
	          if (lineSep === '') {
	            return lines.join('');
	          }
	          return lines.join(lineSep || this.lineSeparator());
	        },
	        getLine: function (line) {
	          var l = this.getLineHandle(line);
	          return l && l.text;
	        },
	        getLineHandle: function (line) {
	          if (isLine(this, line)) {
	            return getLine(this, line);
	          }
	        },
	        getLineNumber: function (line) {
	          return lineNo(line);
	        },
	        getLineHandleVisualStart: function (line) {
	          if (typeof line == "number") {
	            line = getLine(this, line);
	          }
	          return visualLine(line);
	        },
	        lineCount: function () {
	          return this.size;
	        },
	        firstLine: function () {
	          return this.first;
	        },
	        lastLine: function () {
	          return this.first + this.size - 1;
	        },
	        clipPos: function (pos) {
	          return clipPos(this, pos);
	        },
	        getCursor: function (start) {
	          var range = this.sel.primary(),
	            pos;
	          if (start == null || start == "head") {
	            pos = range.head;
	          } else if (start == "anchor") {
	            pos = range.anchor;
	          } else if (start == "end" || start == "to" || start === false) {
	            pos = range.to();
	          } else {
	            pos = range.from();
	          }
	          return pos;
	        },
	        listSelections: function () {
	          return this.sel.ranges;
	        },
	        somethingSelected: function () {
	          return this.sel.somethingSelected();
	        },
	        setCursor: docMethodOp(function (line, ch, options) {
	          setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
	        }),
	        setSelection: docMethodOp(function (anchor, head, options) {
	          setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
	        }),
	        extendSelection: docMethodOp(function (head, other, options) {
	          extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
	        }),
	        extendSelections: docMethodOp(function (heads, options) {
	          extendSelections(this, clipPosArray(this, heads), options);
	        }),
	        extendSelectionsBy: docMethodOp(function (f, options) {
	          var heads = map(this.sel.ranges, f);
	          extendSelections(this, clipPosArray(this, heads), options);
	        }),
	        setSelections: docMethodOp(function (ranges, primary, options) {
	          if (!ranges.length) {
	            return;
	          }
	          var out = [];
	          for (var i = 0; i < ranges.length; i++) {
	            out[i] = new Range(clipPos(this, ranges[i].anchor), clipPos(this, ranges[i].head || ranges[i].anchor));
	          }
	          if (primary == null) {
	            primary = Math.min(ranges.length - 1, this.sel.primIndex);
	          }
	          setSelection(this, normalizeSelection(this.cm, out, primary), options);
	        }),
	        addSelection: docMethodOp(function (anchor, head, options) {
	          var ranges = this.sel.ranges.slice(0);
	          ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
	          setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
	        }),
	        getSelection: function (lineSep) {
	          var ranges = this.sel.ranges,
	            lines;
	          for (var i = 0; i < ranges.length; i++) {
	            var sel = getBetween(this, ranges[i].from(), ranges[i].to());
	            lines = lines ? lines.concat(sel) : sel;
	          }
	          if (lineSep === false) {
	            return lines;
	          } else {
	            return lines.join(lineSep || this.lineSeparator());
	          }
	        },
	        getSelections: function (lineSep) {
	          var parts = [],
	            ranges = this.sel.ranges;
	          for (var i = 0; i < ranges.length; i++) {
	            var sel = getBetween(this, ranges[i].from(), ranges[i].to());
	            if (lineSep !== false) {
	              sel = sel.join(lineSep || this.lineSeparator());
	            }
	            parts[i] = sel;
	          }
	          return parts;
	        },
	        replaceSelection: function (code, collapse, origin) {
	          var dup = [];
	          for (var i = 0; i < this.sel.ranges.length; i++) {
	            dup[i] = code;
	          }
	          this.replaceSelections(dup, collapse, origin || "+input");
	        },
	        replaceSelections: docMethodOp(function (code, collapse, origin) {
	          var changes = [],
	            sel = this.sel;
	          for (var i = 0; i < sel.ranges.length; i++) {
	            var range = sel.ranges[i];
	            changes[i] = {
	              from: range.from(),
	              to: range.to(),
	              text: this.splitLines(code[i]),
	              origin: origin
	            };
	          }
	          var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
	          for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) {
	            makeChange(this, changes[i$1]);
	          }
	          if (newSel) {
	            setSelectionReplaceHistory(this, newSel);
	          } else if (this.cm) {
	            ensureCursorVisible(this.cm);
	          }
	        }),
	        undo: docMethodOp(function () {
	          makeChangeFromHistory(this, "undo");
	        }),
	        redo: docMethodOp(function () {
	          makeChangeFromHistory(this, "redo");
	        }),
	        undoSelection: docMethodOp(function () {
	          makeChangeFromHistory(this, "undo", true);
	        }),
	        redoSelection: docMethodOp(function () {
	          makeChangeFromHistory(this, "redo", true);
	        }),
	        setExtending: function (val) {
	          this.extend = val;
	        },
	        getExtending: function () {
	          return this.extend;
	        },
	        historySize: function () {
	          var hist = this.history,
	            done = 0,
	            undone = 0;
	          for (var i = 0; i < hist.done.length; i++) {
	            if (!hist.done[i].ranges) {
	              ++done;
	            }
	          }
	          for (var i$1 = 0; i$1 < hist.undone.length; i$1++) {
	            if (!hist.undone[i$1].ranges) {
	              ++undone;
	            }
	          }
	          return {
	            undo: done,
	            redo: undone
	          };
	        },
	        clearHistory: function () {
	          var this$1$1 = this;
	          this.history = new History(this.history);
	          linkedDocs(this, function (doc) {
	            return doc.history = this$1$1.history;
	          }, true);
	        },
	        markClean: function () {
	          this.cleanGeneration = this.changeGeneration(true);
	        },
	        changeGeneration: function (forceSplit) {
	          if (forceSplit) {
	            this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
	          }
	          return this.history.generation;
	        },
	        isClean: function (gen) {
	          return this.history.generation == (gen || this.cleanGeneration);
	        },
	        getHistory: function () {
	          return {
	            done: copyHistoryArray(this.history.done),
	            undone: copyHistoryArray(this.history.undone)
	          };
	        },
	        setHistory: function (histData) {
	          var hist = this.history = new History(this.history);
	          hist.done = copyHistoryArray(histData.done.slice(0), null, true);
	          hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
	        },
	        setGutterMarker: docMethodOp(function (line, gutterID, value) {
	          return changeLine(this, line, "gutter", function (line) {
	            var markers = line.gutterMarkers || (line.gutterMarkers = {});
	            markers[gutterID] = value;
	            if (!value && isEmpty(markers)) {
	              line.gutterMarkers = null;
	            }
	            return true;
	          });
	        }),
	        clearGutter: docMethodOp(function (gutterID) {
	          var this$1$1 = this;
	          this.iter(function (line) {
	            if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
	              changeLine(this$1$1, line, "gutter", function () {
	                line.gutterMarkers[gutterID] = null;
	                if (isEmpty(line.gutterMarkers)) {
	                  line.gutterMarkers = null;
	                }
	                return true;
	              });
	            }
	          });
	        }),
	        lineInfo: function (line) {
	          var n;
	          if (typeof line == "number") {
	            if (!isLine(this, line)) {
	              return null;
	            }
	            n = line;
	            line = getLine(this, line);
	            if (!line) {
	              return null;
	            }
	          } else {
	            n = lineNo(line);
	            if (n == null) {
	              return null;
	            }
	          }
	          return {
	            line: n,
	            handle: line,
	            text: line.text,
	            gutterMarkers: line.gutterMarkers,
	            textClass: line.textClass,
	            bgClass: line.bgClass,
	            wrapClass: line.wrapClass,
	            widgets: line.widgets
	          };
	        },
	        addLineClass: docMethodOp(function (handle, where, cls) {
	          return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
	            var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass";
	            if (!line[prop]) {
	              line[prop] = cls;
	            } else if (classTest(cls).test(line[prop])) {
	              return false;
	            } else {
	              line[prop] += " " + cls;
	            }
	            return true;
	          });
	        }),
	        removeLineClass: docMethodOp(function (handle, where, cls) {
	          return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
	            var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass";
	            var cur = line[prop];
	            if (!cur) {
	              return false;
	            } else if (cls == null) {
	              line[prop] = null;
	            } else {
	              var found = cur.match(classTest(cls));
	              if (!found) {
	                return false;
	              }
	              var end = found.index + found[0].length;
	              line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
	            }
	            return true;
	          });
	        }),
	        addLineWidget: docMethodOp(function (handle, node, options) {
	          return addLineWidget(this, handle, node, options);
	        }),
	        removeLineWidget: function (widget) {
	          widget.clear();
	        },
	        markText: function (from, to, options) {
	          return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range");
	        },
	        setBookmark: function (pos, options) {
	          var realOpts = {
	            replacedWith: options && (options.nodeType == null ? options.widget : options),
	            insertLeft: options && options.insertLeft,
	            clearWhenEmpty: false,
	            shared: options && options.shared,
	            handleMouseEvents: options && options.handleMouseEvents
	          };
	          pos = clipPos(this, pos);
	          return markText(this, pos, pos, realOpts, "bookmark");
	        },
	        findMarksAt: function (pos) {
	          pos = clipPos(this, pos);
	          var markers = [],
	            spans = getLine(this, pos.line).markedSpans;
	          if (spans) {
	            for (var i = 0; i < spans.length; ++i) {
	              var span = spans[i];
	              if ((span.from == null || span.from <= pos.ch) && (span.to == null || span.to >= pos.ch)) {
	                markers.push(span.marker.parent || span.marker);
	              }
	            }
	          }
	          return markers;
	        },
	        findMarks: function (from, to, filter) {
	          from = clipPos(this, from);
	          to = clipPos(this, to);
	          var found = [],
	            lineNo = from.line;
	          this.iter(from.line, to.line + 1, function (line) {
	            var spans = line.markedSpans;
	            if (spans) {
	              for (var i = 0; i < spans.length; i++) {
	                var span = spans[i];
	                if (!(span.to != null && lineNo == from.line && from.ch >= span.to || span.from == null && lineNo != from.line || span.from != null && lineNo == to.line && span.from >= to.ch) && (!filter || filter(span.marker))) {
	                  found.push(span.marker.parent || span.marker);
	                }
	              }
	            }
	            ++lineNo;
	          });
	          return found;
	        },
	        getAllMarks: function () {
	          var markers = [];
	          this.iter(function (line) {
	            var sps = line.markedSpans;
	            if (sps) {
	              for (var i = 0; i < sps.length; ++i) {
	                if (sps[i].from != null) {
	                  markers.push(sps[i].marker);
	                }
	              }
	            }
	          });
	          return markers;
	        },
	        posFromIndex: function (off) {
	          var ch,
	            lineNo = this.first,
	            sepSize = this.lineSeparator().length;
	          this.iter(function (line) {
	            var sz = line.text.length + sepSize;
	            if (sz > off) {
	              ch = off;
	              return true;
	            }
	            off -= sz;
	            ++lineNo;
	          });
	          return clipPos(this, Pos(lineNo, ch));
	        },
	        indexFromPos: function (coords) {
	          coords = clipPos(this, coords);
	          var index = coords.ch;
	          if (coords.line < this.first || coords.ch < 0) {
	            return 0;
	          }
	          var sepSize = this.lineSeparator().length;
	          this.iter(this.first, coords.line, function (line) {
	            // iter aborts when callback returns a truthy value
	            index += line.text.length + sepSize;
	          });
	          return index;
	        },
	        copy: function (copyHistory) {
	          var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first, this.lineSep, this.direction);
	          doc.scrollTop = this.scrollTop;
	          doc.scrollLeft = this.scrollLeft;
	          doc.sel = this.sel;
	          doc.extend = false;
	          if (copyHistory) {
	            doc.history.undoDepth = this.history.undoDepth;
	            doc.setHistory(this.getHistory());
	          }
	          return doc;
	        },
	        linkedDoc: function (options) {
	          if (!options) {
	            options = {};
	          }
	          var from = this.first,
	            to = this.first + this.size;
	          if (options.from != null && options.from > from) {
	            from = options.from;
	          }
	          if (options.to != null && options.to < to) {
	            to = options.to;
	          }
	          var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
	          if (options.sharedHist) {
	            copy.history = this.history;
	          }
	          (this.linked || (this.linked = [])).push({
	            doc: copy,
	            sharedHist: options.sharedHist
	          });
	          copy.linked = [{
	            doc: this,
	            isParent: true,
	            sharedHist: options.sharedHist
	          }];
	          copySharedMarkers(copy, findSharedMarkers(this));
	          return copy;
	        },
	        unlinkDoc: function (other) {
	          if (other instanceof CodeMirror) {
	            other = other.doc;
	          }
	          if (this.linked) {
	            for (var i = 0; i < this.linked.length; ++i) {
	              var link = this.linked[i];
	              if (link.doc != other) {
	                continue;
	              }
	              this.linked.splice(i, 1);
	              other.unlinkDoc(this);
	              detachSharedMarkers(findSharedMarkers(this));
	              break;
	            }
	          }
	          // If the histories were shared, split them again
	          if (other.history == this.history) {
	            var splitIds = [other.id];
	            linkedDocs(other, function (doc) {
	              return splitIds.push(doc.id);
	            }, true);
	            other.history = new History(null);
	            other.history.done = copyHistoryArray(this.history.done, splitIds);
	            other.history.undone = copyHistoryArray(this.history.undone, splitIds);
	          }
	        },
	        iterLinkedDocs: function (f) {
	          linkedDocs(this, f);
	        },
	        getMode: function () {
	          return this.mode;
	        },
	        getEditor: function () {
	          return this.cm;
	        },
	        splitLines: function (str) {
	          if (this.lineSep) {
	            return str.split(this.lineSep);
	          }
	          return splitLinesAuto(str);
	        },
	        lineSeparator: function () {
	          return this.lineSep || "\n";
	        },
	        setDirection: docMethodOp(function (dir) {
	          if (dir != "rtl") {
	            dir = "ltr";
	          }
	          if (dir == this.direction) {
	            return;
	          }
	          this.direction = dir;
	          this.iter(function (line) {
	            return line.order = null;
	          });
	          if (this.cm) {
	            directionChanged(this.cm);
	          }
	        })
	      });

	      // Public alias.
	      Doc.prototype.eachLine = Doc.prototype.iter;

	      // Kludge to work around strange IE behavior where it'll sometimes
	      // re-fire a series of drag-related events right after the drop (#1551)
	      var lastDrop = 0;
	      function onDrop(e) {
	        var cm = this;
	        clearDragCursor(cm);
	        if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) {
	          return;
	        }
	        e_preventDefault(e);
	        if (ie) {
	          lastDrop = +new Date();
	        }
	        var pos = posFromMouse(cm, e, true),
	          files = e.dataTransfer.files;
	        if (!pos || cm.isReadOnly()) {
	          return;
	        }
	        // Might be a file drop, in which case we simply extract the text
	        // and insert it.
	        if (files && files.length && window.FileReader && window.File) {
	          var n = files.length,
	            text = Array(n),
	            read = 0;
	          var markAsReadAndPasteIfAllFilesAreRead = function () {
	            if (++read == n) {
	              operation(cm, function () {
	                pos = clipPos(cm.doc, pos);
	                var change = {
	                  from: pos,
	                  to: pos,
	                  text: cm.doc.splitLines(text.filter(function (t) {
	                    return t != null;
	                  }).join(cm.doc.lineSeparator())),
	                  origin: "paste"
	                };
	                makeChange(cm.doc, change);
	                setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
	              })();
	            }
	          };
	          var readTextFromFile = function (file, i) {
	            if (cm.options.allowDropFileTypes && indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
	              markAsReadAndPasteIfAllFilesAreRead();
	              return;
	            }
	            var reader = new FileReader();
	            reader.onerror = function () {
	              return markAsReadAndPasteIfAllFilesAreRead();
	            };
	            reader.onload = function () {
	              var content = reader.result;
	              if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
	                markAsReadAndPasteIfAllFilesAreRead();
	                return;
	              }
	              text[i] = content;
	              markAsReadAndPasteIfAllFilesAreRead();
	            };
	            reader.readAsText(file);
	          };
	          for (var i = 0; i < files.length; i++) {
	            readTextFromFile(files[i], i);
	          }
	        } else {
	          // Normal drop
	          // Don't do a replace if the drop happened inside of the selected text.
	          if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
	            cm.state.draggingText(e);
	            // Ensure the editor is re-focused
	            setTimeout(function () {
	              return cm.display.input.focus();
	            }, 20);
	            return;
	          }
	          try {
	            var text$1 = e.dataTransfer.getData("Text");
	            if (text$1) {
	              var selected;
	              if (cm.state.draggingText && !cm.state.draggingText.copy) {
	                selected = cm.listSelections();
	              }
	              setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
	              if (selected) {
	                for (var i$1 = 0; i$1 < selected.length; ++i$1) {
	                  replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag");
	                }
	              }
	              cm.replaceSelection(text$1, "around", "paste");
	              cm.display.input.focus();
	            }
	          } catch (e$1) {}
	        }
	      }
	      function onDragStart(cm, e) {
	        if (ie && (!cm.state.draggingText || +new Date() - lastDrop < 100)) {
	          e_stop(e);
	          return;
	        }
	        if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) {
	          return;
	        }
	        e.dataTransfer.setData("Text", cm.getSelection());
	        e.dataTransfer.effectAllowed = "copyMove";

	        // Use dummy image instead of default browsers image.
	        // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
	        if (e.dataTransfer.setDragImage && !safari) {
	          var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
	          img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
	          if (presto) {
	            img.width = img.height = 1;
	            cm.display.wrapper.appendChild(img);
	            // Force a relayout, or Opera won't use our image for some obscure reason
	            img._top = img.offsetTop;
	          }
	          e.dataTransfer.setDragImage(img, 0, 0);
	          if (presto) {
	            img.parentNode.removeChild(img);
	          }
	        }
	      }
	      function onDragOver(cm, e) {
	        var pos = posFromMouse(cm, e);
	        if (!pos) {
	          return;
	        }
	        var frag = document.createDocumentFragment();
	        drawSelectionCursor(cm, pos, frag);
	        if (!cm.display.dragCursor) {
	          cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
	          cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
	        }
	        removeChildrenAndAdd(cm.display.dragCursor, frag);
	      }
	      function clearDragCursor(cm) {
	        if (cm.display.dragCursor) {
	          cm.display.lineSpace.removeChild(cm.display.dragCursor);
	          cm.display.dragCursor = null;
	        }
	      }

	      // These must be handled carefully, because naively registering a
	      // handler for each editor will cause the editors to never be
	      // garbage collected.

	      function forEachCodeMirror(f) {
	        if (!document.getElementsByClassName) {
	          return;
	        }
	        var byClass = document.getElementsByClassName("CodeMirror"),
	          editors = [];
	        for (var i = 0; i < byClass.length; i++) {
	          var cm = byClass[i].CodeMirror;
	          if (cm) {
	            editors.push(cm);
	          }
	        }
	        if (editors.length) {
	          editors[0].operation(function () {
	            for (var i = 0; i < editors.length; i++) {
	              f(editors[i]);
	            }
	          });
	        }
	      }
	      var globalsRegistered = false;
	      function ensureGlobalHandlers() {
	        if (globalsRegistered) {
	          return;
	        }
	        registerGlobalHandlers();
	        globalsRegistered = true;
	      }
	      function registerGlobalHandlers() {
	        // When the window resizes, we need to refresh active editors.
	        var resizeTimer;
	        on(window, "resize", function () {
	          if (resizeTimer == null) {
	            resizeTimer = setTimeout(function () {
	              resizeTimer = null;
	              forEachCodeMirror(onResize);
	            }, 100);
	          }
	        });
	        // When the window loses focus, we want to show the editor as blurred
	        on(window, "blur", function () {
	          return forEachCodeMirror(onBlur);
	        });
	      }
	      // Called when the window resizes
	      function onResize(cm) {
	        var d = cm.display;
	        // Might be a text scaling operation, clear size caches.
	        d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
	        d.scrollbarsClipped = false;
	        cm.setSize();
	      }
	      var keyNames = {
	        3: "Pause",
	        8: "Backspace",
	        9: "Tab",
	        13: "Enter",
	        16: "Shift",
	        17: "Ctrl",
	        18: "Alt",
	        19: "Pause",
	        20: "CapsLock",
	        27: "Esc",
	        32: "Space",
	        33: "PageUp",
	        34: "PageDown",
	        35: "End",
	        36: "Home",
	        37: "Left",
	        38: "Up",
	        39: "Right",
	        40: "Down",
	        44: "PrintScrn",
	        45: "Insert",
	        46: "Delete",
	        59: ";",
	        61: "=",
	        91: "Mod",
	        92: "Mod",
	        93: "Mod",
	        106: "*",
	        107: "=",
	        109: "-",
	        110: ".",
	        111: "/",
	        145: "ScrollLock",
	        173: "-",
	        186: ";",
	        187: "=",
	        188: ",",
	        189: "-",
	        190: ".",
	        191: "/",
	        192: "`",
	        219: "[",
	        220: "\\",
	        221: "]",
	        222: "'",
	        224: "Mod",
	        63232: "Up",
	        63233: "Down",
	        63234: "Left",
	        63235: "Right",
	        63272: "Delete",
	        63273: "Home",
	        63275: "End",
	        63276: "PageUp",
	        63277: "PageDown",
	        63302: "Insert"
	      };

	      // Number keys
	      for (var i = 0; i < 10; i++) {
	        keyNames[i + 48] = keyNames[i + 96] = String(i);
	      }
	      // Alphabetic keys
	      for (var i$1 = 65; i$1 <= 90; i$1++) {
	        keyNames[i$1] = String.fromCharCode(i$1);
	      }
	      // Function keys
	      for (var i$2 = 1; i$2 <= 12; i$2++) {
	        keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2;
	      }
	      var keyMap = {};
	      keyMap.basic = {
	        "Left": "goCharLeft",
	        "Right": "goCharRight",
	        "Up": "goLineUp",
	        "Down": "goLineDown",
	        "End": "goLineEnd",
	        "Home": "goLineStartSmart",
	        "PageUp": "goPageUp",
	        "PageDown": "goPageDown",
	        "Delete": "delCharAfter",
	        "Backspace": "delCharBefore",
	        "Shift-Backspace": "delCharBefore",
	        "Tab": "defaultTab",
	        "Shift-Tab": "indentAuto",
	        "Enter": "newlineAndIndent",
	        "Insert": "toggleOverwrite",
	        "Esc": "singleSelection"
	      };
	      // Note that the save and find-related commands aren't defined by
	      // default. User code or addons can define them. Unknown commands
	      // are simply ignored.
	      keyMap.pcDefault = {
	        "Ctrl-A": "selectAll",
	        "Ctrl-D": "deleteLine",
	        "Ctrl-Z": "undo",
	        "Shift-Ctrl-Z": "redo",
	        "Ctrl-Y": "redo",
	        "Ctrl-Home": "goDocStart",
	        "Ctrl-End": "goDocEnd",
	        "Ctrl-Up": "goLineUp",
	        "Ctrl-Down": "goLineDown",
	        "Ctrl-Left": "goGroupLeft",
	        "Ctrl-Right": "goGroupRight",
	        "Alt-Left": "goLineStart",
	        "Alt-Right": "goLineEnd",
	        "Ctrl-Backspace": "delGroupBefore",
	        "Ctrl-Delete": "delGroupAfter",
	        "Ctrl-S": "save",
	        "Ctrl-F": "find",
	        "Ctrl-G": "findNext",
	        "Shift-Ctrl-G": "findPrev",
	        "Shift-Ctrl-F": "replace",
	        "Shift-Ctrl-R": "replaceAll",
	        "Ctrl-[": "indentLess",
	        "Ctrl-]": "indentMore",
	        "Ctrl-U": "undoSelection",
	        "Shift-Ctrl-U": "redoSelection",
	        "Alt-U": "redoSelection",
	        "fallthrough": "basic"
	      };
	      // Very basic readline/emacs-style bindings, which are standard on Mac.
	      keyMap.emacsy = {
	        "Ctrl-F": "goCharRight",
	        "Ctrl-B": "goCharLeft",
	        "Ctrl-P": "goLineUp",
	        "Ctrl-N": "goLineDown",
	        "Ctrl-A": "goLineStart",
	        "Ctrl-E": "goLineEnd",
	        "Ctrl-V": "goPageDown",
	        "Shift-Ctrl-V": "goPageUp",
	        "Ctrl-D": "delCharAfter",
	        "Ctrl-H": "delCharBefore",
	        "Alt-Backspace": "delWordBefore",
	        "Ctrl-K": "killLine",
	        "Ctrl-T": "transposeChars",
	        "Ctrl-O": "openLine"
	      };
	      keyMap.macDefault = {
	        "Cmd-A": "selectAll",
	        "Cmd-D": "deleteLine",
	        "Cmd-Z": "undo",
	        "Shift-Cmd-Z": "redo",
	        "Cmd-Y": "redo",
	        "Cmd-Home": "goDocStart",
	        "Cmd-Up": "goDocStart",
	        "Cmd-End": "goDocEnd",
	        "Cmd-Down": "goDocEnd",
	        "Alt-Left": "goGroupLeft",
	        "Alt-Right": "goGroupRight",
	        "Cmd-Left": "goLineLeft",
	        "Cmd-Right": "goLineRight",
	        "Alt-Backspace": "delGroupBefore",
	        "Ctrl-Alt-Backspace": "delGroupAfter",
	        "Alt-Delete": "delGroupAfter",
	        "Cmd-S": "save",
	        "Cmd-F": "find",
	        "Cmd-G": "findNext",
	        "Shift-Cmd-G": "findPrev",
	        "Cmd-Alt-F": "replace",
	        "Shift-Cmd-Alt-F": "replaceAll",
	        "Cmd-[": "indentLess",
	        "Cmd-]": "indentMore",
	        "Cmd-Backspace": "delWrappedLineLeft",
	        "Cmd-Delete": "delWrappedLineRight",
	        "Cmd-U": "undoSelection",
	        "Shift-Cmd-U": "redoSelection",
	        "Ctrl-Up": "goDocStart",
	        "Ctrl-Down": "goDocEnd",
	        "fallthrough": ["basic", "emacsy"]
	      };
	      keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;

	      // KEYMAP DISPATCH

	      function normalizeKeyName(name) {
	        var parts = name.split(/-(?!$)/);
	        name = parts[parts.length - 1];
	        var alt, ctrl, shift, cmd;
	        for (var i = 0; i < parts.length - 1; i++) {
	          var mod = parts[i];
	          if (/^(cmd|meta|m)$/i.test(mod)) {
	            cmd = true;
	          } else if (/^a(lt)?$/i.test(mod)) {
	            alt = true;
	          } else if (/^(c|ctrl|control)$/i.test(mod)) {
	            ctrl = true;
	          } else if (/^s(hift)?$/i.test(mod)) {
	            shift = true;
	          } else {
	            throw new Error("Unrecognized modifier name: " + mod);
	          }
	        }
	        if (alt) {
	          name = "Alt-" + name;
	        }
	        if (ctrl) {
	          name = "Ctrl-" + name;
	        }
	        if (cmd) {
	          name = "Cmd-" + name;
	        }
	        if (shift) {
	          name = "Shift-" + name;
	        }
	        return name;
	      }

	      // This is a kludge to keep keymaps mostly working as raw objects
	      // (backwards compatibility) while at the same time support features
	      // like normalization and multi-stroke key bindings. It compiles a
	      // new normalized keymap, and then updates the old object to reflect
	      // this.
	      function normalizeKeyMap(keymap) {
	        var copy = {};
	        for (var keyname in keymap) {
	          if (keymap.hasOwnProperty(keyname)) {
	            var value = keymap[keyname];
	            if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) {
	              continue;
	            }
	            if (value == "...") {
	              delete keymap[keyname];
	              continue;
	            }
	            var keys = map(keyname.split(" "), normalizeKeyName);
	            for (var i = 0; i < keys.length; i++) {
	              var val = void 0,
	                name = void 0;
	              if (i == keys.length - 1) {
	                name = keys.join(" ");
	                val = value;
	              } else {
	                name = keys.slice(0, i + 1).join(" ");
	                val = "...";
	              }
	              var prev = copy[name];
	              if (!prev) {
	                copy[name] = val;
	              } else if (prev != val) {
	                throw new Error("Inconsistent bindings for " + name);
	              }
	            }
	            delete keymap[keyname];
	          }
	        }
	        for (var prop in copy) {
	          keymap[prop] = copy[prop];
	        }
	        return keymap;
	      }
	      function lookupKey(key, map, handle, context) {
	        map = getKeyMap(map);
	        var found = map.call ? map.call(key, context) : map[key];
	        if (found === false) {
	          return "nothing";
	        }
	        if (found === "...") {
	          return "multi";
	        }
	        if (found != null && handle(found)) {
	          return "handled";
	        }
	        if (map.fallthrough) {
	          if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") {
	            return lookupKey(key, map.fallthrough, handle, context);
	          }
	          for (var i = 0; i < map.fallthrough.length; i++) {
	            var result = lookupKey(key, map.fallthrough[i], handle, context);
	            if (result) {
	              return result;
	            }
	          }
	        }
	      }

	      // Modifier key presses don't count as 'real' key presses for the
	      // purpose of keymap fallthrough.
	      function isModifierKey(value) {
	        var name = typeof value == "string" ? value : keyNames[value.keyCode];
	        return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
	      }
	      function addModifierNames(name, event, noShift) {
	        var base = name;
	        if (event.altKey && base != "Alt") {
	          name = "Alt-" + name;
	        }
	        if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") {
	          name = "Ctrl-" + name;
	        }
	        if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") {
	          name = "Cmd-" + name;
	        }
	        if (!noShift && event.shiftKey && base != "Shift") {
	          name = "Shift-" + name;
	        }
	        return name;
	      }

	      // Look up the name of a key as indicated by an event object.
	      function keyName(event, noShift) {
	        if (presto && event.keyCode == 34 && event["char"]) {
	          return false;
	        }
	        var name = keyNames[event.keyCode];
	        if (name == null || event.altGraphKey) {
	          return false;
	        }
	        // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
	        // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
	        if (event.keyCode == 3 && event.code) {
	          name = event.code;
	        }
	        return addModifierNames(name, event, noShift);
	      }
	      function getKeyMap(val) {
	        return typeof val == "string" ? keyMap[val] : val;
	      }

	      // Helper for deleting text near the selection(s), used to implement
	      // backspace, delete, and similar functionality.
	      function deleteNearSelection(cm, compute) {
	        var ranges = cm.doc.sel.ranges,
	          kill = [];
	        // Build up a set of ranges to kill first, merging overlapping
	        // ranges.
	        for (var i = 0; i < ranges.length; i++) {
	          var toKill = compute(ranges[i]);
	          while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
	            var replaced = kill.pop();
	            if (cmp(replaced.from, toKill.from) < 0) {
	              toKill.from = replaced.from;
	              break;
	            }
	          }
	          kill.push(toKill);
	        }
	        // Next, remove those actual ranges.
	        runInOp(cm, function () {
	          for (var i = kill.length - 1; i >= 0; i--) {
	            replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
	          }
	          ensureCursorVisible(cm);
	        });
	      }
	      function moveCharLogically(line, ch, dir) {
	        var target = skipExtendingChars(line.text, ch + dir, dir);
	        return target < 0 || target > line.text.length ? null : target;
	      }
	      function moveLogically(line, start, dir) {
	        var ch = moveCharLogically(line, start.ch, dir);
	        return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before");
	      }
	      function endOfLine(visually, cm, lineObj, lineNo, dir) {
	        if (visually) {
	          if (cm.doc.direction == "rtl") {
	            dir = -dir;
	          }
	          var order = getOrder(lineObj, cm.doc.direction);
	          if (order) {
	            var part = dir < 0 ? lst(order) : order[0];
	            var moveInStorageOrder = dir < 0 == (part.level == 1);
	            var sticky = moveInStorageOrder ? "after" : "before";
	            var ch;
	            // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
	            // it could be that the last bidi part is not on the last visual line,
	            // since visual lines contain content order-consecutive chunks.
	            // Thus, in rtl, we are looking for the first (content-order) character
	            // in the rtl chunk that is on the last line (that is, the same line
	            // as the last (content-order) character).
	            if (part.level > 0 || cm.doc.direction == "rtl") {
	              var prep = prepareMeasureForLine(cm, lineObj);
	              ch = dir < 0 ? lineObj.text.length - 1 : 0;
	              var targetTop = measureCharPrepared(cm, prep, ch).top;
	              ch = findFirst(function (ch) {
	                return measureCharPrepared(cm, prep, ch).top == targetTop;
	              }, dir < 0 == (part.level == 1) ? part.from : part.to - 1, ch);
	              if (sticky == "before") {
	                ch = moveCharLogically(lineObj, ch, 1);
	              }
	            } else {
	              ch = dir < 0 ? part.to : part.from;
	            }
	            return new Pos(lineNo, ch, sticky);
	          }
	        }
	        return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after");
	      }
	      function moveVisually(cm, line, start, dir) {
	        var bidi = getOrder(line, cm.doc.direction);
	        if (!bidi) {
	          return moveLogically(line, start, dir);
	        }
	        if (start.ch >= line.text.length) {
	          start.ch = line.text.length;
	          start.sticky = "before";
	        } else if (start.ch <= 0) {
	          start.ch = 0;
	          start.sticky = "after";
	        }
	        var partPos = getBidiPartAt(bidi, start.ch, start.sticky),
	          part = bidi[partPos];
	        if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
	          // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
	          // nothing interesting happens.
	          return moveLogically(line, start, dir);
	        }
	        var mv = function (pos, dir) {
	          return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir);
	        };
	        var prep;
	        var getWrappedLineExtent = function (ch) {
	          if (!cm.options.lineWrapping) {
	            return {
	              begin: 0,
	              end: line.text.length
	            };
	          }
	          prep = prep || prepareMeasureForLine(cm, line);
	          return wrappedLineExtentChar(cm, line, prep, ch);
	        };
	        var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
	        if (cm.doc.direction == "rtl" || part.level == 1) {
	          var moveInStorageOrder = part.level == 1 == dir < 0;
	          var ch = mv(start, moveInStorageOrder ? 1 : -1);
	          if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
	            // Case 2: We move within an rtl part or in an rtl editor on the same visual line
	            var sticky = moveInStorageOrder ? "before" : "after";
	            return new Pos(start.line, ch, sticky);
	          }
	        }

	        // Case 3: Could not move within this bidi part in this visual line, so leave
	        // the current bidi part

	        var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
	          var getRes = function (ch, moveInStorageOrder) {
	            return moveInStorageOrder ? new Pos(start.line, mv(ch, 1), "before") : new Pos(start.line, ch, "after");
	          };
	          for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
	            var part = bidi[partPos];
	            var moveInStorageOrder = dir > 0 == (part.level != 1);
	            var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
	            if (part.from <= ch && ch < part.to) {
	              return getRes(ch, moveInStorageOrder);
	            }
	            ch = moveInStorageOrder ? part.from : mv(part.to, -1);
	            if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) {
	              return getRes(ch, moveInStorageOrder);
	            }
	          }
	        };

	        // Case 3a: Look for other bidi parts on the same visual line
	        var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
	        if (res) {
	          return res;
	        }

	        // Case 3b: Look for other bidi parts on the next visual line
	        var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
	        if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
	          res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
	          if (res) {
	            return res;
	          }
	        }

	        // Case 4: Nowhere to move
	        return null;
	      }

	      // Commands are parameter-less actions that can be performed on an
	      // editor, mostly used for keybindings.
	      var commands = {
	        selectAll: selectAll,
	        singleSelection: function (cm) {
	          return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
	        },
	        killLine: function (cm) {
	          return deleteNearSelection(cm, function (range) {
	            if (range.empty()) {
	              var len = getLine(cm.doc, range.head.line).text.length;
	              if (range.head.ch == len && range.head.line < cm.lastLine()) {
	                return {
	                  from: range.head,
	                  to: Pos(range.head.line + 1, 0)
	                };
	              } else {
	                return {
	                  from: range.head,
	                  to: Pos(range.head.line, len)
	                };
	              }
	            } else {
	              return {
	                from: range.from(),
	                to: range.to()
	              };
	            }
	          });
	        },
	        deleteLine: function (cm) {
	          return deleteNearSelection(cm, function (range) {
	            return {
	              from: Pos(range.from().line, 0),
	              to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
	            };
	          });
	        },
	        delLineLeft: function (cm) {
	          return deleteNearSelection(cm, function (range) {
	            return {
	              from: Pos(range.from().line, 0),
	              to: range.from()
	            };
	          });
	        },
	        delWrappedLineLeft: function (cm) {
	          return deleteNearSelection(cm, function (range) {
	            var top = cm.charCoords(range.head, "div").top + 5;
	            var leftPos = cm.coordsChar({
	              left: 0,
	              top: top
	            }, "div");
	            return {
	              from: leftPos,
	              to: range.from()
	            };
	          });
	        },
	        delWrappedLineRight: function (cm) {
	          return deleteNearSelection(cm, function (range) {
	            var top = cm.charCoords(range.head, "div").top + 5;
	            var rightPos = cm.coordsChar({
	              left: cm.display.lineDiv.offsetWidth + 100,
	              top: top
	            }, "div");
	            return {
	              from: range.from(),
	              to: rightPos
	            };
	          });
	        },
	        undo: function (cm) {
	          return cm.undo();
	        },
	        redo: function (cm) {
	          return cm.redo();
	        },
	        undoSelection: function (cm) {
	          return cm.undoSelection();
	        },
	        redoSelection: function (cm) {
	          return cm.redoSelection();
	        },
	        goDocStart: function (cm) {
	          return cm.extendSelection(Pos(cm.firstLine(), 0));
	        },
	        goDocEnd: function (cm) {
	          return cm.extendSelection(Pos(cm.lastLine()));
	        },
	        goLineStart: function (cm) {
	          return cm.extendSelectionsBy(function (range) {
	            return lineStart(cm, range.head.line);
	          }, {
	            origin: "+move",
	            bias: 1
	          });
	        },
	        goLineStartSmart: function (cm) {
	          return cm.extendSelectionsBy(function (range) {
	            return lineStartSmart(cm, range.head);
	          }, {
	            origin: "+move",
	            bias: 1
	          });
	        },
	        goLineEnd: function (cm) {
	          return cm.extendSelectionsBy(function (range) {
	            return lineEnd(cm, range.head.line);
	          }, {
	            origin: "+move",
	            bias: -1
	          });
	        },
	        goLineRight: function (cm) {
	          return cm.extendSelectionsBy(function (range) {
	            var top = cm.cursorCoords(range.head, "div").top + 5;
	            return cm.coordsChar({
	              left: cm.display.lineDiv.offsetWidth + 100,
	              top: top
	            }, "div");
	          }, sel_move);
	        },
	        goLineLeft: function (cm) {
	          return cm.extendSelectionsBy(function (range) {
	            var top = cm.cursorCoords(range.head, "div").top + 5;
	            return cm.coordsChar({
	              left: 0,
	              top: top
	            }, "div");
	          }, sel_move);
	        },
	        goLineLeftSmart: function (cm) {
	          return cm.extendSelectionsBy(function (range) {
	            var top = cm.cursorCoords(range.head, "div").top + 5;
	            var pos = cm.coordsChar({
	              left: 0,
	              top: top
	            }, "div");
	            if (pos.ch < cm.getLine(pos.line).search(/\S/)) {
	              return lineStartSmart(cm, range.head);
	            }
	            return pos;
	          }, sel_move);
	        },
	        goLineUp: function (cm) {
	          return cm.moveV(-1, "line");
	        },
	        goLineDown: function (cm) {
	          return cm.moveV(1, "line");
	        },
	        goPageUp: function (cm) {
	          return cm.moveV(-1, "page");
	        },
	        goPageDown: function (cm) {
	          return cm.moveV(1, "page");
	        },
	        goCharLeft: function (cm) {
	          return cm.moveH(-1, "char");
	        },
	        goCharRight: function (cm) {
	          return cm.moveH(1, "char");
	        },
	        goColumnLeft: function (cm) {
	          return cm.moveH(-1, "column");
	        },
	        goColumnRight: function (cm) {
	          return cm.moveH(1, "column");
	        },
	        goWordLeft: function (cm) {
	          return cm.moveH(-1, "word");
	        },
	        goGroupRight: function (cm) {
	          return cm.moveH(1, "group");
	        },
	        goGroupLeft: function (cm) {
	          return cm.moveH(-1, "group");
	        },
	        goWordRight: function (cm) {
	          return cm.moveH(1, "word");
	        },
	        delCharBefore: function (cm) {
	          return cm.deleteH(-1, "codepoint");
	        },
	        delCharAfter: function (cm) {
	          return cm.deleteH(1, "char");
	        },
	        delWordBefore: function (cm) {
	          return cm.deleteH(-1, "word");
	        },
	        delWordAfter: function (cm) {
	          return cm.deleteH(1, "word");
	        },
	        delGroupBefore: function (cm) {
	          return cm.deleteH(-1, "group");
	        },
	        delGroupAfter: function (cm) {
	          return cm.deleteH(1, "group");
	        },
	        indentAuto: function (cm) {
	          return cm.indentSelection("smart");
	        },
	        indentMore: function (cm) {
	          return cm.indentSelection("add");
	        },
	        indentLess: function (cm) {
	          return cm.indentSelection("subtract");
	        },
	        insertTab: function (cm) {
	          return cm.replaceSelection("\t");
	        },
	        insertSoftTab: function (cm) {
	          var spaces = [],
	            ranges = cm.listSelections(),
	            tabSize = cm.options.tabSize;
	          for (var i = 0; i < ranges.length; i++) {
	            var pos = ranges[i].from();
	            var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
	            spaces.push(spaceStr(tabSize - col % tabSize));
	          }
	          cm.replaceSelections(spaces);
	        },
	        defaultTab: function (cm) {
	          if (cm.somethingSelected()) {
	            cm.indentSelection("add");
	          } else {
	            cm.execCommand("insertTab");
	          }
	        },
	        // Swap the two chars left and right of each selection's head.
	        // Move cursor behind the two swapped characters afterwards.
	        //
	        // Doesn't consider line feeds a character.
	        // Doesn't scan more than one line above to find a character.
	        // Doesn't do anything on an empty line.
	        // Doesn't do anything with non-empty selections.
	        transposeChars: function (cm) {
	          return runInOp(cm, function () {
	            var ranges = cm.listSelections(),
	              newSel = [];
	            for (var i = 0; i < ranges.length; i++) {
	              if (!ranges[i].empty()) {
	                continue;
	              }
	              var cur = ranges[i].head,
	                line = getLine(cm.doc, cur.line).text;
	              if (line) {
	                if (cur.ch == line.length) {
	                  cur = new Pos(cur.line, cur.ch - 1);
	                }
	                if (cur.ch > 0) {
	                  cur = new Pos(cur.line, cur.ch + 1);
	                  cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), Pos(cur.line, cur.ch - 2), cur, "+transpose");
	                } else if (cur.line > cm.doc.first) {
	                  var prev = getLine(cm.doc, cur.line - 1).text;
	                  if (prev) {
	                    cur = new Pos(cur.line, 1);
	                    cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + prev.charAt(prev.length - 1), Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
	                  }
	                }
	              }
	              newSel.push(new Range(cur, cur));
	            }
	            cm.setSelections(newSel);
	          });
	        },
	        newlineAndIndent: function (cm) {
	          return runInOp(cm, function () {
	            var sels = cm.listSelections();
	            for (var i = sels.length - 1; i >= 0; i--) {
	              cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input");
	            }
	            sels = cm.listSelections();
	            for (var i$1 = 0; i$1 < sels.length; i$1++) {
	              cm.indentLine(sels[i$1].from().line, null, true);
	            }
	            ensureCursorVisible(cm);
	          });
	        },
	        openLine: function (cm) {
	          return cm.replaceSelection("\n", "start");
	        },
	        toggleOverwrite: function (cm) {
	          return cm.toggleOverwrite();
	        }
	      };
	      function lineStart(cm, lineN) {
	        var line = getLine(cm.doc, lineN);
	        var visual = visualLine(line);
	        if (visual != line) {
	          lineN = lineNo(visual);
	        }
	        return endOfLine(true, cm, visual, lineN, 1);
	      }
	      function lineEnd(cm, lineN) {
	        var line = getLine(cm.doc, lineN);
	        var visual = visualLineEnd(line);
	        if (visual != line) {
	          lineN = lineNo(visual);
	        }
	        return endOfLine(true, cm, line, lineN, -1);
	      }
	      function lineStartSmart(cm, pos) {
	        var start = lineStart(cm, pos.line);
	        var line = getLine(cm.doc, start.line);
	        var order = getOrder(line, cm.doc.direction);
	        if (!order || order[0].level == 0) {
	          var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
	          var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
	          return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky);
	        }
	        return start;
	      }

	      // Run a handler that was bound to a key.
	      function doHandleBinding(cm, bound, dropShift) {
	        if (typeof bound == "string") {
	          bound = commands[bound];
	          if (!bound) {
	            return false;
	          }
	        }
	        // Ensure previous input has been read, so that the handler sees a
	        // consistent view of the document
	        cm.display.input.ensurePolled();
	        var prevShift = cm.display.shift,
	          done = false;
	        try {
	          if (cm.isReadOnly()) {
	            cm.state.suppressEdits = true;
	          }
	          if (dropShift) {
	            cm.display.shift = false;
	          }
	          done = bound(cm) != Pass;
	        } finally {
	          cm.display.shift = prevShift;
	          cm.state.suppressEdits = false;
	        }
	        return done;
	      }
	      function lookupKeyForEditor(cm, name, handle) {
	        for (var i = 0; i < cm.state.keyMaps.length; i++) {
	          var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
	          if (result) {
	            return result;
	          }
	        }
	        return cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm) || lookupKey(name, cm.options.keyMap, handle, cm);
	      }

	      // Note that, despite the name, this function is also used to check
	      // for bound mouse clicks.

	      var stopSeq = new Delayed();
	      function dispatchKey(cm, name, e, handle) {
	        var seq = cm.state.keySeq;
	        if (seq) {
	          if (isModifierKey(name)) {
	            return "handled";
	          }
	          if (/\'$/.test(name)) {
	            cm.state.keySeq = null;
	          } else {
	            stopSeq.set(50, function () {
	              if (cm.state.keySeq == seq) {
	                cm.state.keySeq = null;
	                cm.display.input.reset();
	              }
	            });
	          }
	          if (dispatchKeyInner(cm, seq + " " + name, e, handle)) {
	            return true;
	          }
	        }
	        return dispatchKeyInner(cm, name, e, handle);
	      }
	      function dispatchKeyInner(cm, name, e, handle) {
	        var result = lookupKeyForEditor(cm, name, handle);
	        if (result == "multi") {
	          cm.state.keySeq = name;
	        }
	        if (result == "handled") {
	          signalLater(cm, "keyHandled", cm, name, e);
	        }
	        if (result == "handled" || result == "multi") {
	          e_preventDefault(e);
	          restartBlink(cm);
	        }
	        return !!result;
	      }

	      // Handle a key from the keydown event.
	      function handleKeyBinding(cm, e) {
	        var name = keyName(e, true);
	        if (!name) {
	          return false;
	        }
	        if (e.shiftKey && !cm.state.keySeq) {
	          // First try to resolve full name (including 'Shift-'). Failing
	          // that, see if there is a cursor-motion command (starting with
	          // 'go') bound to the keyname without 'Shift-'.
	          return dispatchKey(cm, "Shift-" + name, e, function (b) {
	            return doHandleBinding(cm, b, true);
	          }) || dispatchKey(cm, name, e, function (b) {
	            if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) {
	              return doHandleBinding(cm, b);
	            }
	          });
	        } else {
	          return dispatchKey(cm, name, e, function (b) {
	            return doHandleBinding(cm, b);
	          });
	        }
	      }

	      // Handle a key from the keypress event
	      function handleCharBinding(cm, e, ch) {
	        return dispatchKey(cm, "'" + ch + "'", e, function (b) {
	          return doHandleBinding(cm, b, true);
	        });
	      }
	      var lastStoppedKey = null;
	      function onKeyDown(e) {
	        var cm = this;
	        if (e.target && e.target != cm.display.input.getField()) {
	          return;
	        }
	        cm.curOp.focus = activeElt(root(cm));
	        if (signalDOMEvent(cm, e)) {
	          return;
	        }
	        // IE does strange things with escape.
	        if (ie && ie_version < 11 && e.keyCode == 27) {
	          e.returnValue = false;
	        }
	        var code = e.keyCode;
	        cm.display.shift = code == 16 || e.shiftKey;
	        var handled = handleKeyBinding(cm, e);
	        if (presto) {
	          lastStoppedKey = handled ? code : null;
	          // Opera has no cut event... we try to at least catch the key combo
	          if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) {
	            cm.replaceSelection("", null, "cut");
	          }
	        }
	        if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand) {
	          document.execCommand("cut");
	        }

	        // Turn mouse into crosshair when Alt is held on Mac.
	        if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) {
	          showCrossHair(cm);
	        }
	      }
	      function showCrossHair(cm) {
	        var lineDiv = cm.display.lineDiv;
	        addClass(lineDiv, "CodeMirror-crosshair");
	        function up(e) {
	          if (e.keyCode == 18 || !e.altKey) {
	            rmClass(lineDiv, "CodeMirror-crosshair");
	            off(document, "keyup", up);
	            off(document, "mouseover", up);
	          }
	        }
	        on(document, "keyup", up);
	        on(document, "mouseover", up);
	      }
	      function onKeyUp(e) {
	        if (e.keyCode == 16) {
	          this.doc.sel.shift = false;
	        }
	        signalDOMEvent(this, e);
	      }
	      function onKeyPress(e) {
	        var cm = this;
	        if (e.target && e.target != cm.display.input.getField()) {
	          return;
	        }
	        if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) {
	          return;
	        }
	        var keyCode = e.keyCode,
	          charCode = e.charCode;
	        if (presto && keyCode == lastStoppedKey) {
	          lastStoppedKey = null;
	          e_preventDefault(e);
	          return;
	        }
	        if (presto && (!e.which || e.which < 10) && handleKeyBinding(cm, e)) {
	          return;
	        }
	        var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
	        // Some browsers fire keypress events for backspace
	        if (ch == "\x08") {
	          return;
	        }
	        if (handleCharBinding(cm, e, ch)) {
	          return;
	        }
	        cm.display.input.onKeyPress(e);
	      }
	      var DOUBLECLICK_DELAY = 400;
	      var PastClick = function (time, pos, button) {
	        this.time = time;
	        this.pos = pos;
	        this.button = button;
	      };
	      PastClick.prototype.compare = function (time, pos, button) {
	        return this.time + DOUBLECLICK_DELAY > time && cmp(pos, this.pos) == 0 && button == this.button;
	      };
	      var lastClick, lastDoubleClick;
	      function clickRepeat(pos, button) {
	        var now = +new Date();
	        if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
	          lastClick = lastDoubleClick = null;
	          return "triple";
	        } else if (lastClick && lastClick.compare(now, pos, button)) {
	          lastDoubleClick = new PastClick(now, pos, button);
	          lastClick = null;
	          return "double";
	        } else {
	          lastClick = new PastClick(now, pos, button);
	          lastDoubleClick = null;
	          return "single";
	        }
	      }

	      // A mouse down can be a single click, double click, triple click,
	      // start of selection drag, start of text drag, new cursor
	      // (ctrl-click), rectangle drag (alt-drag), or xwin
	      // middle-click-paste. Or it might be a click on something we should
	      // not interfere with, such as a scrollbar or widget.
	      function onMouseDown(e) {
	        var cm = this,
	          display = cm.display;
	        if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) {
	          return;
	        }
	        display.input.ensurePolled();
	        display.shift = e.shiftKey;
	        if (eventInWidget(display, e)) {
	          if (!webkit) {
	            // Briefly turn off draggability, to allow widgets to do
	            // normal dragging things.
	            display.scroller.draggable = false;
	            setTimeout(function () {
	              return display.scroller.draggable = true;
	            }, 100);
	          }
	          return;
	        }
	        if (clickInGutter(cm, e)) {
	          return;
	        }
	        var pos = posFromMouse(cm, e),
	          button = e_button(e),
	          repeat = pos ? clickRepeat(pos, button) : "single";
	        win(cm).focus();

	        // #3261: make sure, that we're not starting a second selection
	        if (button == 1 && cm.state.selectingText) {
	          cm.state.selectingText(e);
	        }
	        if (pos && handleMappedButton(cm, button, pos, repeat, e)) {
	          return;
	        }
	        if (button == 1) {
	          if (pos) {
	            leftButtonDown(cm, pos, repeat, e);
	          } else if (e_target(e) == display.scroller) {
	            e_preventDefault(e);
	          }
	        } else if (button == 2) {
	          if (pos) {
	            extendSelection(cm.doc, pos);
	          }
	          setTimeout(function () {
	            return display.input.focus();
	          }, 20);
	        } else if (button == 3) {
	          if (captureRightClick) {
	            cm.display.input.onContextMenu(e);
	          } else {
	            delayBlurEvent(cm);
	          }
	        }
	      }
	      function handleMappedButton(cm, button, pos, repeat, event) {
	        var name = "Click";
	        if (repeat == "double") {
	          name = "Double" + name;
	        } else if (repeat == "triple") {
	          name = "Triple" + name;
	        }
	        name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
	        return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
	          if (typeof bound == "string") {
	            bound = commands[bound];
	          }
	          if (!bound) {
	            return false;
	          }
	          var done = false;
	          try {
	            if (cm.isReadOnly()) {
	              cm.state.suppressEdits = true;
	            }
	            done = bound(cm, pos) != Pass;
	          } finally {
	            cm.state.suppressEdits = false;
	          }
	          return done;
	        });
	      }
	      function configureMouse(cm, repeat, event) {
	        var option = cm.getOption("configureMouse");
	        var value = option ? option(cm, repeat, event) : {};
	        if (value.unit == null) {
	          var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
	          value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
	        }
	        if (value.extend == null || cm.doc.extend) {
	          value.extend = cm.doc.extend || event.shiftKey;
	        }
	        if (value.addNew == null) {
	          value.addNew = mac ? event.metaKey : event.ctrlKey;
	        }
	        if (value.moveOnDrag == null) {
	          value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey);
	        }
	        return value;
	      }
	      function leftButtonDown(cm, pos, repeat, event) {
	        if (ie) {
	          setTimeout(bind(ensureFocus, cm), 0);
	        } else {
	          cm.curOp.focus = activeElt(root(cm));
	        }
	        var behavior = configureMouse(cm, repeat, event);
	        var sel = cm.doc.sel,
	          contained;
	        if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && repeat == "single" && (contained = sel.contains(pos)) > -1 && (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) {
	          leftButtonStartDrag(cm, event, pos, behavior);
	        } else {
	          leftButtonSelect(cm, event, pos, behavior);
	        }
	      }

	      // Start a text drag. When it ends, see if any dragging actually
	      // happen, and treat as a click if it didn't.
	      function leftButtonStartDrag(cm, event, pos, behavior) {
	        var display = cm.display,
	          moved = false;
	        var dragEnd = operation(cm, function (e) {
	          if (webkit) {
	            display.scroller.draggable = false;
	          }
	          cm.state.draggingText = false;
	          if (cm.state.delayingBlurEvent) {
	            if (cm.hasFocus()) {
	              cm.state.delayingBlurEvent = false;
	            } else {
	              delayBlurEvent(cm);
	            }
	          }
	          off(display.wrapper.ownerDocument, "mouseup", dragEnd);
	          off(display.wrapper.ownerDocument, "mousemove", mouseMove);
	          off(display.scroller, "dragstart", dragStart);
	          off(display.scroller, "drop", dragEnd);
	          if (!moved) {
	            e_preventDefault(e);
	            if (!behavior.addNew) {
	              extendSelection(cm.doc, pos, null, null, behavior.extend);
	            }
	            // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
	            if (webkit && !safari || ie && ie_version == 9) {
	              setTimeout(function () {
	                display.wrapper.ownerDocument.body.focus({
	                  preventScroll: true
	                });
	                display.input.focus();
	              }, 20);
	            } else {
	              display.input.focus();
	            }
	          }
	        });
	        var mouseMove = function (e2) {
	          moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
	        };
	        var dragStart = function () {
	          return moved = true;
	        };
	        // Let the drag handler handle this.
	        if (webkit) {
	          display.scroller.draggable = true;
	        }
	        cm.state.draggingText = dragEnd;
	        dragEnd.copy = !behavior.moveOnDrag;
	        on(display.wrapper.ownerDocument, "mouseup", dragEnd);
	        on(display.wrapper.ownerDocument, "mousemove", mouseMove);
	        on(display.scroller, "dragstart", dragStart);
	        on(display.scroller, "drop", dragEnd);
	        cm.state.delayingBlurEvent = true;
	        setTimeout(function () {
	          return display.input.focus();
	        }, 20);
	        // IE's approach to draggable
	        if (display.scroller.dragDrop) {
	          display.scroller.dragDrop();
	        }
	      }
	      function rangeForUnit(cm, pos, unit) {
	        if (unit == "char") {
	          return new Range(pos, pos);
	        }
	        if (unit == "word") {
	          return cm.findWordAt(pos);
	        }
	        if (unit == "line") {
	          return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
	        }
	        var result = unit(cm, pos);
	        return new Range(result.from, result.to);
	      }

	      // Normal selection, as opposed to text dragging.
	      function leftButtonSelect(cm, event, start, behavior) {
	        if (ie) {
	          delayBlurEvent(cm);
	        }
	        var display = cm.display,
	          doc = cm.doc;
	        e_preventDefault(event);
	        var ourRange,
	          ourIndex,
	          startSel = doc.sel,
	          ranges = startSel.ranges;
	        if (behavior.addNew && !behavior.extend) {
	          ourIndex = doc.sel.contains(start);
	          if (ourIndex > -1) {
	            ourRange = ranges[ourIndex];
	          } else {
	            ourRange = new Range(start, start);
	          }
	        } else {
	          ourRange = doc.sel.primary();
	          ourIndex = doc.sel.primIndex;
	        }
	        if (behavior.unit == "rectangle") {
	          if (!behavior.addNew) {
	            ourRange = new Range(start, start);
	          }
	          start = posFromMouse(cm, event, true, true);
	          ourIndex = -1;
	        } else {
	          var range = rangeForUnit(cm, start, behavior.unit);
	          if (behavior.extend) {
	            ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend);
	          } else {
	            ourRange = range;
	          }
	        }
	        if (!behavior.addNew) {
	          ourIndex = 0;
	          setSelection(doc, new Selection([ourRange], 0), sel_mouse);
	          startSel = doc.sel;
	        } else if (ourIndex == -1) {
	          ourIndex = ranges.length;
	          setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), {
	            scroll: false,
	            origin: "*mouse"
	          });
	        } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
	          setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), {
	            scroll: false,
	            origin: "*mouse"
	          });
	          startSel = doc.sel;
	        } else {
	          replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
	        }
	        var lastPos = start;
	        function extendTo(pos) {
	          if (cmp(lastPos, pos) == 0) {
	            return;
	          }
	          lastPos = pos;
	          if (behavior.unit == "rectangle") {
	            var ranges = [],
	              tabSize = cm.options.tabSize;
	            var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
	            var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
	            var left = Math.min(startCol, posCol),
	              right = Math.max(startCol, posCol);
	            for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); line <= end; line++) {
	              var text = getLine(doc, line).text,
	                leftPos = findColumn(text, left, tabSize);
	              if (left == right) {
	                ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
	              } else if (text.length > leftPos) {
	                ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
	              }
	            }
	            if (!ranges.length) {
	              ranges.push(new Range(start, start));
	            }
	            setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), {
	              origin: "*mouse",
	              scroll: false
	            });
	            cm.scrollIntoView(pos);
	          } else {
	            var oldRange = ourRange;
	            var range = rangeForUnit(cm, pos, behavior.unit);
	            var anchor = oldRange.anchor,
	              head;
	            if (cmp(range.anchor, anchor) > 0) {
	              head = range.head;
	              anchor = minPos(oldRange.from(), range.anchor);
	            } else {
	              head = range.anchor;
	              anchor = maxPos(oldRange.to(), range.head);
	            }
	            var ranges$1 = startSel.ranges.slice(0);
	            ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
	            setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
	          }
	        }
	        var editorSize = display.wrapper.getBoundingClientRect();
	        // Used to ensure timeout re-tries don't fire when another extend
	        // happened in the meantime (clearTimeout isn't reliable -- at
	        // least on Chrome, the timeouts still happen even when cleared,
	        // if the clear happens after their scheduled firing time).
	        var counter = 0;
	        function extend(e) {
	          var curCount = ++counter;
	          var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
	          if (!cur) {
	            return;
	          }
	          if (cmp(cur, lastPos) != 0) {
	            cm.curOp.focus = activeElt(root(cm));
	            extendTo(cur);
	            var visible = visibleLines(display, doc);
	            if (cur.line >= visible.to || cur.line < visible.from) {
	              setTimeout(operation(cm, function () {
	                if (counter == curCount) {
	                  extend(e);
	                }
	              }), 150);
	            }
	          } else {
	            var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
	            if (outside) {
	              setTimeout(operation(cm, function () {
	                if (counter != curCount) {
	                  return;
	                }
	                display.scroller.scrollTop += outside;
	                extend(e);
	              }), 50);
	            }
	          }
	        }
	        function done(e) {
	          cm.state.selectingText = false;
	          counter = Infinity;
	          // If e is null or undefined we interpret this as someone trying
	          // to explicitly cancel the selection rather than the user
	          // letting go of the mouse button.
	          if (e) {
	            e_preventDefault(e);
	            display.input.focus();
	          }
	          off(display.wrapper.ownerDocument, "mousemove", move);
	          off(display.wrapper.ownerDocument, "mouseup", up);
	          doc.history.lastSelOrigin = null;
	        }
	        var move = operation(cm, function (e) {
	          if (e.buttons === 0 || !e_button(e)) {
	            done(e);
	          } else {
	            extend(e);
	          }
	        });
	        var up = operation(cm, done);
	        cm.state.selectingText = up;
	        on(display.wrapper.ownerDocument, "mousemove", move);
	        on(display.wrapper.ownerDocument, "mouseup", up);
	      }

	      // Used when mouse-selecting to adjust the anchor to the proper side
	      // of a bidi jump depending on the visual position of the head.
	      function bidiSimplify(cm, range) {
	        var anchor = range.anchor;
	        var head = range.head;
	        var anchorLine = getLine(cm.doc, anchor.line);
	        if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) {
	          return range;
	        }
	        var order = getOrder(anchorLine);
	        if (!order) {
	          return range;
	        }
	        var index = getBidiPartAt(order, anchor.ch, anchor.sticky),
	          part = order[index];
	        if (part.from != anchor.ch && part.to != anchor.ch) {
	          return range;
	        }
	        var boundary = index + (part.from == anchor.ch == (part.level != 1) ? 0 : 1);
	        if (boundary == 0 || boundary == order.length) {
	          return range;
	        }

	        // Compute the relative visual position of the head compared to the
	        // anchor (<0 is to the left, >0 to the right)
	        var leftSide;
	        if (head.line != anchor.line) {
	          leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
	        } else {
	          var headIndex = getBidiPartAt(order, head.ch, head.sticky);
	          var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
	          if (headIndex == boundary - 1 || headIndex == boundary) {
	            leftSide = dir < 0;
	          } else {
	            leftSide = dir > 0;
	          }
	        }
	        var usePart = order[boundary + (leftSide ? -1 : 0)];
	        var from = leftSide == (usePart.level == 1);
	        var ch = from ? usePart.from : usePart.to,
	          sticky = from ? "after" : "before";
	        return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head);
	      }

	      // Determines whether an event happened in the gutter, and fires the
	      // handlers for the corresponding event.
	      function gutterEvent(cm, e, type, prevent) {
	        var mX, mY;
	        if (e.touches) {
	          mX = e.touches[0].clientX;
	          mY = e.touches[0].clientY;
	        } else {
	          try {
	            mX = e.clientX;
	            mY = e.clientY;
	          } catch (e$1) {
	            return false;
	          }
	        }
	        if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) {
	          return false;
	        }
	        if (prevent) {
	          e_preventDefault(e);
	        }
	        var display = cm.display;
	        var lineBox = display.lineDiv.getBoundingClientRect();
	        if (mY > lineBox.bottom || !hasHandler(cm, type)) {
	          return e_defaultPrevented(e);
	        }
	        mY -= lineBox.top - display.viewOffset;
	        for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
	          var g = display.gutters.childNodes[i];
	          if (g && g.getBoundingClientRect().right >= mX) {
	            var line = lineAtHeight(cm.doc, mY);
	            var gutter = cm.display.gutterSpecs[i];
	            signal(cm, type, cm, line, gutter.className, e);
	            return e_defaultPrevented(e);
	          }
	        }
	      }
	      function clickInGutter(cm, e) {
	        return gutterEvent(cm, e, "gutterClick", true);
	      }

	      // CONTEXT MENU HANDLING

	      // To make the context menu work, we need to briefly unhide the
	      // textarea (making it as unobtrusive as possible) to let the
	      // right-click take effect on it.
	      function onContextMenu(cm, e) {
	        if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) {
	          return;
	        }
	        if (signalDOMEvent(cm, e, "contextmenu")) {
	          return;
	        }
	        if (!captureRightClick) {
	          cm.display.input.onContextMenu(e);
	        }
	      }
	      function contextMenuInGutter(cm, e) {
	        if (!hasHandler(cm, "gutterContextMenu")) {
	          return false;
	        }
	        return gutterEvent(cm, e, "gutterContextMenu", false);
	      }
	      function themeChanged(cm) {
	        cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
	        clearCaches(cm);
	      }
	      var Init = {
	        toString: function () {
	          return "CodeMirror.Init";
	        }
	      };
	      var defaults = {};
	      var optionHandlers = {};
	      function defineOptions(CodeMirror) {
	        var optionHandlers = CodeMirror.optionHandlers;
	        function option(name, deflt, handle, notOnInit) {
	          CodeMirror.defaults[name] = deflt;
	          if (handle) {
	            optionHandlers[name] = notOnInit ? function (cm, val, old) {
	              if (old != Init) {
	                handle(cm, val, old);
	              }
	            } : handle;
	          }
	        }
	        CodeMirror.defineOption = option;

	        // Passed to option handlers when there is no old value.
	        CodeMirror.Init = Init;

	        // These two are, on init, called from the constructor because they
	        // have to be initialized before the editor can start at all.
	        option("value", "", function (cm, val) {
	          return cm.setValue(val);
	        }, true);
	        option("mode", null, function (cm, val) {
	          cm.doc.modeOption = val;
	          loadMode(cm);
	        }, true);
	        option("indentUnit", 2, loadMode, true);
	        option("indentWithTabs", false);
	        option("smartIndent", true);
	        option("tabSize", 4, function (cm) {
	          resetModeState(cm);
	          clearCaches(cm);
	          regChange(cm);
	        }, true);
	        option("lineSeparator", null, function (cm, val) {
	          cm.doc.lineSep = val;
	          if (!val) {
	            return;
	          }
	          var newBreaks = [],
	            lineNo = cm.doc.first;
	          cm.doc.iter(function (line) {
	            for (var pos = 0;;) {
	              var found = line.text.indexOf(val, pos);
	              if (found == -1) {
	                break;
	              }
	              pos = found + val.length;
	              newBreaks.push(Pos(lineNo, found));
	            }
	            lineNo++;
	          });
	          for (var i = newBreaks.length - 1; i >= 0; i--) {
	            replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length));
	          }
	        });
	        option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\u202d\u202e\u2066\u2067\u2069\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
	          cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
	          if (old != Init) {
	            cm.refresh();
	          }
	        });
	        option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) {
	          return cm.refresh();
	        }, true);
	        option("electricChars", true);
	        option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
	          throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
	        }, true);
	        option("spellcheck", false, function (cm, val) {
	          return cm.getInputField().spellcheck = val;
	        }, true);
	        option("autocorrect", false, function (cm, val) {
	          return cm.getInputField().autocorrect = val;
	        }, true);
	        option("autocapitalize", false, function (cm, val) {
	          return cm.getInputField().autocapitalize = val;
	        }, true);
	        option("rtlMoveVisually", !windows);
	        option("wholeLineUpdateBefore", true);
	        option("theme", "default", function (cm) {
	          themeChanged(cm);
	          updateGutters(cm);
	        }, true);
	        option("keyMap", "default", function (cm, val, old) {
	          var next = getKeyMap(val);
	          var prev = old != Init && getKeyMap(old);
	          if (prev && prev.detach) {
	            prev.detach(cm, next);
	          }
	          if (next.attach) {
	            next.attach(cm, prev || null);
	          }
	        });
	        option("extraKeys", null);
	        option("configureMouse", null);
	        option("lineWrapping", false, wrappingChanged, true);
	        option("gutters", [], function (cm, val) {
	          cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
	          updateGutters(cm);
	        }, true);
	        option("fixedGutter", true, function (cm, val) {
	          cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
	          cm.refresh();
	        }, true);
	        option("coverGutterNextToScrollbar", false, function (cm) {
	          return updateScrollbars(cm);
	        }, true);
	        option("scrollbarStyle", "native", function (cm) {
	          initScrollbars(cm);
	          updateScrollbars(cm);
	          cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
	          cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
	        }, true);
	        option("lineNumbers", false, function (cm, val) {
	          cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
	          updateGutters(cm);
	        }, true);
	        option("firstLineNumber", 1, updateGutters, true);
	        option("lineNumberFormatter", function (integer) {
	          return integer;
	        }, updateGutters, true);
	        option("showCursorWhenSelecting", false, updateSelection, true);
	        option("resetSelectionOnContextMenu", true);
	        option("lineWiseCopyCut", true);
	        option("pasteLinesPerSelection", true);
	        option("selectionsMayTouch", false);
	        option("readOnly", false, function (cm, val) {
	          if (val == "nocursor") {
	            onBlur(cm);
	            cm.display.input.blur();
	          }
	          cm.display.input.readOnlyChanged(val);
	        });
	        option("screenReaderLabel", null, function (cm, val) {
	          val = val === '' ? null : val;
	          cm.display.input.screenReaderLabelChanged(val);
	        });
	        option("disableInput", false, function (cm, val) {
	          if (!val) {
	            cm.display.input.reset();
	          }
	        }, true);
	        option("dragDrop", true, dragDropChanged);
	        option("allowDropFileTypes", null);
	        option("cursorBlinkRate", 530);
	        option("cursorScrollMargin", 0);
	        option("cursorHeight", 1, updateSelection, true);
	        option("singleCursorHeightPerLine", true, updateSelection, true);
	        option("workTime", 100);
	        option("workDelay", 100);
	        option("flattenSpans", true, resetModeState, true);
	        option("addModeClass", false, resetModeState, true);
	        option("pollInterval", 100);
	        option("undoDepth", 200, function (cm, val) {
	          return cm.doc.history.undoDepth = val;
	        });
	        option("historyEventDelay", 1250);
	        option("viewportMargin", 10, function (cm) {
	          return cm.refresh();
	        }, true);
	        option("maxHighlightLength", 10000, resetModeState, true);
	        option("moveInputWithCursor", true, function (cm, val) {
	          if (!val) {
	            cm.display.input.resetPosition();
	          }
	        });
	        option("tabindex", null, function (cm, val) {
	          return cm.display.input.getField().tabIndex = val || "";
	        });
	        option("autofocus", null);
	        option("direction", "ltr", function (cm, val) {
	          return cm.doc.setDirection(val);
	        }, true);
	        option("phrases", null);
	      }
	      function dragDropChanged(cm, value, old) {
	        var wasOn = old && old != Init;
	        if (!value != !wasOn) {
	          var funcs = cm.display.dragFunctions;
	          var toggle = value ? on : off;
	          toggle(cm.display.scroller, "dragstart", funcs.start);
	          toggle(cm.display.scroller, "dragenter", funcs.enter);
	          toggle(cm.display.scroller, "dragover", funcs.over);
	          toggle(cm.display.scroller, "dragleave", funcs.leave);
	          toggle(cm.display.scroller, "drop", funcs.drop);
	        }
	      }
	      function wrappingChanged(cm) {
	        if (cm.options.lineWrapping) {
	          addClass(cm.display.wrapper, "CodeMirror-wrap");
	          cm.display.sizer.style.minWidth = "";
	          cm.display.sizerWidth = null;
	        } else {
	          rmClass(cm.display.wrapper, "CodeMirror-wrap");
	          findMaxLine(cm);
	        }
	        estimateLineHeights(cm);
	        regChange(cm);
	        clearCaches(cm);
	        setTimeout(function () {
	          return updateScrollbars(cm);
	        }, 100);
	      }

	      // A CodeMirror instance represents an editor. This is the object
	      // that user code is usually dealing with.

	      function CodeMirror(place, options) {
	        var this$1$1 = this;
	        if (!(this instanceof CodeMirror)) {
	          return new CodeMirror(place, options);
	        }
	        this.options = options = options ? copyObj(options) : {};
	        // Determine effective options based on given values and defaults.
	        copyObj(defaults, options, false);
	        var doc = options.value;
	        if (typeof doc == "string") {
	          doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction);
	        } else if (options.mode) {
	          doc.modeOption = options.mode;
	        }
	        this.doc = doc;
	        var input = new CodeMirror.inputStyles[options.inputStyle](this);
	        var display = this.display = new Display(place, doc, input, options);
	        display.wrapper.CodeMirror = this;
	        themeChanged(this);
	        if (options.lineWrapping) {
	          this.display.wrapper.className += " CodeMirror-wrap";
	        }
	        initScrollbars(this);
	        this.state = {
	          keyMaps: [],
	          // stores maps added by addKeyMap
	          overlays: [],
	          // highlighting overlays, as added by addOverlay
	          modeGen: 0,
	          // bumped when mode/overlay changes, used to invalidate highlighting info
	          overwrite: false,
	          delayingBlurEvent: false,
	          focused: false,
	          suppressEdits: false,
	          // used to disable editing during key handlers when in readOnly mode
	          pasteIncoming: -1,
	          cutIncoming: -1,
	          // help recognize paste/cut edits in input.poll
	          selectingText: false,
	          draggingText: false,
	          highlight: new Delayed(),
	          // stores highlight worker timeout
	          keySeq: null,
	          // Unfinished key sequence
	          specialChars: null
	        };
	        if (options.autofocus && !mobile) {
	          display.input.focus();
	        }

	        // Override magic textarea content restore that IE sometimes does
	        // on our hidden textarea on reload
	        if (ie && ie_version < 11) {
	          setTimeout(function () {
	            return this$1$1.display.input.reset(true);
	          }, 20);
	        }
	        registerEventHandlers(this);
	        ensureGlobalHandlers();
	        startOperation(this);
	        this.curOp.forceUpdate = true;
	        attachDoc(this, doc);
	        if (options.autofocus && !mobile || this.hasFocus()) {
	          setTimeout(function () {
	            if (this$1$1.hasFocus() && !this$1$1.state.focused) {
	              onFocus(this$1$1);
	            }
	          }, 20);
	        } else {
	          onBlur(this);
	        }
	        for (var opt in optionHandlers) {
	          if (optionHandlers.hasOwnProperty(opt)) {
	            optionHandlers[opt](this, options[opt], Init);
	          }
	        }
	        maybeUpdateLineNumberWidth(this);
	        if (options.finishInit) {
	          options.finishInit(this);
	        }
	        for (var i = 0; i < initHooks.length; ++i) {
	          initHooks[i](this);
	        }
	        endOperation(this);
	        // Suppress optimizelegibility in Webkit, since it breaks text
	        // measuring on line wrapping boundaries.
	        if (webkit && options.lineWrapping && getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") {
	          display.lineDiv.style.textRendering = "auto";
	        }
	      }

	      // The default configuration options.
	      CodeMirror.defaults = defaults;
	      // Functions to run when options are changed.
	      CodeMirror.optionHandlers = optionHandlers;

	      // Attach the necessary event handlers when initializing the editor
	      function registerEventHandlers(cm) {
	        var d = cm.display;
	        on(d.scroller, "mousedown", operation(cm, onMouseDown));
	        // Older IE's will not fire a second mousedown for a double click
	        if (ie && ie_version < 11) {
	          on(d.scroller, "dblclick", operation(cm, function (e) {
	            if (signalDOMEvent(cm, e)) {
	              return;
	            }
	            var pos = posFromMouse(cm, e);
	            if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) {
	              return;
	            }
	            e_preventDefault(e);
	            var word = cm.findWordAt(pos);
	            extendSelection(cm.doc, word.anchor, word.head);
	          }));
	        } else {
	          on(d.scroller, "dblclick", function (e) {
	            return signalDOMEvent(cm, e) || e_preventDefault(e);
	          });
	        }
	        // Some browsers fire contextmenu *after* opening the menu, at
	        // which point we can't mess with it anymore. Context menu is
	        // handled in onMouseDown for these browsers.
	        on(d.scroller, "contextmenu", function (e) {
	          return onContextMenu(cm, e);
	        });
	        on(d.input.getField(), "contextmenu", function (e) {
	          if (!d.scroller.contains(e.target)) {
	            onContextMenu(cm, e);
	          }
	        });

	        // Used to suppress mouse event handling when a touch happens
	        var touchFinished,
	          prevTouch = {
	            end: 0
	          };
	        function finishTouch() {
	          if (d.activeTouch) {
	            touchFinished = setTimeout(function () {
	              return d.activeTouch = null;
	            }, 1000);
	            prevTouch = d.activeTouch;
	            prevTouch.end = +new Date();
	          }
	        }
	        function isMouseLikeTouchEvent(e) {
	          if (e.touches.length != 1) {
	            return false;
	          }
	          var touch = e.touches[0];
	          return touch.radiusX <= 1 && touch.radiusY <= 1;
	        }
	        function farAway(touch, other) {
	          if (other.left == null) {
	            return true;
	          }
	          var dx = other.left - touch.left,
	            dy = other.top - touch.top;
	          return dx * dx + dy * dy > 20 * 20;
	        }
	        on(d.scroller, "touchstart", function (e) {
	          if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
	            d.input.ensurePolled();
	            clearTimeout(touchFinished);
	            var now = +new Date();
	            d.activeTouch = {
	              start: now,
	              moved: false,
	              prev: now - prevTouch.end <= 300 ? prevTouch : null
	            };
	            if (e.touches.length == 1) {
	              d.activeTouch.left = e.touches[0].pageX;
	              d.activeTouch.top = e.touches[0].pageY;
	            }
	          }
	        });
	        on(d.scroller, "touchmove", function () {
	          if (d.activeTouch) {
	            d.activeTouch.moved = true;
	          }
	        });
	        on(d.scroller, "touchend", function (e) {
	          var touch = d.activeTouch;
	          if (touch && !eventInWidget(d, e) && touch.left != null && !touch.moved && new Date() - touch.start < 300) {
	            var pos = cm.coordsChar(d.activeTouch, "page"),
	              range;
	            if (!touch.prev || farAway(touch, touch.prev))
	              // Single tap
	              {
	                range = new Range(pos, pos);
	              } else if (!touch.prev.prev || farAway(touch, touch.prev.prev))
	              // Double tap
	              {
	                range = cm.findWordAt(pos);
	              } else
	              // Triple tap
	              {
	                range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
	              }
	            cm.setSelection(range.anchor, range.head);
	            cm.focus();
	            e_preventDefault(e);
	          }
	          finishTouch();
	        });
	        on(d.scroller, "touchcancel", finishTouch);

	        // Sync scrolling between fake scrollbars and real scrollable
	        // area, ensure viewport is updated when scrolling.
	        on(d.scroller, "scroll", function () {
	          if (d.scroller.clientHeight) {
	            updateScrollTop(cm, d.scroller.scrollTop);
	            setScrollLeft(cm, d.scroller.scrollLeft, true);
	            signal(cm, "scroll", cm);
	          }
	        });

	        // Listen to wheel events in order to try and update the viewport on time.
	        on(d.scroller, "mousewheel", function (e) {
	          return onScrollWheel(cm, e);
	        });
	        on(d.scroller, "DOMMouseScroll", function (e) {
	          return onScrollWheel(cm, e);
	        });

	        // Prevent wrapper from ever scrolling
	        on(d.wrapper, "scroll", function () {
	          return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0;
	        });
	        d.dragFunctions = {
	          enter: function (e) {
	            if (!signalDOMEvent(cm, e)) {
	              e_stop(e);
	            }
	          },
	          over: function (e) {
	            if (!signalDOMEvent(cm, e)) {
	              onDragOver(cm, e);
	              e_stop(e);
	            }
	          },
	          start: function (e) {
	            return onDragStart(cm, e);
	          },
	          drop: operation(cm, onDrop),
	          leave: function (e) {
	            if (!signalDOMEvent(cm, e)) {
	              clearDragCursor(cm);
	            }
	          }
	        };
	        var inp = d.input.getField();
	        on(inp, "keyup", function (e) {
	          return onKeyUp.call(cm, e);
	        });
	        on(inp, "keydown", operation(cm, onKeyDown));
	        on(inp, "keypress", operation(cm, onKeyPress));
	        on(inp, "focus", function (e) {
	          return onFocus(cm, e);
	        });
	        on(inp, "blur", function (e) {
	          return onBlur(cm, e);
	        });
	      }
	      var initHooks = [];
	      CodeMirror.defineInitHook = function (f) {
	        return initHooks.push(f);
	      };

	      // Indent the given line. The how parameter can be "smart",
	      // "add"/null, "subtract", or "prev". When aggressive is false
	      // (typically set to true for forced single-line indents), empty
	      // lines are not indented, and places where the mode returns Pass
	      // are left alone.
	      function indentLine(cm, n, how, aggressive) {
	        var doc = cm.doc,
	          state;
	        if (how == null) {
	          how = "add";
	        }
	        if (how == "smart") {
	          // Fall back to "prev" when the mode doesn't have an indentation
	          // method.
	          if (!doc.mode.indent) {
	            how = "prev";
	          } else {
	            state = getContextBefore(cm, n).state;
	          }
	        }
	        var tabSize = cm.options.tabSize;
	        var line = getLine(doc, n),
	          curSpace = countColumn(line.text, null, tabSize);
	        if (line.stateAfter) {
	          line.stateAfter = null;
	        }
	        var curSpaceString = line.text.match(/^\s*/)[0],
	          indentation;
	        if (!aggressive && !/\S/.test(line.text)) {
	          indentation = 0;
	          how = "not";
	        } else if (how == "smart") {
	          indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
	          if (indentation == Pass || indentation > 150) {
	            if (!aggressive) {
	              return;
	            }
	            how = "prev";
	          }
	        }
	        if (how == "prev") {
	          if (n > doc.first) {
	            indentation = countColumn(getLine(doc, n - 1).text, null, tabSize);
	          } else {
	            indentation = 0;
	          }
	        } else if (how == "add") {
	          indentation = curSpace + cm.options.indentUnit;
	        } else if (how == "subtract") {
	          indentation = curSpace - cm.options.indentUnit;
	        } else if (typeof how == "number") {
	          indentation = curSpace + how;
	        }
	        indentation = Math.max(0, indentation);
	        var indentString = "",
	          pos = 0;
	        if (cm.options.indentWithTabs) {
	          for (var i = Math.floor(indentation / tabSize); i; --i) {
	            pos += tabSize;
	            indentString += "\t";
	          }
	        }
	        if (pos < indentation) {
	          indentString += spaceStr(indentation - pos);
	        }
	        if (indentString != curSpaceString) {
	          replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
	          line.stateAfter = null;
	          return true;
	        } else {
	          // Ensure that, if the cursor was in the whitespace at the start
	          // of the line, it is moved to the end of that space.
	          for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
	            var range = doc.sel.ranges[i$1];
	            if (range.head.line == n && range.head.ch < curSpaceString.length) {
	              var pos$1 = Pos(n, curSpaceString.length);
	              replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
	              break;
	            }
	          }
	        }
	      }

	      // This will be set to a {lineWise: bool, text: [string]} object, so
	      // that, when pasting, we know what kind of selections the copied
	      // text was made out of.
	      var lastCopied = null;
	      function setLastCopied(newLastCopied) {
	        lastCopied = newLastCopied;
	      }
	      function applyTextInput(cm, inserted, deleted, sel, origin) {
	        var doc = cm.doc;
	        cm.display.shift = false;
	        if (!sel) {
	          sel = doc.sel;
	        }
	        var recent = +new Date() - 200;
	        var paste = origin == "paste" || cm.state.pasteIncoming > recent;
	        var textLines = splitLinesAuto(inserted),
	          multiPaste = null;
	        // When pasting N lines into N selections, insert one line per selection
	        if (paste && sel.ranges.length > 1) {
	          if (lastCopied && lastCopied.text.join("\n") == inserted) {
	            if (sel.ranges.length % lastCopied.text.length == 0) {
	              multiPaste = [];
	              for (var i = 0; i < lastCopied.text.length; i++) {
	                multiPaste.push(doc.splitLines(lastCopied.text[i]));
	              }
	            }
	          } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
	            multiPaste = map(textLines, function (l) {
	              return [l];
	            });
	          }
	        }
	        var updateInput = cm.curOp.updateInput;
	        // Normal behavior is to insert the new text into every selection
	        for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
	          var range = sel.ranges[i$1];
	          var from = range.from(),
	            to = range.to();
	          if (range.empty()) {
	            if (deleted && deleted > 0)
	              // Handle deletion
	              {
	                from = Pos(from.line, from.ch - deleted);
	              } else if (cm.state.overwrite && !paste)
	              // Handle overwrite
	              {
	                to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
	              } else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n")) {
	              from = to = Pos(from.line, 0);
	            }
	          }
	          var changeEvent = {
	            from: from,
	            to: to,
	            text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
	            origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")
	          };
	          makeChange(cm.doc, changeEvent);
	          signalLater(cm, "inputRead", cm, changeEvent);
	        }
	        if (inserted && !paste) {
	          triggerElectric(cm, inserted);
	        }
	        ensureCursorVisible(cm);
	        if (cm.curOp.updateInput < 2) {
	          cm.curOp.updateInput = updateInput;
	        }
	        cm.curOp.typing = true;
	        cm.state.pasteIncoming = cm.state.cutIncoming = -1;
	      }
	      function handlePaste(e, cm) {
	        var pasted = e.clipboardData && e.clipboardData.getData("Text");
	        if (pasted) {
	          e.preventDefault();
	          if (!cm.isReadOnly() && !cm.options.disableInput && cm.hasFocus()) {
	            runInOp(cm, function () {
	              return applyTextInput(cm, pasted, 0, null, "paste");
	            });
	          }
	          return true;
	        }
	      }
	      function triggerElectric(cm, inserted) {
	        // When an 'electric' character is inserted, immediately trigger a reindent
	        if (!cm.options.electricChars || !cm.options.smartIndent) {
	          return;
	        }
	        var sel = cm.doc.sel;
	        for (var i = sel.ranges.length - 1; i >= 0; i--) {
	          var range = sel.ranges[i];
	          if (range.head.ch > 100 || i && sel.ranges[i - 1].head.line == range.head.line) {
	            continue;
	          }
	          var mode = cm.getModeAt(range.head);
	          var indented = false;
	          if (mode.electricChars) {
	            for (var j = 0; j < mode.electricChars.length; j++) {
	              if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
	                indented = indentLine(cm, range.head.line, "smart");
	                break;
	              }
	            }
	          } else if (mode.electricInput) {
	            if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) {
	              indented = indentLine(cm, range.head.line, "smart");
	            }
	          }
	          if (indented) {
	            signalLater(cm, "electricInput", cm, range.head.line);
	          }
	        }
	      }
	      function copyableRanges(cm) {
	        var text = [],
	          ranges = [];
	        for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
	          var line = cm.doc.sel.ranges[i].head.line;
	          var lineRange = {
	            anchor: Pos(line, 0),
	            head: Pos(line + 1, 0)
	          };
	          ranges.push(lineRange);
	          text.push(cm.getRange(lineRange.anchor, lineRange.head));
	        }
	        return {
	          text: text,
	          ranges: ranges
	        };
	      }
	      function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
	        field.setAttribute("autocorrect", autocorrect ? "on" : "off");
	        field.setAttribute("autocapitalize", autocapitalize ? "on" : "off");
	        field.setAttribute("spellcheck", !!spellcheck);
	      }
	      function hiddenTextarea() {
	        var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none");
	        var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
	        // The textarea is kept positioned near the cursor to prevent the
	        // fact that it'll be scrolled into view on input from scrolling
	        // our fake cursor out of view. On webkit, when wrap=off, paste is
	        // very slow. So make the area wide instead.
	        if (webkit) {
	          te.style.width = "1000px";
	        } else {
	          te.setAttribute("wrap", "off");
	        }
	        // If border: 0; -- iOS fails to open keyboard (issue #1287)
	        if (ios) {
	          te.style.border = "1px solid black";
	        }
	        return div;
	      }

	      // The publicly visible API. Note that methodOp(f) means
	      // 'wrap f in an operation, performed on its `this` parameter'.

	      // This is not the complete set of editor methods. Most of the
	      // methods defined on the Doc type are also injected into
	      // CodeMirror.prototype, for backwards compatibility and
	      // convenience.

	      function addEditorMethods(CodeMirror) {
	        var optionHandlers = CodeMirror.optionHandlers;
	        var helpers = CodeMirror.helpers = {};
	        CodeMirror.prototype = {
	          constructor: CodeMirror,
	          focus: function () {
	            win(this).focus();
	            this.display.input.focus();
	          },
	          setOption: function (option, value) {
	            var options = this.options,
	              old = options[option];
	            if (options[option] == value && option != "mode") {
	              return;
	            }
	            options[option] = value;
	            if (optionHandlers.hasOwnProperty(option)) {
	              operation(this, optionHandlers[option])(this, value, old);
	            }
	            signal(this, "optionChange", this, option);
	          },
	          getOption: function (option) {
	            return this.options[option];
	          },
	          getDoc: function () {
	            return this.doc;
	          },
	          addKeyMap: function (map, bottom) {
	            this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
	          },
	          removeKeyMap: function (map) {
	            var maps = this.state.keyMaps;
	            for (var i = 0; i < maps.length; ++i) {
	              if (maps[i] == map || maps[i].name == map) {
	                maps.splice(i, 1);
	                return true;
	              }
	            }
	          },
	          addOverlay: methodOp(function (spec, options) {
	            var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
	            if (mode.startState) {
	              throw new Error("Overlays may not be stateful.");
	            }
	            insertSorted(this.state.overlays, {
	              mode: mode,
	              modeSpec: spec,
	              opaque: options && options.opaque,
	              priority: options && options.priority || 0
	            }, function (overlay) {
	              return overlay.priority;
	            });
	            this.state.modeGen++;
	            regChange(this);
	          }),
	          removeOverlay: methodOp(function (spec) {
	            var overlays = this.state.overlays;
	            for (var i = 0; i < overlays.length; ++i) {
	              var cur = overlays[i].modeSpec;
	              if (cur == spec || typeof spec == "string" && cur.name == spec) {
	                overlays.splice(i, 1);
	                this.state.modeGen++;
	                regChange(this);
	                return;
	              }
	            }
	          }),
	          indentLine: methodOp(function (n, dir, aggressive) {
	            if (typeof dir != "string" && typeof dir != "number") {
	              if (dir == null) {
	                dir = this.options.smartIndent ? "smart" : "prev";
	              } else {
	                dir = dir ? "add" : "subtract";
	              }
	            }
	            if (isLine(this.doc, n)) {
	              indentLine(this, n, dir, aggressive);
	            }
	          }),
	          indentSelection: methodOp(function (how) {
	            var ranges = this.doc.sel.ranges,
	              end = -1;
	            for (var i = 0; i < ranges.length; i++) {
	              var range = ranges[i];
	              if (!range.empty()) {
	                var from = range.from(),
	                  to = range.to();
	                var start = Math.max(end, from.line);
	                end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
	                for (var j = start; j < end; ++j) {
	                  indentLine(this, j, how);
	                }
	                var newRanges = this.doc.sel.ranges;
	                if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) {
	                  replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
	                }
	              } else if (range.head.line > end) {
	                indentLine(this, range.head.line, how, true);
	                end = range.head.line;
	                if (i == this.doc.sel.primIndex) {
	                  ensureCursorVisible(this);
	                }
	              }
	            }
	          }),
	          // Fetch the parser token for a given character. Useful for hacks
	          // that want to inspect the mode state (say, for completion).
	          getTokenAt: function (pos, precise) {
	            return takeToken(this, pos, precise);
	          },
	          getLineTokens: function (line, precise) {
	            return takeToken(this, Pos(line), precise, true);
	          },
	          getTokenTypeAt: function (pos) {
	            pos = clipPos(this.doc, pos);
	            var styles = getLineStyles(this, getLine(this.doc, pos.line));
	            var before = 0,
	              after = (styles.length - 1) / 2,
	              ch = pos.ch;
	            var type;
	            if (ch == 0) {
	              type = styles[2];
	            } else {
	              for (;;) {
	                var mid = before + after >> 1;
	                if ((mid ? styles[mid * 2 - 1] : 0) >= ch) {
	                  after = mid;
	                } else if (styles[mid * 2 + 1] < ch) {
	                  before = mid + 1;
	                } else {
	                  type = styles[mid * 2 + 2];
	                  break;
	                }
	              }
	            }
	            var cut = type ? type.indexOf("overlay ") : -1;
	            return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
	          },
	          getModeAt: function (pos) {
	            var mode = this.doc.mode;
	            if (!mode.innerMode) {
	              return mode;
	            }
	            return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
	          },
	          getHelper: function (pos, type) {
	            return this.getHelpers(pos, type)[0];
	          },
	          getHelpers: function (pos, type) {
	            var found = [];
	            if (!helpers.hasOwnProperty(type)) {
	              return found;
	            }
	            var help = helpers[type],
	              mode = this.getModeAt(pos);
	            if (typeof mode[type] == "string") {
	              if (help[mode[type]]) {
	                found.push(help[mode[type]]);
	              }
	            } else if (mode[type]) {
	              for (var i = 0; i < mode[type].length; i++) {
	                var val = help[mode[type][i]];
	                if (val) {
	                  found.push(val);
	                }
	              }
	            } else if (mode.helperType && help[mode.helperType]) {
	              found.push(help[mode.helperType]);
	            } else if (help[mode.name]) {
	              found.push(help[mode.name]);
	            }
	            for (var i$1 = 0; i$1 < help._global.length; i$1++) {
	              var cur = help._global[i$1];
	              if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) {
	                found.push(cur.val);
	              }
	            }
	            return found;
	          },
	          getStateAfter: function (line, precise) {
	            var doc = this.doc;
	            line = clipLine(doc, line == null ? doc.first + doc.size - 1 : line);
	            return getContextBefore(this, line + 1, precise).state;
	          },
	          cursorCoords: function (start, mode) {
	            var pos,
	              range = this.doc.sel.primary();
	            if (start == null) {
	              pos = range.head;
	            } else if (typeof start == "object") {
	              pos = clipPos(this.doc, start);
	            } else {
	              pos = start ? range.from() : range.to();
	            }
	            return cursorCoords(this, pos, mode || "page");
	          },
	          charCoords: function (pos, mode) {
	            return charCoords(this, clipPos(this.doc, pos), mode || "page");
	          },
	          coordsChar: function (coords, mode) {
	            coords = fromCoordSystem(this, coords, mode || "page");
	            return coordsChar(this, coords.left, coords.top);
	          },
	          lineAtHeight: function (height, mode) {
	            height = fromCoordSystem(this, {
	              top: height,
	              left: 0
	            }, mode || "page").top;
	            return lineAtHeight(this.doc, height + this.display.viewOffset);
	          },
	          heightAtLine: function (line, mode, includeWidgets) {
	            var end = false,
	              lineObj;
	            if (typeof line == "number") {
	              var last = this.doc.first + this.doc.size - 1;
	              if (line < this.doc.first) {
	                line = this.doc.first;
	              } else if (line > last) {
	                line = last;
	                end = true;
	              }
	              lineObj = getLine(this.doc, line);
	            } else {
	              lineObj = line;
	            }
	            return intoCoordSystem(this, lineObj, {
	              top: 0,
	              left: 0
	            }, mode || "page", includeWidgets || end).top + (end ? this.doc.height - heightAtLine(lineObj) : 0);
	          },
	          defaultTextHeight: function () {
	            return textHeight(this.display);
	          },
	          defaultCharWidth: function () {
	            return charWidth(this.display);
	          },
	          getViewport: function () {
	            return {
	              from: this.display.viewFrom,
	              to: this.display.viewTo
	            };
	          },
	          addWidget: function (pos, node, scroll, vert, horiz) {
	            var display = this.display;
	            pos = cursorCoords(this, clipPos(this.doc, pos));
	            var top = pos.bottom,
	              left = pos.left;
	            node.style.position = "absolute";
	            node.setAttribute("cm-ignore-events", "true");
	            this.display.input.setUneditable(node);
	            display.sizer.appendChild(node);
	            if (vert == "over") {
	              top = pos.top;
	            } else if (vert == "above" || vert == "near") {
	              var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
	                hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
	              // Default to positioning above (if specified and possible); otherwise default to positioning below
	              if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) {
	                top = pos.top - node.offsetHeight;
	              } else if (pos.bottom + node.offsetHeight <= vspace) {
	                top = pos.bottom;
	              }
	              if (left + node.offsetWidth > hspace) {
	                left = hspace - node.offsetWidth;
	              }
	            }
	            node.style.top = top + "px";
	            node.style.left = node.style.right = "";
	            if (horiz == "right") {
	              left = display.sizer.clientWidth - node.offsetWidth;
	              node.style.right = "0px";
	            } else {
	              if (horiz == "left") {
	                left = 0;
	              } else if (horiz == "middle") {
	                left = (display.sizer.clientWidth - node.offsetWidth) / 2;
	              }
	              node.style.left = left + "px";
	            }
	            if (scroll) {
	              scrollIntoView(this, {
	                left: left,
	                top: top,
	                right: left + node.offsetWidth,
	                bottom: top + node.offsetHeight
	              });
	            }
	          },
	          triggerOnKeyDown: methodOp(onKeyDown),
	          triggerOnKeyPress: methodOp(onKeyPress),
	          triggerOnKeyUp: onKeyUp,
	          triggerOnMouseDown: methodOp(onMouseDown),
	          execCommand: function (cmd) {
	            if (commands.hasOwnProperty(cmd)) {
	              return commands[cmd].call(null, this);
	            }
	          },
	          triggerElectric: methodOp(function (text) {
	            triggerElectric(this, text);
	          }),
	          findPosH: function (from, amount, unit, visually) {
	            var dir = 1;
	            if (amount < 0) {
	              dir = -1;
	              amount = -amount;
	            }
	            var cur = clipPos(this.doc, from);
	            for (var i = 0; i < amount; ++i) {
	              cur = findPosH(this.doc, cur, dir, unit, visually);
	              if (cur.hitSide) {
	                break;
	              }
	            }
	            return cur;
	          },
	          moveH: methodOp(function (dir, unit) {
	            var this$1$1 = this;
	            this.extendSelectionsBy(function (range) {
	              if (this$1$1.display.shift || this$1$1.doc.extend || range.empty()) {
	                return findPosH(this$1$1.doc, range.head, dir, unit, this$1$1.options.rtlMoveVisually);
	              } else {
	                return dir < 0 ? range.from() : range.to();
	              }
	            }, sel_move);
	          }),
	          deleteH: methodOp(function (dir, unit) {
	            var sel = this.doc.sel,
	              doc = this.doc;
	            if (sel.somethingSelected()) {
	              doc.replaceSelection("", null, "+delete");
	            } else {
	              deleteNearSelection(this, function (range) {
	                var other = findPosH(doc, range.head, dir, unit, false);
	                return dir < 0 ? {
	                  from: other,
	                  to: range.head
	                } : {
	                  from: range.head,
	                  to: other
	                };
	              });
	            }
	          }),
	          findPosV: function (from, amount, unit, goalColumn) {
	            var dir = 1,
	              x = goalColumn;
	            if (amount < 0) {
	              dir = -1;
	              amount = -amount;
	            }
	            var cur = clipPos(this.doc, from);
	            for (var i = 0; i < amount; ++i) {
	              var coords = cursorCoords(this, cur, "div");
	              if (x == null) {
	                x = coords.left;
	              } else {
	                coords.left = x;
	              }
	              cur = findPosV(this, coords, dir, unit);
	              if (cur.hitSide) {
	                break;
	              }
	            }
	            return cur;
	          },
	          moveV: methodOp(function (dir, unit) {
	            var this$1$1 = this;
	            var doc = this.doc,
	              goals = [];
	            var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
	            doc.extendSelectionsBy(function (range) {
	              if (collapse) {
	                return dir < 0 ? range.from() : range.to();
	              }
	              var headPos = cursorCoords(this$1$1, range.head, "div");
	              if (range.goalColumn != null) {
	                headPos.left = range.goalColumn;
	              }
	              goals.push(headPos.left);
	              var pos = findPosV(this$1$1, headPos, dir, unit);
	              if (unit == "page" && range == doc.sel.primary()) {
	                addToScrollTop(this$1$1, charCoords(this$1$1, pos, "div").top - headPos.top);
	              }
	              return pos;
	            }, sel_move);
	            if (goals.length) {
	              for (var i = 0; i < doc.sel.ranges.length; i++) {
	                doc.sel.ranges[i].goalColumn = goals[i];
	              }
	            }
	          }),
	          // Find the word at the given position (as returned by coordsChar).
	          findWordAt: function (pos) {
	            var doc = this.doc,
	              line = getLine(doc, pos.line).text;
	            var start = pos.ch,
	              end = pos.ch;
	            if (line) {
	              var helper = this.getHelper(pos, "wordChars");
	              if ((pos.sticky == "before" || end == line.length) && start) {
	                --start;
	              } else {
	                ++end;
	              }
	              var startChar = line.charAt(start);
	              var check = isWordChar(startChar, helper) ? function (ch) {
	                return isWordChar(ch, helper);
	              } : /\s/.test(startChar) ? function (ch) {
	                return /\s/.test(ch);
	              } : function (ch) {
	                return !/\s/.test(ch) && !isWordChar(ch);
	              };
	              while (start > 0 && check(line.charAt(start - 1))) {
	                --start;
	              }
	              while (end < line.length && check(line.charAt(end))) {
	                ++end;
	              }
	            }
	            return new Range(Pos(pos.line, start), Pos(pos.line, end));
	          },
	          toggleOverwrite: function (value) {
	            if (value != null && value == this.state.overwrite) {
	              return;
	            }
	            if (this.state.overwrite = !this.state.overwrite) {
	              addClass(this.display.cursorDiv, "CodeMirror-overwrite");
	            } else {
	              rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
	            }
	            signal(this, "overwriteToggle", this, this.state.overwrite);
	          },
	          hasFocus: function () {
	            return this.display.input.getField() == activeElt(root(this));
	          },
	          isReadOnly: function () {
	            return !!(this.options.readOnly || this.doc.cantEdit);
	          },
	          scrollTo: methodOp(function (x, y) {
	            scrollToCoords(this, x, y);
	          }),
	          getScrollInfo: function () {
	            var scroller = this.display.scroller;
	            return {
	              left: scroller.scrollLeft,
	              top: scroller.scrollTop,
	              height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
	              width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
	              clientHeight: displayHeight(this),
	              clientWidth: displayWidth(this)
	            };
	          },
	          scrollIntoView: methodOp(function (range, margin) {
	            if (range == null) {
	              range = {
	                from: this.doc.sel.primary().head,
	                to: null
	              };
	              if (margin == null) {
	                margin = this.options.cursorScrollMargin;
	              }
	            } else if (typeof range == "number") {
	              range = {
	                from: Pos(range, 0),
	                to: null
	              };
	            } else if (range.from == null) {
	              range = {
	                from: range,
	                to: null
	              };
	            }
	            if (!range.to) {
	              range.to = range.from;
	            }
	            range.margin = margin || 0;
	            if (range.from.line != null) {
	              scrollToRange(this, range);
	            } else {
	              scrollToCoordsRange(this, range.from, range.to, range.margin);
	            }
	          }),
	          setSize: methodOp(function (width, height) {
	            var this$1$1 = this;
	            var interpret = function (val) {
	              return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
	            };
	            if (width != null) {
	              this.display.wrapper.style.width = interpret(width);
	            }
	            if (height != null) {
	              this.display.wrapper.style.height = interpret(height);
	            }
	            if (this.options.lineWrapping) {
	              clearLineMeasurementCache(this);
	            }
	            var lineNo = this.display.viewFrom;
	            this.doc.iter(lineNo, this.display.viewTo, function (line) {
	              if (line.widgets) {
	                for (var i = 0; i < line.widgets.length; i++) {
	                  if (line.widgets[i].noHScroll) {
	                    regLineChange(this$1$1, lineNo, "widget");
	                    break;
	                  }
	                }
	              }
	              ++lineNo;
	            });
	            this.curOp.forceUpdate = true;
	            signal(this, "refresh", this);
	          }),
	          operation: function (f) {
	            return runInOp(this, f);
	          },
	          startOperation: function () {
	            return startOperation(this);
	          },
	          endOperation: function () {
	            return endOperation(this);
	          },
	          refresh: methodOp(function () {
	            var oldHeight = this.display.cachedTextHeight;
	            regChange(this);
	            this.curOp.forceUpdate = true;
	            clearCaches(this);
	            scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
	            updateGutterSpace(this.display);
	            if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping) {
	              estimateLineHeights(this);
	            }
	            signal(this, "refresh", this);
	          }),
	          swapDoc: methodOp(function (doc) {
	            var old = this.doc;
	            old.cm = null;
	            // Cancel the current text selection if any (#5821)
	            if (this.state.selectingText) {
	              this.state.selectingText();
	            }
	            attachDoc(this, doc);
	            clearCaches(this);
	            this.display.input.reset();
	            scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
	            this.curOp.forceScroll = true;
	            signalLater(this, "swapDoc", this, old);
	            return old;
	          }),
	          phrase: function (phraseText) {
	            var phrases = this.options.phrases;
	            return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText;
	          },
	          getInputField: function () {
	            return this.display.input.getField();
	          },
	          getWrapperElement: function () {
	            return this.display.wrapper;
	          },
	          getScrollerElement: function () {
	            return this.display.scroller;
	          },
	          getGutterElement: function () {
	            return this.display.gutters;
	          }
	        };
	        eventMixin(CodeMirror);
	        CodeMirror.registerHelper = function (type, name, value) {
	          if (!helpers.hasOwnProperty(type)) {
	            helpers[type] = CodeMirror[type] = {
	              _global: []
	            };
	          }
	          helpers[type][name] = value;
	        };
	        CodeMirror.registerGlobalHelper = function (type, name, predicate, value) {
	          CodeMirror.registerHelper(type, name, value);
	          helpers[type]._global.push({
	            pred: predicate,
	            val: value
	          });
	        };
	      }

	      // Used for horizontal relative motion. Dir is -1 or 1 (left or
	      // right), unit can be "codepoint", "char", "column" (like char, but
	      // doesn't cross line boundaries), "word" (across next word), or
	      // "group" (to the start of next group of word or
	      // non-word-non-whitespace chars). The visually param controls
	      // whether, in right-to-left text, direction 1 means to move towards
	      // the next index in the string, or towards the character to the right
	      // of the current position. The resulting position will have a
	      // hitSide=true property if it reached the end of the document.
	      function findPosH(doc, pos, dir, unit, visually) {
	        var oldPos = pos;
	        var origDir = dir;
	        var lineObj = getLine(doc, pos.line);
	        var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
	        function findNextLine() {
	          var l = pos.line + lineDir;
	          if (l < doc.first || l >= doc.first + doc.size) {
	            return false;
	          }
	          pos = new Pos(l, pos.ch, pos.sticky);
	          return lineObj = getLine(doc, l);
	        }
	        function moveOnce(boundToLine) {
	          var next;
	          if (unit == "codepoint") {
	            var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1));
	            if (isNaN(ch)) {
	              next = null;
	            } else {
	              var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF;
	              next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir);
	            }
	          } else if (visually) {
	            next = moveVisually(doc.cm, lineObj, pos, dir);
	          } else {
	            next = moveLogically(lineObj, pos, dir);
	          }
	          if (next == null) {
	            if (!boundToLine && findNextLine()) {
	              pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir);
	            } else {
	              return false;
	            }
	          } else {
	            pos = next;
	          }
	          return true;
	        }
	        if (unit == "char" || unit == "codepoint") {
	          moveOnce();
	        } else if (unit == "column") {
	          moveOnce(true);
	        } else if (unit == "word" || unit == "group") {
	          var sawType = null,
	            group = unit == "group";
	          var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
	          for (var first = true;; first = false) {
	            if (dir < 0 && !moveOnce(!first)) {
	              break;
	            }
	            var cur = lineObj.text.charAt(pos.ch) || "\n";
	            var type = isWordChar(cur, helper) ? "w" : group && cur == "\n" ? "n" : !group || /\s/.test(cur) ? null : "p";
	            if (group && !first && !type) {
	              type = "s";
	            }
	            if (sawType && sawType != type) {
	              if (dir < 0) {
	                dir = 1;
	                moveOnce();
	                pos.sticky = "after";
	              }
	              break;
	            }
	            if (type) {
	              sawType = type;
	            }
	            if (dir > 0 && !moveOnce(!first)) {
	              break;
	            }
	          }
	        }
	        var result = skipAtomic(doc, pos, oldPos, origDir, true);
	        if (equalCursorPos(oldPos, result)) {
	          result.hitSide = true;
	        }
	        return result;
	      }

	      // For relative vertical movement. Dir may be -1 or 1. Unit can be
	      // "page" or "line". The resulting position will have a hitSide=true
	      // property if it reached the end of the document.
	      function findPosV(cm, pos, dir, unit) {
	        var doc = cm.doc,
	          x = pos.left,
	          y;
	        if (unit == "page") {
	          var pageSize = Math.min(cm.display.wrapper.clientHeight, win(cm).innerHeight || doc(cm).documentElement.clientHeight);
	          var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
	          y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
	        } else if (unit == "line") {
	          y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
	        }
	        var target;
	        for (;;) {
	          target = coordsChar(cm, x, y);
	          if (!target.outside) {
	            break;
	          }
	          if (dir < 0 ? y <= 0 : y >= doc.height) {
	            target.hitSide = true;
	            break;
	          }
	          y += dir * 5;
	        }
	        return target;
	      }

	      // CONTENTEDITABLE INPUT STYLE

	      var ContentEditableInput = function (cm) {
	        this.cm = cm;
	        this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
	        this.polling = new Delayed();
	        this.composing = null;
	        this.gracePeriod = false;
	        this.readDOMTimeout = null;
	      };
	      ContentEditableInput.prototype.init = function (display) {
	        var this$1$1 = this;
	        var input = this,
	          cm = input.cm;
	        var div = input.div = display.lineDiv;
	        div.contentEditable = true;
	        disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
	        function belongsToInput(e) {
	          for (var t = e.target; t; t = t.parentNode) {
	            if (t == div) {
	              return true;
	            }
	            if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) {
	              break;
	            }
	          }
	          return false;
	        }
	        on(div, "paste", function (e) {
	          if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) {
	            return;
	          }
	          // IE doesn't fire input events, so we schedule a read for the pasted content in this way
	          if (ie_version <= 11) {
	            setTimeout(operation(cm, function () {
	              return this$1$1.updateFromDOM();
	            }), 20);
	          }
	        });
	        on(div, "compositionstart", function (e) {
	          this$1$1.composing = {
	            data: e.data,
	            done: false
	          };
	        });
	        on(div, "compositionupdate", function (e) {
	          if (!this$1$1.composing) {
	            this$1$1.composing = {
	              data: e.data,
	              done: false
	            };
	          }
	        });
	        on(div, "compositionend", function (e) {
	          if (this$1$1.composing) {
	            if (e.data != this$1$1.composing.data) {
	              this$1$1.readFromDOMSoon();
	            }
	            this$1$1.composing.done = true;
	          }
	        });
	        on(div, "touchstart", function () {
	          return input.forceCompositionEnd();
	        });
	        on(div, "input", function () {
	          if (!this$1$1.composing) {
	            this$1$1.readFromDOMSoon();
	          }
	        });
	        function onCopyCut(e) {
	          if (!belongsToInput(e) || signalDOMEvent(cm, e)) {
	            return;
	          }
	          if (cm.somethingSelected()) {
	            setLastCopied({
	              lineWise: false,
	              text: cm.getSelections()
	            });
	            if (e.type == "cut") {
	              cm.replaceSelection("", null, "cut");
	            }
	          } else if (!cm.options.lineWiseCopyCut) {
	            return;
	          } else {
	            var ranges = copyableRanges(cm);
	            setLastCopied({
	              lineWise: true,
	              text: ranges.text
	            });
	            if (e.type == "cut") {
	              cm.operation(function () {
	                cm.setSelections(ranges.ranges, 0, sel_dontScroll);
	                cm.replaceSelection("", null, "cut");
	              });
	            }
	          }
	          if (e.clipboardData) {
	            e.clipboardData.clearData();
	            var content = lastCopied.text.join("\n");
	            // iOS exposes the clipboard API, but seems to discard content inserted into it
	            e.clipboardData.setData("Text", content);
	            if (e.clipboardData.getData("Text") == content) {
	              e.preventDefault();
	              return;
	            }
	          }
	          // Old-fashioned briefly-focus-a-textarea hack
	          var kludge = hiddenTextarea(),
	            te = kludge.firstChild;
	          disableBrowserMagic(te);
	          cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
	          te.value = lastCopied.text.join("\n");
	          var hadFocus = activeElt(rootNode(div));
	          selectInput(te);
	          setTimeout(function () {
	            cm.display.lineSpace.removeChild(kludge);
	            hadFocus.focus();
	            if (hadFocus == div) {
	              input.showPrimarySelection();
	            }
	          }, 50);
	        }
	        on(div, "copy", onCopyCut);
	        on(div, "cut", onCopyCut);
	      };
	      ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
	        // Label for screenreaders, accessibility
	        if (label) {
	          this.div.setAttribute('aria-label', label);
	        } else {
	          this.div.removeAttribute('aria-label');
	        }
	      };
	      ContentEditableInput.prototype.prepareSelection = function () {
	        var result = prepareSelection(this.cm, false);
	        result.focus = activeElt(rootNode(this.div)) == this.div;
	        return result;
	      };
	      ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
	        if (!info || !this.cm.display.view.length) {
	          return;
	        }
	        if (info.focus || takeFocus) {
	          this.showPrimarySelection();
	        }
	        this.showMultipleSelections(info);
	      };
	      ContentEditableInput.prototype.getSelection = function () {
	        return this.cm.display.wrapper.ownerDocument.getSelection();
	      };
	      ContentEditableInput.prototype.showPrimarySelection = function () {
	        var sel = this.getSelection(),
	          cm = this.cm,
	          prim = cm.doc.sel.primary();
	        var from = prim.from(),
	          to = prim.to();
	        if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
	          sel.removeAllRanges();
	          return;
	        }
	        var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
	        var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
	        if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && cmp(minPos(curAnchor, curFocus), from) == 0 && cmp(maxPos(curAnchor, curFocus), to) == 0) {
	          return;
	        }
	        var view = cm.display.view;
	        var start = from.line >= cm.display.viewFrom && posToDOM(cm, from) || {
	          node: view[0].measure.map[2],
	          offset: 0
	        };
	        var end = to.line < cm.display.viewTo && posToDOM(cm, to);
	        if (!end) {
	          var measure = view[view.length - 1].measure;
	          var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
	          end = {
	            node: map[map.length - 1],
	            offset: map[map.length - 2] - map[map.length - 3]
	          };
	        }
	        if (!start || !end) {
	          sel.removeAllRanges();
	          return;
	        }
	        var old = sel.rangeCount && sel.getRangeAt(0),
	          rng;
	        try {
	          rng = range(start.node, start.offset, end.offset, end.node);
	        } catch (e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
	        if (rng) {
	          if (!gecko && cm.state.focused) {
	            sel.collapse(start.node, start.offset);
	            if (!rng.collapsed) {
	              sel.removeAllRanges();
	              sel.addRange(rng);
	            }
	          } else {
	            sel.removeAllRanges();
	            sel.addRange(rng);
	          }
	          if (old && sel.anchorNode == null) {
	            sel.addRange(old);
	          } else if (gecko) {
	            this.startGracePeriod();
	          }
	        }
	        this.rememberSelection();
	      };
	      ContentEditableInput.prototype.startGracePeriod = function () {
	        var this$1$1 = this;
	        clearTimeout(this.gracePeriod);
	        this.gracePeriod = setTimeout(function () {
	          this$1$1.gracePeriod = false;
	          if (this$1$1.selectionChanged()) {
	            this$1$1.cm.operation(function () {
	              return this$1$1.cm.curOp.selectionChanged = true;
	            });
	          }
	        }, 20);
	      };
	      ContentEditableInput.prototype.showMultipleSelections = function (info) {
	        removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
	        removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
	      };
	      ContentEditableInput.prototype.rememberSelection = function () {
	        var sel = this.getSelection();
	        this.lastAnchorNode = sel.anchorNode;
	        this.lastAnchorOffset = sel.anchorOffset;
	        this.lastFocusNode = sel.focusNode;
	        this.lastFocusOffset = sel.focusOffset;
	      };
	      ContentEditableInput.prototype.selectionInEditor = function () {
	        var sel = this.getSelection();
	        if (!sel.rangeCount) {
	          return false;
	        }
	        var node = sel.getRangeAt(0).commonAncestorContainer;
	        return contains(this.div, node);
	      };
	      ContentEditableInput.prototype.focus = function () {
	        if (this.cm.options.readOnly != "nocursor") {
	          if (!this.selectionInEditor() || activeElt(rootNode(this.div)) != this.div) {
	            this.showSelection(this.prepareSelection(), true);
	          }
	          this.div.focus();
	        }
	      };
	      ContentEditableInput.prototype.blur = function () {
	        this.div.blur();
	      };
	      ContentEditableInput.prototype.getField = function () {
	        return this.div;
	      };
	      ContentEditableInput.prototype.supportsTouch = function () {
	        return true;
	      };
	      ContentEditableInput.prototype.receivedFocus = function () {
	        var this$1$1 = this;
	        var input = this;
	        if (this.selectionInEditor()) {
	          setTimeout(function () {
	            return this$1$1.pollSelection();
	          }, 20);
	        } else {
	          runInOp(this.cm, function () {
	            return input.cm.curOp.selectionChanged = true;
	          });
	        }
	        function poll() {
	          if (input.cm.state.focused) {
	            input.pollSelection();
	            input.polling.set(input.cm.options.pollInterval, poll);
	          }
	        }
	        this.polling.set(this.cm.options.pollInterval, poll);
	      };
	      ContentEditableInput.prototype.selectionChanged = function () {
	        var sel = this.getSelection();
	        return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
	      };
	      ContentEditableInput.prototype.pollSelection = function () {
	        if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) {
	          return;
	        }
	        var sel = this.getSelection(),
	          cm = this.cm;
	        // On Android Chrome (version 56, at least), backspacing into an
	        // uneditable block element will put the cursor in that element,
	        // and then, because it's not editable, hide the virtual keyboard.
	        // Because Android doesn't allow us to actually detect backspace
	        // presses in a sane way, this code checks for when that happens
	        // and simulates a backspace press in this case.
	        if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
	          this.cm.triggerOnKeyDown({
	            type: "keydown",
	            keyCode: 8,
	            preventDefault: Math.abs
	          });
	          this.blur();
	          this.focus();
	          return;
	        }
	        if (this.composing) {
	          return;
	        }
	        this.rememberSelection();
	        var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
	        var head = domToPos(cm, sel.focusNode, sel.focusOffset);
	        if (anchor && head) {
	          runInOp(cm, function () {
	            setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
	            if (anchor.bad || head.bad) {
	              cm.curOp.selectionChanged = true;
	            }
	          });
	        }
	      };
	      ContentEditableInput.prototype.pollContent = function () {
	        if (this.readDOMTimeout != null) {
	          clearTimeout(this.readDOMTimeout);
	          this.readDOMTimeout = null;
	        }
	        var cm = this.cm,
	          display = cm.display,
	          sel = cm.doc.sel.primary();
	        var from = sel.from(),
	          to = sel.to();
	        if (from.ch == 0 && from.line > cm.firstLine()) {
	          from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length);
	        }
	        if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) {
	          to = Pos(to.line + 1, 0);
	        }
	        if (from.line < display.viewFrom || to.line > display.viewTo - 1) {
	          return false;
	        }
	        var fromIndex, fromLine, fromNode;
	        if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
	          fromLine = lineNo(display.view[0].line);
	          fromNode = display.view[0].node;
	        } else {
	          fromLine = lineNo(display.view[fromIndex].line);
	          fromNode = display.view[fromIndex - 1].node.nextSibling;
	        }
	        var toIndex = findViewIndex(cm, to.line);
	        var toLine, toNode;
	        if (toIndex == display.view.length - 1) {
	          toLine = display.viewTo - 1;
	          toNode = display.lineDiv.lastChild;
	        } else {
	          toLine = lineNo(display.view[toIndex + 1].line) - 1;
	          toNode = display.view[toIndex + 1].node.previousSibling;
	        }
	        if (!fromNode) {
	          return false;
	        }
	        var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
	        var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
	        while (newText.length > 1 && oldText.length > 1) {
	          if (lst(newText) == lst(oldText)) {
	            newText.pop();
	            oldText.pop();
	            toLine--;
	          } else if (newText[0] == oldText[0]) {
	            newText.shift();
	            oldText.shift();
	            fromLine++;
	          } else {
	            break;
	          }
	        }
	        var cutFront = 0,
	          cutEnd = 0;
	        var newTop = newText[0],
	          oldTop = oldText[0],
	          maxCutFront = Math.min(newTop.length, oldTop.length);
	        while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) {
	          ++cutFront;
	        }
	        var newBot = lst(newText),
	          oldBot = lst(oldText);
	        var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), oldBot.length - (oldText.length == 1 ? cutFront : 0));
	        while (cutEnd < maxCutEnd && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
	          ++cutEnd;
	        }
	        // Try to move start of change to start of selection if ambiguous
	        if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
	          while (cutFront && cutFront > from.ch && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
	            cutFront--;
	            cutEnd++;
	          }
	        }
	        newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
	        newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
	        var chFrom = Pos(fromLine, cutFront);
	        var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
	        if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
	          replaceRange(cm.doc, newText, chFrom, chTo, "+input");
	          return true;
	        }
	      };
	      ContentEditableInput.prototype.ensurePolled = function () {
	        this.forceCompositionEnd();
	      };
	      ContentEditableInput.prototype.reset = function () {
	        this.forceCompositionEnd();
	      };
	      ContentEditableInput.prototype.forceCompositionEnd = function () {
	        if (!this.composing) {
	          return;
	        }
	        clearTimeout(this.readDOMTimeout);
	        this.composing = null;
	        this.updateFromDOM();
	        this.div.blur();
	        this.div.focus();
	      };
	      ContentEditableInput.prototype.readFromDOMSoon = function () {
	        var this$1$1 = this;
	        if (this.readDOMTimeout != null) {
	          return;
	        }
	        this.readDOMTimeout = setTimeout(function () {
	          this$1$1.readDOMTimeout = null;
	          if (this$1$1.composing) {
	            if (this$1$1.composing.done) {
	              this$1$1.composing = null;
	            } else {
	              return;
	            }
	          }
	          this$1$1.updateFromDOM();
	        }, 80);
	      };
	      ContentEditableInput.prototype.updateFromDOM = function () {
	        var this$1$1 = this;
	        if (this.cm.isReadOnly() || !this.pollContent()) {
	          runInOp(this.cm, function () {
	            return regChange(this$1$1.cm);
	          });
	        }
	      };
	      ContentEditableInput.prototype.setUneditable = function (node) {
	        node.contentEditable = "false";
	      };
	      ContentEditableInput.prototype.onKeyPress = function (e) {
	        if (e.charCode == 0 || this.composing) {
	          return;
	        }
	        e.preventDefault();
	        if (!this.cm.isReadOnly()) {
	          operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
	        }
	      };
	      ContentEditableInput.prototype.readOnlyChanged = function (val) {
	        this.div.contentEditable = String(val != "nocursor");
	      };
	      ContentEditableInput.prototype.onContextMenu = function () {};
	      ContentEditableInput.prototype.resetPosition = function () {};
	      ContentEditableInput.prototype.needsContentAttribute = true;
	      function posToDOM(cm, pos) {
	        var view = findViewForLine(cm, pos.line);
	        if (!view || view.hidden) {
	          return null;
	        }
	        var line = getLine(cm.doc, pos.line);
	        var info = mapFromLineView(view, line, pos.line);
	        var order = getOrder(line, cm.doc.direction),
	          side = "left";
	        if (order) {
	          var partPos = getBidiPartAt(order, pos.ch);
	          side = partPos % 2 ? "right" : "left";
	        }
	        var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
	        result.offset = result.collapse == "right" ? result.end : result.start;
	        return result;
	      }
	      function isInGutter(node) {
	        for (var scan = node; scan; scan = scan.parentNode) {
	          if (/CodeMirror-gutter-wrapper/.test(scan.className)) {
	            return true;
	          }
	        }
	        return false;
	      }
	      function badPos(pos, bad) {
	        if (bad) {
	          pos.bad = true;
	        }
	        return pos;
	      }
	      function domTextBetween(cm, from, to, fromLine, toLine) {
	        var text = "",
	          closing = false,
	          lineSep = cm.doc.lineSeparator(),
	          extraLinebreak = false;
	        function recognizeMarker(id) {
	          return function (marker) {
	            return marker.id == id;
	          };
	        }
	        function close() {
	          if (closing) {
	            text += lineSep;
	            if (extraLinebreak) {
	              text += lineSep;
	            }
	            closing = extraLinebreak = false;
	          }
	        }
	        function addText(str) {
	          if (str) {
	            close();
	            text += str;
	          }
	        }
	        function walk(node) {
	          if (node.nodeType == 1) {
	            var cmText = node.getAttribute("cm-text");
	            if (cmText) {
	              addText(cmText);
	              return;
	            }
	            var markerID = node.getAttribute("cm-marker"),
	              range;
	            if (markerID) {
	              var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
	              if (found.length && (range = found[0].find(0))) {
	                addText(getBetween(cm.doc, range.from, range.to).join(lineSep));
	              }
	              return;
	            }
	            if (node.getAttribute("contenteditable") == "false") {
	              return;
	            }
	            var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
	            if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) {
	              return;
	            }
	            if (isBlock) {
	              close();
	            }
	            for (var i = 0; i < node.childNodes.length; i++) {
	              walk(node.childNodes[i]);
	            }
	            if (/^(pre|p)$/i.test(node.nodeName)) {
	              extraLinebreak = true;
	            }
	            if (isBlock) {
	              closing = true;
	            }
	          } else if (node.nodeType == 3) {
	            addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
	          }
	        }
	        for (;;) {
	          walk(from);
	          if (from == to) {
	            break;
	          }
	          from = from.nextSibling;
	          extraLinebreak = false;
	        }
	        return text;
	      }
	      function domToPos(cm, node, offset) {
	        var lineNode;
	        if (node == cm.display.lineDiv) {
	          lineNode = cm.display.lineDiv.childNodes[offset];
	          if (!lineNode) {
	            return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
	          }
	          node = null;
	          offset = 0;
	        } else {
	          for (lineNode = node;; lineNode = lineNode.parentNode) {
	            if (!lineNode || lineNode == cm.display.lineDiv) {
	              return null;
	            }
	            if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) {
	              break;
	            }
	          }
	        }
	        for (var i = 0; i < cm.display.view.length; i++) {
	          var lineView = cm.display.view[i];
	          if (lineView.node == lineNode) {
	            return locateNodeInLineView(lineView, node, offset);
	          }
	        }
	      }
	      function locateNodeInLineView(lineView, node, offset) {
	        var wrapper = lineView.text.firstChild,
	          bad = false;
	        if (!node || !contains(wrapper, node)) {
	          return badPos(Pos(lineNo(lineView.line), 0), true);
	        }
	        if (node == wrapper) {
	          bad = true;
	          node = wrapper.childNodes[offset];
	          offset = 0;
	          if (!node) {
	            var line = lineView.rest ? lst(lineView.rest) : lineView.line;
	            return badPos(Pos(lineNo(line), line.text.length), bad);
	          }
	        }
	        var textNode = node.nodeType == 3 ? node : null,
	          topNode = node;
	        if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
	          textNode = node.firstChild;
	          if (offset) {
	            offset = textNode.nodeValue.length;
	          }
	        }
	        while (topNode.parentNode != wrapper) {
	          topNode = topNode.parentNode;
	        }
	        var measure = lineView.measure,
	          maps = measure.maps;
	        function find(textNode, topNode, offset) {
	          for (var i = -1; i < (maps ? maps.length : 0); i++) {
	            var map = i < 0 ? measure.map : maps[i];
	            for (var j = 0; j < map.length; j += 3) {
	              var curNode = map[j + 2];
	              if (curNode == textNode || curNode == topNode) {
	                var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
	                var ch = map[j] + offset;
	                if (offset < 0 || curNode != textNode) {
	                  ch = map[j + (offset ? 1 : 0)];
	                }
	                return Pos(line, ch);
	              }
	            }
	          }
	        }
	        var found = find(textNode, topNode, offset);
	        if (found) {
	          return badPos(found, bad);
	        }

	        // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
	        for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
	          found = find(after, after.firstChild, 0);
	          if (found) {
	            return badPos(Pos(found.line, found.ch - dist), bad);
	          } else {
	            dist += after.textContent.length;
	          }
	        }
	        for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
	          found = find(before, before.firstChild, -1);
	          if (found) {
	            return badPos(Pos(found.line, found.ch + dist$1), bad);
	          } else {
	            dist$1 += before.textContent.length;
	          }
	        }
	      }

	      // TEXTAREA INPUT STYLE

	      var TextareaInput = function (cm) {
	        this.cm = cm;
	        // See input.poll and input.reset
	        this.prevInput = "";

	        // Flag that indicates whether we expect input to appear real soon
	        // now (after some event like 'keypress' or 'input') and are
	        // polling intensively.
	        this.pollingFast = false;
	        // Self-resetting timeout for the poller
	        this.polling = new Delayed();
	        // Used to work around IE issue with selection being forgotten when focus moves away from textarea
	        this.hasSelection = false;
	        this.composing = null;
	        this.resetting = false;
	      };
	      TextareaInput.prototype.init = function (display) {
	        var this$1$1 = this;
	        var input = this,
	          cm = this.cm;
	        this.createField(display);
	        var te = this.textarea;
	        display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);

	        // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
	        if (ios) {
	          te.style.width = "0px";
	        }
	        on(te, "input", function () {
	          if (ie && ie_version >= 9 && this$1$1.hasSelection) {
	            this$1$1.hasSelection = null;
	          }
	          input.poll();
	        });
	        on(te, "paste", function (e) {
	          if (signalDOMEvent(cm, e) || handlePaste(e, cm)) {
	            return;
	          }
	          cm.state.pasteIncoming = +new Date();
	          input.fastPoll();
	        });
	        function prepareCopyCut(e) {
	          if (signalDOMEvent(cm, e)) {
	            return;
	          }
	          if (cm.somethingSelected()) {
	            setLastCopied({
	              lineWise: false,
	              text: cm.getSelections()
	            });
	          } else if (!cm.options.lineWiseCopyCut) {
	            return;
	          } else {
	            var ranges = copyableRanges(cm);
	            setLastCopied({
	              lineWise: true,
	              text: ranges.text
	            });
	            if (e.type == "cut") {
	              cm.setSelections(ranges.ranges, null, sel_dontScroll);
	            } else {
	              input.prevInput = "";
	              te.value = ranges.text.join("\n");
	              selectInput(te);
	            }
	          }
	          if (e.type == "cut") {
	            cm.state.cutIncoming = +new Date();
	          }
	        }
	        on(te, "cut", prepareCopyCut);
	        on(te, "copy", prepareCopyCut);
	        on(display.scroller, "paste", function (e) {
	          if (eventInWidget(display, e) || signalDOMEvent(cm, e)) {
	            return;
	          }
	          if (!te.dispatchEvent) {
	            cm.state.pasteIncoming = +new Date();
	            input.focus();
	            return;
	          }

	          // Pass the `paste` event to the textarea so it's handled by its event listener.
	          var event = new Event("paste");
	          event.clipboardData = e.clipboardData;
	          te.dispatchEvent(event);
	        });

	        // Prevent normal selection in the editor (we handle our own)
	        on(display.lineSpace, "selectstart", function (e) {
	          if (!eventInWidget(display, e)) {
	            e_preventDefault(e);
	          }
	        });
	        on(te, "compositionstart", function () {
	          var start = cm.getCursor("from");
	          if (input.composing) {
	            input.composing.range.clear();
	          }
	          input.composing = {
	            start: start,
	            range: cm.markText(start, cm.getCursor("to"), {
	              className: "CodeMirror-composing"
	            })
	          };
	        });
	        on(te, "compositionend", function () {
	          if (input.composing) {
	            input.poll();
	            input.composing.range.clear();
	            input.composing = null;
	          }
	        });
	      };
	      TextareaInput.prototype.createField = function (_display) {
	        // Wraps and hides input textarea
	        this.wrapper = hiddenTextarea();
	        // The semihidden textarea that is focused when the editor is
	        // focused, and receives input.
	        this.textarea = this.wrapper.firstChild;
	        var opts = this.cm.options;
	        disableBrowserMagic(this.textarea, opts.spellcheck, opts.autocorrect, opts.autocapitalize);
	      };
	      TextareaInput.prototype.screenReaderLabelChanged = function (label) {
	        // Label for screenreaders, accessibility
	        if (label) {
	          this.textarea.setAttribute('aria-label', label);
	        } else {
	          this.textarea.removeAttribute('aria-label');
	        }
	      };
	      TextareaInput.prototype.prepareSelection = function () {
	        // Redraw the selection and/or cursor
	        var cm = this.cm,
	          display = cm.display,
	          doc = cm.doc;
	        var result = prepareSelection(cm);

	        // Move the hidden textarea near the cursor to prevent scrolling artifacts
	        if (cm.options.moveInputWithCursor) {
	          var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
	          var wrapOff = display.wrapper.getBoundingClientRect(),
	            lineOff = display.lineDiv.getBoundingClientRect();
	          result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, headPos.top + lineOff.top - wrapOff.top));
	          result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, headPos.left + lineOff.left - wrapOff.left));
	        }
	        return result;
	      };
	      TextareaInput.prototype.showSelection = function (drawn) {
	        var cm = this.cm,
	          display = cm.display;
	        removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
	        removeChildrenAndAdd(display.selectionDiv, drawn.selection);
	        if (drawn.teTop != null) {
	          this.wrapper.style.top = drawn.teTop + "px";
	          this.wrapper.style.left = drawn.teLeft + "px";
	        }
	      };

	      // Reset the input to correspond to the selection (or to be empty,
	      // when not typing and nothing is selected)
	      TextareaInput.prototype.reset = function (typing) {
	        if (this.contextMenuPending || this.composing && typing) {
	          return;
	        }
	        var cm = this.cm;
	        this.resetting = true;
	        if (cm.somethingSelected()) {
	          this.prevInput = "";
	          var content = cm.getSelection();
	          this.textarea.value = content;
	          if (cm.state.focused) {
	            selectInput(this.textarea);
	          }
	          if (ie && ie_version >= 9) {
	            this.hasSelection = content;
	          }
	        } else if (!typing) {
	          this.prevInput = this.textarea.value = "";
	          if (ie && ie_version >= 9) {
	            this.hasSelection = null;
	          }
	        }
	        this.resetting = false;
	      };
	      TextareaInput.prototype.getField = function () {
	        return this.textarea;
	      };
	      TextareaInput.prototype.supportsTouch = function () {
	        return false;
	      };
	      TextareaInput.prototype.focus = function () {
	        if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt(rootNode(this.textarea)) != this.textarea)) {
	          try {
	            this.textarea.focus();
	          } catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
	        }
	      };
	      TextareaInput.prototype.blur = function () {
	        this.textarea.blur();
	      };
	      TextareaInput.prototype.resetPosition = function () {
	        this.wrapper.style.top = this.wrapper.style.left = 0;
	      };
	      TextareaInput.prototype.receivedFocus = function () {
	        this.slowPoll();
	      };

	      // Poll for input changes, using the normal rate of polling. This
	      // runs as long as the editor is focused.
	      TextareaInput.prototype.slowPoll = function () {
	        var this$1$1 = this;
	        if (this.pollingFast) {
	          return;
	        }
	        this.polling.set(this.cm.options.pollInterval, function () {
	          this$1$1.poll();
	          if (this$1$1.cm.state.focused) {
	            this$1$1.slowPoll();
	          }
	        });
	      };

	      // When an event has just come in that is likely to add or change
	      // something in the input textarea, we poll faster, to ensure that
	      // the change appears on the screen quickly.
	      TextareaInput.prototype.fastPoll = function () {
	        var missed = false,
	          input = this;
	        input.pollingFast = true;
	        function p() {
	          var changed = input.poll();
	          if (!changed && !missed) {
	            missed = true;
	            input.polling.set(60, p);
	          } else {
	            input.pollingFast = false;
	            input.slowPoll();
	          }
	        }
	        input.polling.set(20, p);
	      };

	      // Read input from the textarea, and update the document to match.
	      // When something is selected, it is present in the textarea, and
	      // selected (unless it is huge, in which case a placeholder is
	      // used). When nothing is selected, the cursor sits after previously
	      // seen text (can be empty), which is stored in prevInput (we must
	      // not reset the textarea when typing, because that breaks IME).
	      TextareaInput.prototype.poll = function () {
	        var this$1$1 = this;
	        var cm = this.cm,
	          input = this.textarea,
	          prevInput = this.prevInput;
	        // Since this is called a *lot*, try to bail out as cheaply as
	        // possible when it is clear that nothing happened. hasSelection
	        // will be the case when there is a lot of text in the textarea,
	        // in which case reading its value would be expensive.
	        if (this.contextMenuPending || this.resetting || !cm.state.focused || hasSelection(input) && !prevInput && !this.composing || cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) {
	          return false;
	        }
	        var text = input.value;
	        // If nothing changed, bail.
	        if (text == prevInput && !cm.somethingSelected()) {
	          return false;
	        }
	        // Work around nonsensical selection resetting in IE9/10, and
	        // inexplicable appearance of private area unicode characters on
	        // some key combos in Mac (#2689).
	        if (ie && ie_version >= 9 && this.hasSelection === text || mac && /[\uf700-\uf7ff]/.test(text)) {
	          cm.display.input.reset();
	          return false;
	        }
	        if (cm.doc.sel == cm.display.selForContextMenu) {
	          var first = text.charCodeAt(0);
	          if (first == 0x200b && !prevInput) {
	            prevInput = "\u200b";
	          }
	          if (first == 0x21da) {
	            this.reset();
	            return this.cm.execCommand("undo");
	          }
	        }
	        // Find the part of the input that is actually new
	        var same = 0,
	          l = Math.min(prevInput.length, text.length);
	        while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) {
	          ++same;
	        }
	        runInOp(cm, function () {
	          applyTextInput(cm, text.slice(same), prevInput.length - same, null, this$1$1.composing ? "*compose" : null);

	          // Don't leave long text in the textarea, since it makes further polling slow
	          if (text.length > 1000 || text.indexOf("\n") > -1) {
	            input.value = this$1$1.prevInput = "";
	          } else {
	            this$1$1.prevInput = text;
	          }
	          if (this$1$1.composing) {
	            this$1$1.composing.range.clear();
	            this$1$1.composing.range = cm.markText(this$1$1.composing.start, cm.getCursor("to"), {
	              className: "CodeMirror-composing"
	            });
	          }
	        });
	        return true;
	      };
	      TextareaInput.prototype.ensurePolled = function () {
	        if (this.pollingFast && this.poll()) {
	          this.pollingFast = false;
	        }
	      };
	      TextareaInput.prototype.onKeyPress = function () {
	        if (ie && ie_version >= 9) {
	          this.hasSelection = null;
	        }
	        this.fastPoll();
	      };
	      TextareaInput.prototype.onContextMenu = function (e) {
	        var input = this,
	          cm = input.cm,
	          display = cm.display,
	          te = input.textarea;
	        if (input.contextMenuPending) {
	          input.contextMenuPending();
	        }
	        var pos = posFromMouse(cm, e),
	          scrollPos = display.scroller.scrollTop;
	        if (!pos || presto) {
	          return;
	        } // Opera is difficult.

	        // Reset the current text selection only if the click is done outside of the selection
	        // and 'resetSelectionOnContextMenu' option is true.
	        var reset = cm.options.resetSelectionOnContextMenu;
	        if (reset && cm.doc.sel.contains(pos) == -1) {
	          operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
	        }
	        var oldCSS = te.style.cssText,
	          oldWrapperCSS = input.wrapper.style.cssText;
	        var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
	        input.wrapper.style.cssText = "position: static";
	        te.style.cssText = "position: absolute; width: 30px; height: 30px;\n      top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n      z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n      outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
	        var oldScrollY;
	        if (webkit) {
	          oldScrollY = te.ownerDocument.defaultView.scrollY;
	        } // Work around Chrome issue (#2712)
	        display.input.focus();
	        if (webkit) {
	          te.ownerDocument.defaultView.scrollTo(null, oldScrollY);
	        }
	        display.input.reset();
	        // Adds "Select all" to context menu in FF
	        if (!cm.somethingSelected()) {
	          te.value = input.prevInput = " ";
	        }
	        input.contextMenuPending = rehide;
	        display.selForContextMenu = cm.doc.sel;
	        clearTimeout(display.detectingSelectAll);

	        // Select-all will be greyed out if there's nothing to select, so
	        // this adds a zero-width space so that we can later check whether
	        // it got selected.
	        function prepareSelectAllHack() {
	          if (te.selectionStart != null) {
	            var selected = cm.somethingSelected();
	            var extval = "\u200b" + (selected ? te.value : "");
	            te.value = "\u21da"; // Used to catch context-menu undo
	            te.value = extval;
	            input.prevInput = selected ? "" : "\u200b";
	            te.selectionStart = 1;
	            te.selectionEnd = extval.length;
	            // Re-set this, in case some other handler touched the
	            // selection in the meantime.
	            display.selForContextMenu = cm.doc.sel;
	          }
	        }
	        function rehide() {
	          if (input.contextMenuPending != rehide) {
	            return;
	          }
	          input.contextMenuPending = false;
	          input.wrapper.style.cssText = oldWrapperCSS;
	          te.style.cssText = oldCSS;
	          if (ie && ie_version < 9) {
	            display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
	          }

	          // Try to detect the user choosing select-all
	          if (te.selectionStart != null) {
	            if (!ie || ie && ie_version < 9) {
	              prepareSelectAllHack();
	            }
	            var i = 0,
	              poll = function () {
	                if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && te.selectionEnd > 0 && input.prevInput == "\u200b") {
	                  operation(cm, selectAll)(cm);
	                } else if (i++ < 10) {
	                  display.detectingSelectAll = setTimeout(poll, 500);
	                } else {
	                  display.selForContextMenu = null;
	                  display.input.reset();
	                }
	              };
	            display.detectingSelectAll = setTimeout(poll, 200);
	          }
	        }
	        if (ie && ie_version >= 9) {
	          prepareSelectAllHack();
	        }
	        if (captureRightClick) {
	          e_stop(e);
	          var mouseup = function () {
	            off(window, "mouseup", mouseup);
	            setTimeout(rehide, 20);
	          };
	          on(window, "mouseup", mouseup);
	        } else {
	          setTimeout(rehide, 50);
	        }
	      };
	      TextareaInput.prototype.readOnlyChanged = function (val) {
	        if (!val) {
	          this.reset();
	        }
	        this.textarea.disabled = val == "nocursor";
	        this.textarea.readOnly = !!val;
	      };
	      TextareaInput.prototype.setUneditable = function () {};
	      TextareaInput.prototype.needsContentAttribute = false;
	      function fromTextArea(textarea, options) {
	        options = options ? copyObj(options) : {};
	        options.value = textarea.value;
	        if (!options.tabindex && textarea.tabIndex) {
	          options.tabindex = textarea.tabIndex;
	        }
	        if (!options.placeholder && textarea.placeholder) {
	          options.placeholder = textarea.placeholder;
	        }
	        // Set autofocus to true if this textarea is focused, or if it has
	        // autofocus and no other element is focused.
	        if (options.autofocus == null) {
	          var hasFocus = activeElt(rootNode(textarea));
	          options.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body;
	        }
	        function save() {
	          textarea.value = cm.getValue();
	        }
	        var realSubmit;
	        if (textarea.form) {
	          on(textarea.form, "submit", save);
	          // Deplorable hack to make the submit method do the right thing.
	          if (!options.leaveSubmitMethodAlone) {
	            var form = textarea.form;
	            realSubmit = form.submit;
	            try {
	              var wrappedSubmit = form.submit = function () {
	                save();
	                form.submit = realSubmit;
	                form.submit();
	                form.submit = wrappedSubmit;
	              };
	            } catch (e) {}
	          }
	        }
	        options.finishInit = function (cm) {
	          cm.save = save;
	          cm.getTextArea = function () {
	            return textarea;
	          };
	          cm.toTextArea = function () {
	            cm.toTextArea = isNaN; // Prevent this from being ran twice
	            save();
	            textarea.parentNode.removeChild(cm.getWrapperElement());
	            textarea.style.display = "";
	            if (textarea.form) {
	              off(textarea.form, "submit", save);
	              if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function") {
	                textarea.form.submit = realSubmit;
	              }
	            }
	          };
	        };
	        textarea.style.display = "none";
	        var cm = CodeMirror(function (node) {
	          return textarea.parentNode.insertBefore(node, textarea.nextSibling);
	        }, options);
	        return cm;
	      }
	      function addLegacyProps(CodeMirror) {
	        CodeMirror.off = off;
	        CodeMirror.on = on;
	        CodeMirror.wheelEventPixels = wheelEventPixels;
	        CodeMirror.Doc = Doc;
	        CodeMirror.splitLines = splitLinesAuto;
	        CodeMirror.countColumn = countColumn;
	        CodeMirror.findColumn = findColumn;
	        CodeMirror.isWordChar = isWordCharBasic;
	        CodeMirror.Pass = Pass;
	        CodeMirror.signal = signal;
	        CodeMirror.Line = Line;
	        CodeMirror.changeEnd = changeEnd;
	        CodeMirror.scrollbarModel = scrollbarModel;
	        CodeMirror.Pos = Pos;
	        CodeMirror.cmpPos = cmp;
	        CodeMirror.modes = modes;
	        CodeMirror.mimeModes = mimeModes;
	        CodeMirror.resolveMode = resolveMode;
	        CodeMirror.getMode = getMode;
	        CodeMirror.modeExtensions = modeExtensions;
	        CodeMirror.extendMode = extendMode;
	        CodeMirror.copyState = copyState;
	        CodeMirror.startState = startState;
	        CodeMirror.innerMode = innerMode;
	        CodeMirror.commands = commands;
	        CodeMirror.keyMap = keyMap;
	        CodeMirror.keyName = keyName;
	        CodeMirror.isModifierKey = isModifierKey;
	        CodeMirror.lookupKey = lookupKey;
	        CodeMirror.normalizeKeyMap = normalizeKeyMap;
	        CodeMirror.StringStream = StringStream;
	        CodeMirror.SharedTextMarker = SharedTextMarker;
	        CodeMirror.TextMarker = TextMarker;
	        CodeMirror.LineWidget = LineWidget;
	        CodeMirror.e_preventDefault = e_preventDefault;
	        CodeMirror.e_stopPropagation = e_stopPropagation;
	        CodeMirror.e_stop = e_stop;
	        CodeMirror.addClass = addClass;
	        CodeMirror.contains = contains;
	        CodeMirror.rmClass = rmClass;
	        CodeMirror.keyNames = keyNames;
	      }

	      // EDITOR CONSTRUCTOR

	      defineOptions(CodeMirror);
	      addEditorMethods(CodeMirror);

	      // Set up methods on CodeMirror's prototype to redirect to the editor's document.
	      var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
	      for (var prop in Doc.prototype) {
	        if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) {
	          CodeMirror.prototype[prop] = function (method) {
	            return function () {
	              return method.apply(this.doc, arguments);
	            };
	          }(Doc.prototype[prop]);
	        }
	      }
	      eventMixin(Doc);
	      CodeMirror.inputStyles = {
	        "textarea": TextareaInput,
	        "contenteditable": ContentEditableInput
	      };

	      // Extra arguments are stored as the mode's dependencies, which is
	      // used by (legacy) mechanisms like loadmode.js to automatically
	      // load a mode. (Preferred mechanism is the require/define calls.)
	      CodeMirror.defineMode = function (name /*, mode, …*/) {
	        if (!CodeMirror.defaults.mode && name != "null") {
	          CodeMirror.defaults.mode = name;
	        }
	        defineMode.apply(this, arguments);
	      };
	      CodeMirror.defineMIME = defineMIME;

	      // Minimal default mode.
	      CodeMirror.defineMode("null", function () {
	        return {
	          token: function (stream) {
	            return stream.skipToEnd();
	          }
	        };
	      });
	      CodeMirror.defineMIME("text/plain", "null");

	      // EXTENSIONS

	      CodeMirror.defineExtension = function (name, func) {
	        CodeMirror.prototype[name] = func;
	      };
	      CodeMirror.defineDocExtension = function (name, func) {
	        Doc.prototype[name] = func;
	      };
	      CodeMirror.fromTextArea = fromTextArea;
	      addLegacyProps(CodeMirror);
	      CodeMirror.version = "5.65.21";
	      return CodeMirror;
	    });
	  })(codemirror$1);
	  return codemirror$1.exports;
	}

	var codemirrorExports = requireCodemirror();
	const CodeMirror = /*@__PURE__*/getDefaultExportFromCjs(codemirrorExports);

	var placeholder = {exports: {}};

	var hasRequiredPlaceholder;
	function requirePlaceholder() {
	  if (hasRequiredPlaceholder) return placeholder.exports;
	  hasRequiredPlaceholder = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {
	      CodeMirror.defineOption("placeholder", "", function (cm, val, old) {
	        var prev = old && old != CodeMirror.Init;
	        if (val && !prev) {
	          cm.on("blur", onBlur);
	          cm.on("change", onChange);
	          cm.on("swapDoc", onChange);
	          CodeMirror.on(cm.getInputField(), "compositionupdate", cm.state.placeholderCompose = function () {
	            onComposition(cm);
	          });
	          onChange(cm);
	        } else if (!val && prev) {
	          cm.off("blur", onBlur);
	          cm.off("change", onChange);
	          cm.off("swapDoc", onChange);
	          CodeMirror.off(cm.getInputField(), "compositionupdate", cm.state.placeholderCompose);
	          clearPlaceholder(cm);
	          var wrapper = cm.getWrapperElement();
	          wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
	        }
	        if (val && !cm.hasFocus()) onBlur(cm);
	      });
	      function clearPlaceholder(cm) {
	        if (cm.state.placeholder) {
	          cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
	          cm.state.placeholder = null;
	        }
	      }
	      function setPlaceholder(cm) {
	        clearPlaceholder(cm);
	        var elt = cm.state.placeholder = document.createElement("pre");
	        elt.style.cssText = "height: 0; overflow: visible";
	        elt.style.direction = cm.getOption("direction");
	        elt.className = "CodeMirror-placeholder CodeMirror-line-like";
	        var placeHolder = cm.getOption("placeholder");
	        if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder);
	        elt.appendChild(placeHolder);
	        cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
	      }
	      function onComposition(cm) {
	        setTimeout(function () {
	          var empty = false;
	          if (cm.lineCount() == 1) {
	            var input = cm.getInputField();
	            empty = input.nodeName == "TEXTAREA" ? !cm.getLine(0).length : !/[^\u200b]/.test(input.querySelector(".CodeMirror-line").textContent);
	          }
	          if (empty) setPlaceholder(cm);else clearPlaceholder(cm);
	        }, 20);
	      }
	      function onBlur(cm) {
	        if (isEmpty(cm)) setPlaceholder(cm);
	      }
	      function onChange(cm) {
	        var wrapper = cm.getWrapperElement(),
	          empty = isEmpty(cm);
	        wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
	        if (empty) setPlaceholder(cm);else clearPlaceholder(cm);
	      }
	      function isEmpty(cm) {
	        return cm.lineCount() === 1 && cm.getLine(0) === "";
	      }
	    });
	  })();
	  return placeholder.exports;
	}

	requirePlaceholder();

	var continuelist = {exports: {}};

	var hasRequiredContinuelist;
	function requireContinuelist() {
	  if (hasRequiredContinuelist) return continuelist.exports;
	  hasRequiredContinuelist = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      var listRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]\s|[*+-]\s|(\d+)([.)]))(\s*)/,
	        emptyListRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]|[*+-]|(\d+)[.)])(\s*)$/,
	        unorderedListRE = /[*+-]\s/;
	      CodeMirror.commands.newlineAndIndentContinueMarkdownList = function (cm) {
	        if (cm.getOption("disableInput")) return CodeMirror.Pass;
	        var ranges = cm.listSelections(),
	          replacements = [];
	        for (var i = 0; i < ranges.length; i++) {
	          var pos = ranges[i].head;

	          // If we're not in Markdown mode, fall back to normal newlineAndIndent
	          var eolState = cm.getStateAfter(pos.line);
	          var inner = CodeMirror.innerMode(cm.getMode(), eolState);
	          if (inner.mode.name !== "markdown" && inner.mode.helperType !== "markdown") {
	            cm.execCommand("newlineAndIndent");
	            return;
	          } else {
	            eolState = inner.state;
	          }
	          var inList = eolState.list !== false;
	          var inQuote = eolState.quote !== 0;
	          var line = cm.getLine(pos.line),
	            match = listRE.exec(line);
	          var cursorBeforeBullet = /^\s*$/.test(line.slice(0, pos.ch));
	          if (!ranges[i].empty() || !inList && !inQuote || !match || cursorBeforeBullet) {
	            cm.execCommand("newlineAndIndent");
	            return;
	          }
	          if (emptyListRE.test(line)) {
	            var endOfQuote = inQuote && />\s*$/.test(line);
	            var endOfList = !/>\s*$/.test(line);
	            if (endOfQuote || endOfList) cm.replaceRange("", {
	              line: pos.line,
	              ch: 0
	            }, {
	              line: pos.line,
	              ch: pos.ch + 1
	            });
	            replacements[i] = "\n";
	          } else {
	            var indent = match[1],
	              after = match[5];
	            var numbered = !(unorderedListRE.test(match[2]) || match[2].indexOf(">") >= 0);
	            var bullet = numbered ? parseInt(match[3], 10) + 1 + match[4] : match[2].replace("x", " ");
	            replacements[i] = "\n" + indent + bullet + after;
	            if (numbered) incrementRemainingMarkdownListNumbers(cm, pos);
	          }
	        }
	        cm.replaceSelections(replacements);
	      };

	      // Auto-updating Markdown list numbers when a new item is added to the
	      // middle of a list
	      function incrementRemainingMarkdownListNumbers(cm, pos) {
	        var startLine = pos.line,
	          lookAhead = 0,
	          skipCount = 0;
	        var startItem = listRE.exec(cm.getLine(startLine)),
	          startIndent = startItem[1];
	        do {
	          lookAhead += 1;
	          var nextLineNumber = startLine + lookAhead;
	          var nextLine = cm.getLine(nextLineNumber),
	            nextItem = listRE.exec(nextLine);
	          if (nextItem) {
	            var nextIndent = nextItem[1];
	            var newNumber = parseInt(startItem[3], 10) + lookAhead - skipCount;
	            var nextNumber = parseInt(nextItem[3], 10),
	              itemNumber = nextNumber;
	            if (startIndent === nextIndent && !isNaN(nextNumber)) {
	              if (newNumber === nextNumber) itemNumber = nextNumber + 1;
	              if (newNumber > nextNumber) itemNumber = newNumber + 1;
	              cm.replaceRange(nextLine.replace(listRE, nextIndent + itemNumber + nextItem[4] + nextItem[5]), {
	                line: nextLineNumber,
	                ch: 0
	              }, {
	                line: nextLineNumber,
	                ch: nextLine.length
	              });
	            } else {
	              if (startIndent.length > nextIndent.length) return;
	              // This doesn't run if the next line immediately indents, as it is
	              // not clear of the users intention (new indented item or same level)
	              if (startIndent.length < nextIndent.length && lookAhead === 1) return;
	              skipCount += 1;
	            }
	          }
	        } while (nextItem);
	      }
	    });
	  })();
	  return continuelist.exports;
	}

	requireContinuelist();

	var matchbrackets = {exports: {}};

	var hasRequiredMatchbrackets;
	function requireMatchbrackets() {
	  if (hasRequiredMatchbrackets) return matchbrackets.exports;
	  hasRequiredMatchbrackets = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {
	      var ie_lt8 = /MSIE \d/.test(navigator.userAgent) && (document.documentMode == null || document.documentMode < 8);
	      var Pos = CodeMirror.Pos;
	      var matching = {
	        "(": ")>",
	        ")": "(<",
	        "[": "]>",
	        "]": "[<",
	        "{": "}>",
	        "}": "{<",
	        "<": ">>",
	        ">": "<<"
	      };
	      function bracketRegex(config) {
	        return config && config.bracketRegex || /[(){}[\]]/;
	      }
	      function findMatchingBracket(cm, where, config) {
	        var line = cm.getLineHandle(where.line),
	          pos = where.ch - 1;
	        var afterCursor = config && config.afterCursor;
	        if (afterCursor == null) afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className);
	        var re = bracketRegex(config);

	        // A cursor is defined as between two characters, but in vim command mode
	        // (i.e. not insert mode), the cursor is visually represented as a
	        // highlighted box on top of the 2nd character. Otherwise, we allow matches
	        // from before or after the cursor.
	        var match = !afterCursor && pos >= 0 && re.test(line.text.charAt(pos)) && matching[line.text.charAt(pos)] || re.test(line.text.charAt(pos + 1)) && matching[line.text.charAt(++pos)];
	        if (!match) return null;
	        var dir = match.charAt(1) == ">" ? 1 : -1;
	        if (config && config.strict && dir > 0 != (pos == where.ch)) return null;
	        var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));
	        var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style, config);
	        if (found == null) return null;
	        return {
	          from: Pos(where.line, pos),
	          to: found && found.pos,
	          match: found && found.ch == match.charAt(0),
	          forward: dir > 0
	        };
	      }

	      // bracketRegex is used to specify which type of bracket to scan
	      // should be a regexp, e.g. /[[\]]/
	      //
	      // Note: If "where" is on an open bracket, then this bracket is ignored.
	      //
	      // Returns false when no bracket was found, null when it reached
	      // maxScanLines and gave up
	      function scanForBracket(cm, where, dir, style, config) {
	        var maxScanLen = config && config.maxScanLineLength || 10000;
	        var maxScanLines = config && config.maxScanLines || 1000;
	        var stack = [];
	        var re = bracketRegex(config);
	        var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1) : Math.max(cm.firstLine() - 1, where.line - maxScanLines);
	        for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {
	          var line = cm.getLine(lineNo);
	          if (!line) continue;
	          var pos = dir > 0 ? 0 : line.length - 1,
	            end = dir > 0 ? line.length : -1;
	          if (line.length > maxScanLen) continue;
	          if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);
	          for (; pos != end; pos += dir) {
	            var ch = line.charAt(pos);
	            if (re.test(ch) && (style === undefined || (cm.getTokenTypeAt(Pos(lineNo, pos + 1)) || "") == (style || ""))) {
	              var match = matching[ch];
	              if (match && match.charAt(1) == ">" == dir > 0) stack.push(ch);else if (!stack.length) return {
	                pos: Pos(lineNo, pos),
	                ch: ch
	              };else stack.pop();
	            }
	          }
	        }
	        return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;
	      }
	      function matchBrackets(cm, autoclear, config) {
	        // Disable brace matching in long lines, since it'll cause hugely slow updates
	        var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000,
	          highlightNonMatching = config && config.highlightNonMatching;
	        var marks = [],
	          ranges = cm.listSelections();
	        for (var i = 0; i < ranges.length; i++) {
	          var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config);
	          if (match && (match.match || highlightNonMatching !== false) && cm.getLine(match.from.line).length <= maxHighlightLen) {
	            var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
	            marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {
	              className: style
	            }));
	            if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen) marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {
	              className: style
	            }));
	          }
	        }
	        if (marks.length) {
	          // Kludge to work around the IE bug from issue #1193, where text
	          // input stops going to the textarea whenever this fires.
	          if (ie_lt8 && cm.state.focused) cm.focus();
	          var clear = function () {
	            cm.operation(function () {
	              for (var i = 0; i < marks.length; i++) marks[i].clear();
	            });
	          };
	          if (autoclear) setTimeout(clear, 800);else return clear;
	        }
	      }
	      function doMatchBrackets(cm) {
	        cm.operation(function () {
	          if (cm.state.matchBrackets.currentlyHighlighted) {
	            cm.state.matchBrackets.currentlyHighlighted();
	            cm.state.matchBrackets.currentlyHighlighted = null;
	          }
	          cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);
	        });
	      }
	      function clearHighlighted(cm) {
	        if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) {
	          cm.state.matchBrackets.currentlyHighlighted();
	          cm.state.matchBrackets.currentlyHighlighted = null;
	        }
	      }
	      CodeMirror.defineOption("matchBrackets", false, function (cm, val, old) {
	        if (old && old != CodeMirror.Init) {
	          cm.off("cursorActivity", doMatchBrackets);
	          cm.off("focus", doMatchBrackets);
	          cm.off("blur", clearHighlighted);
	          clearHighlighted(cm);
	        }
	        if (val) {
	          cm.state.matchBrackets = typeof val == "object" ? val : {};
	          cm.on("cursorActivity", doMatchBrackets);
	          cm.on("focus", doMatchBrackets);
	          cm.on("blur", clearHighlighted);
	        }
	      });
	      CodeMirror.defineExtension("matchBrackets", function () {
	        matchBrackets(this, true);
	      });
	      CodeMirror.defineExtension("findMatchingBracket", function (pos, config, oldConfig) {
	        // Backwards-compatibility kludge
	        if (oldConfig || typeof config == "boolean") {
	          if (!oldConfig) {
	            config = config ? {
	              strict: true
	            } : null;
	          } else {
	            oldConfig.strict = config;
	            config = oldConfig;
	          }
	        }
	        return findMatchingBracket(this, pos, config);
	      });
	      CodeMirror.defineExtension("scanForBracket", function (pos, dir, style, config) {
	        return scanForBracket(this, pos, dir, style, config);
	      });
	    });
	  })();
	  return matchbrackets.exports;
	}

	requireMatchbrackets();

	var jsonLint = {exports: {}};

	var hasRequiredJsonLint;
	function requireJsonLint() {
	  if (hasRequiredJsonLint) return jsonLint.exports;
	  hasRequiredJsonLint = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    // Depends on jsonlint.js from https://github.com/zaach/jsonlint

	    // declare global: jsonlint

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      CodeMirror.registerHelper("lint", "json", function (text) {
	        var found = [];
	        if (!window.jsonlint) {
	          if (window.console) {
	            window.console.error("Error: window.jsonlint not defined, CodeMirror JSON linting cannot run.");
	          }
	          return found;
	        }
	        // for jsonlint's web dist jsonlint is exported as an object with a single property parser, of which parseError
	        // is a subproperty
	        var jsonlint = window.jsonlint.parser || window.jsonlint;
	        jsonlint.parseError = function (str, hash) {
	          var loc = hash.loc;
	          found.push({
	            from: CodeMirror.Pos(loc.first_line - 1, loc.first_column),
	            to: CodeMirror.Pos(loc.last_line - 1, loc.last_column),
	            message: str
	          });
	        };
	        try {
	          jsonlint.parse(text);
	        } catch (e) {}
	        return found;
	      });
	    });
	  })();
	  return jsonLint.exports;
	}

	requireJsonLint();

	var lint = {exports: {}};

	var hasRequiredLint;
	function requireLint() {
	  if (hasRequiredLint) return lint.exports;
	  hasRequiredLint = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      var GUTTER_ID = "CodeMirror-lint-markers";
	      var LINT_LINE_ID = "CodeMirror-lint-line-";
	      function showTooltip(cm, e, content) {
	        var tt = document.createElement("div");
	        tt.className = "CodeMirror-lint-tooltip cm-s-" + cm.options.theme;
	        tt.appendChild(content.cloneNode(true));
	        if (cm.state.lint.options.selfContain) cm.getWrapperElement().appendChild(tt);else document.body.appendChild(tt);
	        function position(e) {
	          if (!tt.parentNode) return CodeMirror.off(document, "mousemove", position);
	          var top = Math.max(0, e.clientY - tt.offsetHeight - 5);
	          var left = Math.max(0, Math.min(e.clientX + 5, tt.ownerDocument.defaultView.innerWidth - tt.offsetWidth));
	          tt.style.top = top + "px";
	          tt.style.left = left + "px";
	        }
	        CodeMirror.on(document, "mousemove", position);
	        position(e);
	        if (tt.style.opacity != null) tt.style.opacity = 1;
	        return tt;
	      }
	      function rm(elt) {
	        if (elt.parentNode) elt.parentNode.removeChild(elt);
	      }
	      function hideTooltip(tt) {
	        if (!tt.parentNode) return;
	        if (tt.style.opacity == null) rm(tt);
	        tt.style.opacity = 0;
	        setTimeout(function () {
	          rm(tt);
	        }, 600);
	      }
	      function showTooltipFor(cm, e, content, node) {
	        var tooltip = showTooltip(cm, e, content);
	        function hide() {
	          CodeMirror.off(node, "mouseout", hide);
	          if (tooltip) {
	            hideTooltip(tooltip);
	            tooltip = null;
	          }
	        }
	        var poll = setInterval(function () {
	          if (tooltip) for (var n = node;; n = n.parentNode) {
	            if (n && n.nodeType == 11) n = n.host;
	            if (n == document.body) return;
	            if (!n) {
	              hide();
	              break;
	            }
	          }
	          if (!tooltip) return clearInterval(poll);
	        }, 400);
	        CodeMirror.on(node, "mouseout", hide);
	      }
	      function LintState(cm, conf, hasGutter) {
	        this.marked = [];
	        if (conf instanceof Function) conf = {
	          getAnnotations: conf
	        };
	        if (!conf || conf === true) conf = {};
	        this.options = {};
	        this.linterOptions = conf.options || {};
	        for (var prop in defaults) this.options[prop] = defaults[prop];
	        for (var prop in conf) {
	          if (defaults.hasOwnProperty(prop)) {
	            if (conf[prop] != null) this.options[prop] = conf[prop];
	          } else if (!conf.options) {
	            this.linterOptions[prop] = conf[prop];
	          }
	        }
	        this.timeout = null;
	        this.hasGutter = hasGutter;
	        this.onMouseOver = function (e) {
	          onMouseOver(cm, e);
	        };
	        this.waitingFor = 0;
	      }
	      var defaults = {
	        highlightLines: false,
	        tooltips: true,
	        delay: 500,
	        lintOnChange: true,
	        getAnnotations: null,
	        async: false,
	        selfContain: null,
	        formatAnnotation: null,
	        onUpdateLinting: null
	      };
	      function clearMarks(cm) {
	        var state = cm.state.lint;
	        if (state.hasGutter) cm.clearGutter(GUTTER_ID);
	        if (state.options.highlightLines) clearErrorLines(cm);
	        for (var i = 0; i < state.marked.length; ++i) state.marked[i].clear();
	        state.marked.length = 0;
	      }
	      function clearErrorLines(cm) {
	        cm.eachLine(function (line) {
	          var has = line.wrapClass && /\bCodeMirror-lint-line-\w+\b/.exec(line.wrapClass);
	          if (has) cm.removeLineClass(line, "wrap", has[0]);
	        });
	      }
	      function makeMarker(cm, labels, severity, multiple, tooltips) {
	        var marker = document.createElement("div"),
	          inner = marker;
	        marker.className = "CodeMirror-lint-marker CodeMirror-lint-marker-" + severity;
	        if (multiple) {
	          inner = marker.appendChild(document.createElement("div"));
	          inner.className = "CodeMirror-lint-marker CodeMirror-lint-marker-multiple";
	        }
	        if (tooltips != false) CodeMirror.on(inner, "mouseover", function (e) {
	          showTooltipFor(cm, e, labels, inner);
	        });
	        return marker;
	      }
	      function getMaxSeverity(a, b) {
	        if (a == "error") return a;else return b;
	      }
	      function groupByLine(annotations) {
	        var lines = [];
	        for (var i = 0; i < annotations.length; ++i) {
	          var ann = annotations[i],
	            line = ann.from.line;
	          (lines[line] || (lines[line] = [])).push(ann);
	        }
	        return lines;
	      }
	      function annotationTooltip(ann) {
	        var severity = ann.severity;
	        if (!severity) severity = "error";
	        var tip = document.createElement("div");
	        tip.className = "CodeMirror-lint-message CodeMirror-lint-message-" + severity;
	        if (typeof ann.messageHTML != 'undefined') {
	          tip.innerHTML = ann.messageHTML;
	        } else {
	          tip.appendChild(document.createTextNode(ann.message));
	        }
	        return tip;
	      }
	      function lintAsync(cm, getAnnotations) {
	        var state = cm.state.lint;
	        var id = ++state.waitingFor;
	        function abort() {
	          id = -1;
	          cm.off("change", abort);
	        }
	        cm.on("change", abort);
	        getAnnotations(cm.getValue(), function (annotations, arg2) {
	          cm.off("change", abort);
	          if (state.waitingFor != id) return;
	          if (arg2 && annotations instanceof CodeMirror) annotations = arg2;
	          cm.operation(function () {
	            updateLinting(cm, annotations);
	          });
	        }, state.linterOptions, cm);
	      }
	      function startLinting(cm) {
	        var state = cm.state.lint;
	        if (!state) return;
	        var options = state.options;
	        /*
	         * Passing rules in `options` property prevents JSHint (and other linters) from complaining
	         * about unrecognized rules like `onUpdateLinting`, `delay`, `lintOnChange`, etc.
	         */
	        var getAnnotations = options.getAnnotations || cm.getHelper(CodeMirror.Pos(0, 0), "lint");
	        if (!getAnnotations) return;
	        if (options.async || getAnnotations.async) {
	          lintAsync(cm, getAnnotations);
	        } else {
	          var annotations = getAnnotations(cm.getValue(), state.linterOptions, cm);
	          if (!annotations) return;
	          if (annotations.then) annotations.then(function (issues) {
	            cm.operation(function () {
	              updateLinting(cm, issues);
	            });
	          });else cm.operation(function () {
	            updateLinting(cm, annotations);
	          });
	        }
	      }
	      function updateLinting(cm, annotationsNotSorted) {
	        var state = cm.state.lint;
	        if (!state) return;
	        var options = state.options;
	        clearMarks(cm);
	        var annotations = groupByLine(annotationsNotSorted);
	        for (var line = 0; line < annotations.length; ++line) {
	          var anns = annotations[line];
	          if (!anns) continue;
	          var maxSeverity = null;
	          var tipLabel = state.hasGutter && document.createDocumentFragment();
	          for (var i = 0; i < anns.length; ++i) {
	            var ann = anns[i];
	            var severity = ann.severity;
	            if (!severity) severity = "error";
	            maxSeverity = getMaxSeverity(maxSeverity, severity);
	            if (options.formatAnnotation) ann = options.formatAnnotation(ann);
	            if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann));
	            if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, {
	              className: "CodeMirror-lint-mark CodeMirror-lint-mark-" + severity,
	              __annotation: ann
	            }));
	          }
	          if (state.hasGutter) cm.setGutterMarker(line, GUTTER_ID, makeMarker(cm, tipLabel, maxSeverity, anns.length > 1, options.tooltips));
	          if (options.highlightLines) cm.addLineClass(line, "wrap", LINT_LINE_ID + maxSeverity);
	        }
	        if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm);
	      }
	      function onChange(cm) {
	        var state = cm.state.lint;
	        if (!state) return;
	        clearTimeout(state.timeout);
	        state.timeout = setTimeout(function () {
	          startLinting(cm);
	        }, state.options.delay);
	      }
	      function popupTooltips(cm, annotations, e) {
	        var target = e.target || e.srcElement;
	        var tooltip = document.createDocumentFragment();
	        for (var i = 0; i < annotations.length; i++) {
	          var ann = annotations[i];
	          tooltip.appendChild(annotationTooltip(ann));
	        }
	        showTooltipFor(cm, e, tooltip, target);
	      }
	      function onMouseOver(cm, e) {
	        var target = e.target || e.srcElement;
	        if (!/\bCodeMirror-lint-mark-/.test(target.className)) return;
	        var box = target.getBoundingClientRect(),
	          x = (box.left + box.right) / 2,
	          y = (box.top + box.bottom) / 2;
	        var spans = cm.findMarksAt(cm.coordsChar({
	          left: x,
	          top: y
	        }, "client"));
	        var annotations = [];
	        for (var i = 0; i < spans.length; ++i) {
	          var ann = spans[i].__annotation;
	          if (ann) annotations.push(ann);
	        }
	        if (annotations.length) popupTooltips(cm, annotations, e);
	      }
	      CodeMirror.defineOption("lint", false, function (cm, val, old) {
	        if (old && old != CodeMirror.Init) {
	          clearMarks(cm);
	          if (cm.state.lint.options.lintOnChange !== false) cm.off("change", onChange);
	          CodeMirror.off(cm.getWrapperElement(), "mouseover", cm.state.lint.onMouseOver);
	          clearTimeout(cm.state.lint.timeout);
	          delete cm.state.lint;
	        }
	        if (val) {
	          var gutters = cm.getOption("gutters"),
	            hasLintGutter = false;
	          for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true;
	          var state = cm.state.lint = new LintState(cm, val, hasLintGutter);
	          if (state.options.lintOnChange) cm.on("change", onChange);
	          if (state.options.tooltips != false && state.options.tooltips != "gutter") CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver);
	          startLinting(cm);
	        }
	      });
	      CodeMirror.defineExtension("performLint", function () {
	        startLinting(this);
	      });
	    });
	  })();
	  return lint.exports;
	}

	requireLint();

	var overlay = {exports: {}};

	var hasRequiredOverlay;
	function requireOverlay() {
	  if (hasRequiredOverlay) return overlay.exports;
	  hasRequiredOverlay = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    // Utility function that allows modes to be combined. The mode given
	    // as the base argument takes care of most of the normal mode
	    // functionality, but a second (typically simple) mode is used, which
	    // can override the style of text. Both modes get to parse all of the
	    // text, but when both assign a non-null style to a piece of code, the
	    // overlay wins, unless the combine argument was true and not overridden,
	    // or state.overlay.combineTokens was true, in which case the styles are
	    // combined.

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      CodeMirror.overlayMode = function (base, overlay, combine) {
	        return {
	          startState: function () {
	            return {
	              base: CodeMirror.startState(base),
	              overlay: CodeMirror.startState(overlay),
	              basePos: 0,
	              baseCur: null,
	              overlayPos: 0,
	              overlayCur: null,
	              streamSeen: null
	            };
	          },
	          copyState: function (state) {
	            return {
	              base: CodeMirror.copyState(base, state.base),
	              overlay: CodeMirror.copyState(overlay, state.overlay),
	              basePos: state.basePos,
	              baseCur: null,
	              overlayPos: state.overlayPos,
	              overlayCur: null
	            };
	          },
	          token: function (stream, state) {
	            if (stream != state.streamSeen || Math.min(state.basePos, state.overlayPos) < stream.start) {
	              state.streamSeen = stream;
	              state.basePos = state.overlayPos = stream.start;
	            }
	            if (stream.start == state.basePos) {
	              state.baseCur = base.token(stream, state.base);
	              state.basePos = stream.pos;
	            }
	            if (stream.start == state.overlayPos) {
	              stream.pos = stream.start;
	              state.overlayCur = overlay.token(stream, state.overlay);
	              state.overlayPos = stream.pos;
	            }
	            stream.pos = Math.min(state.basePos, state.overlayPos);

	            // state.overlay.combineTokens always takes precedence over combine,
	            // unless set to null
	            if (state.overlayCur == null) return state.baseCur;else if (state.baseCur != null && state.overlay.combineTokens || combine && state.overlay.combineTokens == null) return state.baseCur + " " + state.overlayCur;else return state.overlayCur;
	          },
	          indent: base.indent && function (state, textAfter, line) {
	            return base.indent(state.base, textAfter, line);
	          },
	          electricChars: base.electricChars,
	          innerMode: function (state) {
	            return {
	              state: state.base,
	              mode: base
	            };
	          },
	          blankLine: function (state) {
	            var baseToken, overlayToken;
	            if (base.blankLine) baseToken = base.blankLine(state.base);
	            if (overlay.blankLine) overlayToken = overlay.blankLine(state.overlay);
	            return overlayToken == null ? baseToken : combine && baseToken != null ? baseToken + " " + overlayToken : overlayToken;
	          }
	        };
	      };
	    });
	  })();
	  return overlay.exports;
	}

	requireOverlay();

	var simple = {exports: {}};

	var hasRequiredSimple;
	function requireSimple() {
	  if (hasRequiredSimple) return simple.exports;
	  hasRequiredSimple = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      CodeMirror.defineSimpleMode = function (name, states) {
	        CodeMirror.defineMode(name, function (config) {
	          return CodeMirror.simpleMode(config, states);
	        });
	      };
	      CodeMirror.simpleMode = function (config, states) {
	        ensureState(states, "start");
	        var states_ = {},
	          meta = states.meta || {},
	          hasIndentation = false;
	        for (var state in states) if (state != meta && states.hasOwnProperty(state)) {
	          var list = states_[state] = [],
	            orig = states[state];
	          for (var i = 0; i < orig.length; i++) {
	            var data = orig[i];
	            list.push(new Rule(data, states));
	            if (data.indent || data.dedent) hasIndentation = true;
	          }
	        }
	        var mode = {
	          startState: function () {
	            return {
	              state: "start",
	              pending: null,
	              local: null,
	              localState: null,
	              indent: hasIndentation ? [] : null
	            };
	          },
	          copyState: function (state) {
	            var s = {
	              state: state.state,
	              pending: state.pending,
	              local: state.local,
	              localState: null,
	              indent: state.indent && state.indent.slice(0)
	            };
	            if (state.localState) s.localState = CodeMirror.copyState(state.local.mode, state.localState);
	            if (state.stack) s.stack = state.stack.slice(0);
	            for (var pers = state.persistentStates; pers; pers = pers.next) s.persistentStates = {
	              mode: pers.mode,
	              spec: pers.spec,
	              state: pers.state == state.localState ? s.localState : CodeMirror.copyState(pers.mode, pers.state),
	              next: s.persistentStates
	            };
	            return s;
	          },
	          token: tokenFunction(states_, config),
	          innerMode: function (state) {
	            return state.local && {
	              mode: state.local.mode,
	              state: state.localState
	            };
	          },
	          indent: indentFunction(states_, meta)
	        };
	        if (meta) for (var prop in meta) if (meta.hasOwnProperty(prop)) mode[prop] = meta[prop];
	        return mode;
	      };
	      function ensureState(states, name) {
	        if (!states.hasOwnProperty(name)) throw new Error("Undefined state " + name + " in simple mode");
	      }
	      function toRegex(val, caret) {
	        if (!val) return /(?:)/;
	        var flags = "";
	        if (val instanceof RegExp) {
	          if (val.ignoreCase) flags = "i";
	          if (val.unicode) flags += "u";
	          val = val.source;
	        } else {
	          val = String(val);
	        }
	        return new RegExp((caret === false ? "" : "^") + "(?:" + val + ")", flags);
	      }
	      function asToken(val) {
	        if (!val) return null;
	        if (val.apply) return val;
	        if (typeof val == "string") return val.replace(/\./g, " ");
	        var result = [];
	        for (var i = 0; i < val.length; i++) result.push(val[i] && val[i].replace(/\./g, " "));
	        return result;
	      }
	      function Rule(data, states) {
	        if (data.next || data.push) ensureState(states, data.next || data.push);
	        this.regex = toRegex(data.regex);
	        this.token = asToken(data.token);
	        this.data = data;
	      }
	      function tokenFunction(states, config) {
	        return function (stream, state) {
	          if (state.pending) {
	            var pend = state.pending.shift();
	            if (state.pending.length == 0) state.pending = null;
	            stream.pos += pend.text.length;
	            return pend.token;
	          }
	          if (state.local) {
	            if (state.local.end && stream.match(state.local.end)) {
	              var tok = state.local.endToken || null;
	              state.local = state.localState = null;
	              return tok;
	            } else {
	              var tok = state.local.mode.token(stream, state.localState),
	                m;
	              if (state.local.endScan && (m = state.local.endScan.exec(stream.current()))) stream.pos = stream.start + m.index;
	              return tok;
	            }
	          }
	          var curState = states[state.state];
	          for (var i = 0; i < curState.length; i++) {
	            var rule = curState[i];
	            var matches = (!rule.data.sol || stream.sol()) && stream.match(rule.regex);
	            if (matches) {
	              if (rule.data.next) {
	                state.state = rule.data.next;
	              } else if (rule.data.push) {
	                (state.stack || (state.stack = [])).push(state.state);
	                state.state = rule.data.push;
	              } else if (rule.data.pop && state.stack && state.stack.length) {
	                state.state = state.stack.pop();
	              }
	              if (rule.data.mode) enterLocalMode(config, state, rule.data.mode, rule.token);
	              if (rule.data.indent) state.indent.push(stream.indentation() + config.indentUnit);
	              if (rule.data.dedent) state.indent.pop();
	              var token = rule.token;
	              if (token && token.apply) token = token(matches);
	              if (matches.length > 2 && rule.token && typeof rule.token != "string") {
	                for (var j = 2; j < matches.length; j++) if (matches[j]) (state.pending || (state.pending = [])).push({
	                  text: matches[j],
	                  token: rule.token[j - 1]
	                });
	                stream.backUp(matches[0].length - (matches[1] ? matches[1].length : 0));
	                return token[0];
	              } else if (token && token.join) {
	                return token[0];
	              } else {
	                return token;
	              }
	            }
	          }
	          stream.next();
	          return null;
	        };
	      }
	      function cmp(a, b) {
	        if (a === b) return true;
	        if (!a || typeof a != "object" || !b || typeof b != "object") return false;
	        var props = 0;
	        for (var prop in a) if (a.hasOwnProperty(prop)) {
	          if (!b.hasOwnProperty(prop) || !cmp(a[prop], b[prop])) return false;
	          props++;
	        }
	        for (var prop in b) if (b.hasOwnProperty(prop)) props--;
	        return props == 0;
	      }
	      function enterLocalMode(config, state, spec, token) {
	        var pers;
	        if (spec.persistent) for (var p = state.persistentStates; p && !pers; p = p.next) if (spec.spec ? cmp(spec.spec, p.spec) : spec.mode == p.mode) pers = p;
	        var mode = pers ? pers.mode : spec.mode || CodeMirror.getMode(config, spec.spec);
	        var lState = pers ? pers.state : CodeMirror.startState(mode);
	        if (spec.persistent && !pers) state.persistentStates = {
	          mode: mode,
	          spec: spec.spec,
	          state: lState,
	          next: state.persistentStates
	        };
	        state.localState = lState;
	        state.local = {
	          mode: mode,
	          end: spec.end && toRegex(spec.end),
	          endScan: spec.end && spec.forceEnd !== false && toRegex(spec.end, false),
	          endToken: token && token.join ? token[token.length - 1] : token
	        };
	      }
	      function indexOf(val, arr) {
	        for (var i = 0; i < arr.length; i++) if (arr[i] === val) return true;
	      }
	      function indentFunction(states, meta) {
	        return function (state, textAfter, line) {
	          if (state.local && state.local.mode.indent) return state.local.mode.indent(state.localState, textAfter, line);
	          if (state.indent == null || state.local || meta.dontIndentStates && indexOf(state.state, meta.dontIndentStates) > -1) return CodeMirror.Pass;
	          var pos = state.indent.length - 1,
	            rules = states[state.state];
	          scan: for (;;) {
	            for (var i = 0; i < rules.length; i++) {
	              var rule = rules[i];
	              if (rule.data.dedent && rule.data.dedentIfLineStart !== false) {
	                var m = rule.regex.exec(textAfter);
	                if (m && m[0]) {
	                  pos--;
	                  if (rule.next || rule.push) rules = states[rule.next || rule.push];
	                  textAfter = textAfter.slice(m[0].length);
	                  continue scan;
	                }
	              }
	            }
	            break;
	          }
	          return pos < 0 ? 0 : state.indent[pos];
	        };
	      }
	    });
	  })();
	  return simple.exports;
	}

	requireSimple();

	var markSelection = {exports: {}};

	var hasRequiredMarkSelection;
	function requireMarkSelection() {
	  if (hasRequiredMarkSelection) return markSelection.exports;
	  hasRequiredMarkSelection = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    // Because sometimes you need to mark the selected *text*.
	    //
	    // Adds an option 'styleSelectedText' which, when enabled, gives
	    // selected text the CSS class given as option value, or
	    // "CodeMirror-selectedtext" when the value is not a string.

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      CodeMirror.defineOption("styleSelectedText", false, function (cm, val, old) {
	        var prev = old && old != CodeMirror.Init;
	        if (val && !prev) {
	          cm.state.markedSelection = [];
	          cm.state.markedSelectionStyle = typeof val == "string" ? val : "CodeMirror-selectedtext";
	          reset(cm);
	          cm.on("cursorActivity", onCursorActivity);
	          cm.on("change", onChange);
	        } else if (!val && prev) {
	          cm.off("cursorActivity", onCursorActivity);
	          cm.off("change", onChange);
	          clear(cm);
	          cm.state.markedSelection = cm.state.markedSelectionStyle = null;
	        }
	      });
	      function onCursorActivity(cm) {
	        if (cm.state.markedSelection) cm.operation(function () {
	          update(cm);
	        });
	      }
	      function onChange(cm) {
	        if (cm.state.markedSelection && cm.state.markedSelection.length) cm.operation(function () {
	          clear(cm);
	        });
	      }
	      var CHUNK_SIZE = 8;
	      var Pos = CodeMirror.Pos;
	      var cmp = CodeMirror.cmpPos;
	      function coverRange(cm, from, to, addAt) {
	        if (cmp(from, to) == 0) return;
	        var array = cm.state.markedSelection;
	        var cls = cm.state.markedSelectionStyle;
	        for (var line = from.line;;) {
	          var start = line == from.line ? from : Pos(line, 0);
	          var endLine = line + CHUNK_SIZE,
	            atEnd = endLine >= to.line;
	          var end = atEnd ? to : Pos(endLine, 0);
	          var mark = cm.markText(start, end, {
	            className: cls
	          });
	          if (addAt == null) array.push(mark);else array.splice(addAt++, 0, mark);
	          if (atEnd) break;
	          line = endLine;
	        }
	      }
	      function clear(cm) {
	        var array = cm.state.markedSelection;
	        for (var i = 0; i < array.length; ++i) array[i].clear();
	        array.length = 0;
	      }
	      function reset(cm) {
	        clear(cm);
	        var ranges = cm.listSelections();
	        for (var i = 0; i < ranges.length; i++) coverRange(cm, ranges[i].from(), ranges[i].to());
	      }
	      function update(cm) {
	        if (!cm.somethingSelected()) return clear(cm);
	        if (cm.listSelections().length > 1) return reset(cm);
	        var from = cm.getCursor("start"),
	          to = cm.getCursor("end");
	        var array = cm.state.markedSelection;
	        if (!array.length) return coverRange(cm, from, to);
	        var coverStart = array[0].find(),
	          coverEnd = array[array.length - 1].find();
	        if (!coverStart || !coverEnd || to.line - from.line <= CHUNK_SIZE || cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0) return reset(cm);
	        while (cmp(from, coverStart.from) > 0) {
	          array.shift().clear();
	          coverStart = array[0].find();
	        }
	        if (cmp(from, coverStart.from) < 0) {
	          if (coverStart.to.line - from.line < CHUNK_SIZE) {
	            array.shift().clear();
	            coverRange(cm, from, coverStart.to, 0);
	          } else {
	            coverRange(cm, from, coverStart.from, 0);
	          }
	        }
	        while (cmp(to, coverEnd.to) < 0) {
	          array.pop().clear();
	          coverEnd = array[array.length - 1].find();
	        }
	        if (cmp(to, coverEnd.to) > 0) {
	          if (to.line - coverEnd.from.line < CHUNK_SIZE) {
	            array.pop().clear();
	            coverRange(cm, coverEnd.from, to);
	          } else {
	            coverRange(cm, coverEnd.to, to);
	          }
	        }
	      }
	    });
	  })();
	  return markSelection.exports;
	}

	requireMarkSelection();

	var coffeescript = {exports: {}};

	var hasRequiredCoffeescript;
	function requireCoffeescript() {
	  if (hasRequiredCoffeescript) return coffeescript.exports;
	  hasRequiredCoffeescript = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    /**
	     * Link to the project's GitHub page:
	     * https://github.com/pickhardt/coffeescript-codemirror-mode
	     */
	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      CodeMirror.defineMode("coffeescript", function (conf, parserConf) {
	        var ERRORCLASS = "error";
	        function wordRegexp(words) {
	          return new RegExp("^((" + words.join(")|(") + "))\\b");
	        }
	        var operators = /^(?:->|=>|\+[+=]?|-[\-=]?|\*[\*=]?|\/[\/=]?|[=!]=|<[><]?=?|>>?=?|%=?|&=?|\|=?|\^=?|\~|!|\?|(or|and|\|\||&&|\?)=)/;
	        var delimiters = /^(?:[()\[\]{},:`=;]|\.\.?\.?)/;
	        var identifiers = /^[_A-Za-z$][_A-Za-z$0-9]*/;
	        var atProp = /^@[_A-Za-z$][_A-Za-z$0-9]*/;
	        var wordOperators = wordRegexp(["and", "or", "not", "is", "isnt", "in", "instanceof", "typeof"]);
	        var indentKeywords = ["for", "while", "loop", "if", "unless", "else", "switch", "try", "catch", "finally", "class"];
	        var commonKeywords = ["break", "by", "continue", "debugger", "delete", "do", "in", "of", "new", "return", "then", "this", "@", "throw", "when", "until", "extends"];
	        var keywords = wordRegexp(indentKeywords.concat(commonKeywords));
	        indentKeywords = wordRegexp(indentKeywords);
	        var stringPrefixes = /^('{3}|\"{3}|['\"])/;
	        var regexPrefixes = /^(\/{3}|\/)/;
	        var commonConstants = ["Infinity", "NaN", "undefined", "null", "true", "false", "on", "off", "yes", "no"];
	        var constants = wordRegexp(commonConstants);

	        // Tokenizers
	        function tokenBase(stream, state) {
	          // Handle scope changes
	          if (stream.sol()) {
	            if (state.scope.align === null) state.scope.align = false;
	            var scopeOffset = state.scope.offset;
	            if (stream.eatSpace()) {
	              var lineOffset = stream.indentation();
	              if (lineOffset > scopeOffset && state.scope.type == "coffee") {
	                return "indent";
	              } else if (lineOffset < scopeOffset) {
	                return "dedent";
	              }
	              return null;
	            } else {
	              if (scopeOffset > 0) {
	                dedent(stream, state);
	              }
	            }
	          }
	          if (stream.eatSpace()) {
	            return null;
	          }
	          var ch = stream.peek();

	          // Handle docco title comment (single line)
	          if (stream.match("####")) {
	            stream.skipToEnd();
	            return "comment";
	          }

	          // Handle multi line comments
	          if (stream.match("###")) {
	            state.tokenize = longComment;
	            return state.tokenize(stream, state);
	          }

	          // Single line comment
	          if (ch === "#") {
	            stream.skipToEnd();
	            return "comment";
	          }

	          // Handle number literals
	          if (stream.match(/^-?[0-9\.]/, false)) {
	            var floatLiteral = false;
	            // Floats
	            if (stream.match(/^-?\d*\.\d+(e[\+\-]?\d+)?/i)) {
	              floatLiteral = true;
	            }
	            if (stream.match(/^-?\d+\.\d*/)) {
	              floatLiteral = true;
	            }
	            if (stream.match(/^-?\.\d+/)) {
	              floatLiteral = true;
	            }
	            if (floatLiteral) {
	              // prevent from getting extra . on 1..
	              if (stream.peek() == ".") {
	                stream.backUp(1);
	              }
	              return "number";
	            }
	            // Integers
	            var intLiteral = false;
	            // Hex
	            if (stream.match(/^-?0x[0-9a-f]+/i)) {
	              intLiteral = true;
	            }
	            // Decimal
	            if (stream.match(/^-?[1-9]\d*(e[\+\-]?\d+)?/)) {
	              intLiteral = true;
	            }
	            // Zero by itself with no other piece of number.
	            if (stream.match(/^-?0(?![\dx])/i)) {
	              intLiteral = true;
	            }
	            if (intLiteral) {
	              return "number";
	            }
	          }

	          // Handle strings
	          if (stream.match(stringPrefixes)) {
	            state.tokenize = tokenFactory(stream.current(), false, "string");
	            return state.tokenize(stream, state);
	          }
	          // Handle regex literals
	          if (stream.match(regexPrefixes)) {
	            if (stream.current() != "/" || stream.match(/^.*\//, false)) {
	              // prevent highlight of division
	              state.tokenize = tokenFactory(stream.current(), true, "string-2");
	              return state.tokenize(stream, state);
	            } else {
	              stream.backUp(1);
	            }
	          }

	          // Handle operators and delimiters
	          if (stream.match(operators) || stream.match(wordOperators)) {
	            return "operator";
	          }
	          if (stream.match(delimiters)) {
	            return "punctuation";
	          }
	          if (stream.match(constants)) {
	            return "atom";
	          }
	          if (stream.match(atProp) || state.prop && stream.match(identifiers)) {
	            return "property";
	          }
	          if (stream.match(keywords)) {
	            return "keyword";
	          }
	          if (stream.match(identifiers)) {
	            return "variable";
	          }

	          // Handle non-detected items
	          stream.next();
	          return ERRORCLASS;
	        }
	        function tokenFactory(delimiter, singleline, outclass) {
	          return function (stream, state) {
	            while (!stream.eol()) {
	              stream.eatWhile(/[^'"\/\\]/);
	              if (stream.eat("\\")) {
	                stream.next();
	                if (singleline && stream.eol()) {
	                  return outclass;
	                }
	              } else if (stream.match(delimiter)) {
	                state.tokenize = tokenBase;
	                return outclass;
	              } else {
	                stream.eat(/['"\/]/);
	              }
	            }
	            if (singleline) {
	              if (parserConf.singleLineStringErrors) {
	                outclass = ERRORCLASS;
	              } else {
	                state.tokenize = tokenBase;
	              }
	            }
	            return outclass;
	          };
	        }
	        function longComment(stream, state) {
	          while (!stream.eol()) {
	            stream.eatWhile(/[^#]/);
	            if (stream.match("###")) {
	              state.tokenize = tokenBase;
	              break;
	            }
	            stream.eatWhile("#");
	          }
	          return "comment";
	        }
	        function indent(stream, state, type) {
	          type = type || "coffee";
	          var offset = 0,
	            align = false,
	            alignOffset = null;
	          for (var scope = state.scope; scope; scope = scope.prev) {
	            if (scope.type === "coffee" || scope.type == "}") {
	              offset = scope.offset + conf.indentUnit;
	              break;
	            }
	          }
	          if (type !== "coffee") {
	            align = null;
	            alignOffset = stream.column() + stream.current().length;
	          } else if (state.scope.align) {
	            state.scope.align = false;
	          }
	          state.scope = {
	            offset: offset,
	            type: type,
	            prev: state.scope,
	            align: align,
	            alignOffset: alignOffset
	          };
	        }
	        function dedent(stream, state) {
	          if (!state.scope.prev) return;
	          if (state.scope.type === "coffee") {
	            var _indent = stream.indentation();
	            var matched = false;
	            for (var scope = state.scope; scope; scope = scope.prev) {
	              if (_indent === scope.offset) {
	                matched = true;
	                break;
	              }
	            }
	            if (!matched) {
	              return true;
	            }
	            while (state.scope.prev && state.scope.offset !== _indent) {
	              state.scope = state.scope.prev;
	            }
	            return false;
	          } else {
	            state.scope = state.scope.prev;
	            return false;
	          }
	        }
	        function tokenLexer(stream, state) {
	          var style = state.tokenize(stream, state);
	          var current = stream.current();

	          // Handle scope changes.
	          if (current === "return") {
	            state.dedent = true;
	          }
	          if ((current === "->" || current === "=>") && stream.eol() || style === "indent") {
	            indent(stream, state);
	          }
	          var delimiter_index = "[({".indexOf(current);
	          if (delimiter_index !== -1) {
	            indent(stream, state, "])}".slice(delimiter_index, delimiter_index + 1));
	          }
	          if (indentKeywords.exec(current)) {
	            indent(stream, state);
	          }
	          if (current == "then") {
	            dedent(stream, state);
	          }
	          if (style === "dedent") {
	            if (dedent(stream, state)) {
	              return ERRORCLASS;
	            }
	          }
	          delimiter_index = "])}".indexOf(current);
	          if (delimiter_index !== -1) {
	            while (state.scope.type == "coffee" && state.scope.prev) state.scope = state.scope.prev;
	            if (state.scope.type == current) state.scope = state.scope.prev;
	          }
	          if (state.dedent && stream.eol()) {
	            if (state.scope.type == "coffee" && state.scope.prev) state.scope = state.scope.prev;
	            state.dedent = false;
	          }
	          return style;
	        }
	        var external = {
	          startState: function (basecolumn) {
	            return {
	              tokenize: tokenBase,
	              scope: {
	                offset: basecolumn || 0,
	                type: "coffee",
	                prev: null,
	                align: false
	              },
	              prop: false,
	              dedent: 0
	            };
	          },
	          token: function (stream, state) {
	            var fillAlign = state.scope.align === null && state.scope;
	            if (fillAlign && stream.sol()) fillAlign.align = false;
	            var style = tokenLexer(stream, state);
	            if (style && style != "comment") {
	              if (fillAlign) fillAlign.align = true;
	              state.prop = style == "punctuation" && stream.current() == ".";
	            }
	            return style;
	          },
	          indent: function (state, text) {
	            if (state.tokenize != tokenBase) return 0;
	            var scope = state.scope;
	            var closer = text && "])}".indexOf(text.charAt(0)) > -1;
	            if (closer) while (scope.type == "coffee" && scope.prev) scope = scope.prev;
	            var closes = closer && scope.type === text.charAt(0);
	            if (scope.align) return scope.alignOffset - (closes ? 1 : 0);else return (closes ? scope.prev : scope).offset;
	          },
	          lineComment: "#",
	          fold: "indent"
	        };
	        return external;
	      });

	      // IANA registered media type
	      // https://www.iana.org/assignments/media-types/
	      CodeMirror.defineMIME("application/vnd.coffeescript", "coffeescript");
	      CodeMirror.defineMIME("text/x-coffeescript", "coffeescript");
	      CodeMirror.defineMIME("text/coffeescript", "coffeescript");
	    });
	  })();
	  return coffeescript.exports;
	}

	requireCoffeescript();

	var css = {exports: {}};

	var hasRequiredCss;
	function requireCss() {
	  if (hasRequiredCss) return css.exports;
	  hasRequiredCss = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      CodeMirror.defineMode("css", function (config, parserConfig) {
	        var inline = parserConfig.inline;
	        if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css");
	        var indentUnit = config.indentUnit,
	          tokenHooks = parserConfig.tokenHooks,
	          documentTypes = parserConfig.documentTypes || {},
	          mediaTypes = parserConfig.mediaTypes || {},
	          mediaFeatures = parserConfig.mediaFeatures || {},
	          mediaValueKeywords = parserConfig.mediaValueKeywords || {},
	          propertyKeywords = parserConfig.propertyKeywords || {},
	          nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {},
	          fontProperties = parserConfig.fontProperties || {},
	          counterDescriptors = parserConfig.counterDescriptors || {},
	          colorKeywords = parserConfig.colorKeywords || {},
	          valueKeywords = parserConfig.valueKeywords || {},
	          allowNested = parserConfig.allowNested,
	          lineComment = parserConfig.lineComment,
	          supportsAtComponent = parserConfig.supportsAtComponent === true,
	          highlightNonStandardPropertyKeywords = config.highlightNonStandardPropertyKeywords !== false;
	        var type, override;
	        function ret(style, tp) {
	          type = tp;
	          return style;
	        }

	        // Tokenizers

	        function tokenBase(stream, state) {
	          var ch = stream.next();
	          if (tokenHooks[ch]) {
	            var result = tokenHooks[ch](stream, state);
	            if (result !== false) return result;
	          }
	          if (ch == "@") {
	            stream.eatWhile(/[\w\\\-]/);
	            return ret("def", stream.current());
	          } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) {
	            return ret(null, "compare");
	          } else if (ch == "\"" || ch == "'") {
	            state.tokenize = tokenString(ch);
	            return state.tokenize(stream, state);
	          } else if (ch == "#") {
	            stream.eatWhile(/[\w\\\-]/);
	            return ret("atom", "hash");
	          } else if (ch == "!") {
	            stream.match(/^\s*\w*/);
	            return ret("keyword", "important");
	          } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) {
	            stream.eatWhile(/[\w.%]/);
	            return ret("number", "unit");
	          } else if (ch === "-") {
	            if (/[\d.]/.test(stream.peek())) {
	              stream.eatWhile(/[\w.%]/);
	              return ret("number", "unit");
	            } else if (stream.match(/^-[\w\\\-]*/)) {
	              stream.eatWhile(/[\w\\\-]/);
	              if (stream.match(/^\s*:/, false)) return ret("variable-2", "variable-definition");
	              return ret("variable-2", "variable");
	            } else if (stream.match(/^\w+-/)) {
	              return ret("meta", "meta");
	            }
	          } else if (/[,+>*\/]/.test(ch)) {
	            return ret(null, "select-op");
	          } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {
	            return ret("qualifier", "qualifier");
	          } else if (/[:;{}\[\]\(\)]/.test(ch)) {
	            return ret(null, ch);
	          } else if (stream.match(/^[\w-.]+(?=\()/)) {
	            if (/^(url(-prefix)?|domain|regexp)$/i.test(stream.current())) {
	              state.tokenize = tokenParenthesized;
	            }
	            return ret("variable callee", "variable");
	          } else if (/[\w\\\-]/.test(ch)) {
	            stream.eatWhile(/[\w\\\-]/);
	            return ret("property", "word");
	          } else {
	            return ret(null, null);
	          }
	        }
	        function tokenString(quote) {
	          return function (stream, state) {
	            var escaped = false,
	              ch;
	            while ((ch = stream.next()) != null) {
	              if (ch == quote && !escaped) {
	                if (quote == ")") stream.backUp(1);
	                break;
	              }
	              escaped = !escaped && ch == "\\";
	            }
	            if (ch == quote || !escaped && quote != ")") state.tokenize = null;
	            return ret("string", "string");
	          };
	        }
	        function tokenParenthesized(stream, state) {
	          stream.next(); // Must be '('
	          if (!stream.match(/^\s*[\"\')]/, false)) state.tokenize = tokenString(")");else state.tokenize = null;
	          return ret(null, "(");
	        }

	        // Context management

	        function Context(type, indent, prev) {
	          this.type = type;
	          this.indent = indent;
	          this.prev = prev;
	        }
	        function pushContext(state, stream, type, indent) {
	          state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context);
	          return type;
	        }
	        function popContext(state) {
	          if (state.context.prev) state.context = state.context.prev;
	          return state.context.type;
	        }
	        function pass(type, stream, state) {
	          return states[state.context.type](type, stream, state);
	        }
	        function popAndPass(type, stream, state, n) {
	          for (var i = n || 1; i > 0; i--) state.context = state.context.prev;
	          return pass(type, stream, state);
	        }

	        // Parser

	        function wordAsValue(stream) {
	          var word = stream.current().toLowerCase();
	          if (valueKeywords.hasOwnProperty(word)) override = "atom";else if (colorKeywords.hasOwnProperty(word)) override = "keyword";else override = "variable";
	        }
	        var states = {};
	        states.top = function (type, stream, state) {
	          if (type == "{") {
	            return pushContext(state, stream, "block");
	          } else if (type == "}" && state.context.prev) {
	            return popContext(state);
	          } else if (supportsAtComponent && /@component/i.test(type)) {
	            return pushContext(state, stream, "atComponentBlock");
	          } else if (/^@(-moz-)?document$/i.test(type)) {
	            return pushContext(state, stream, "documentTypes");
	          } else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type)) {
	            return pushContext(state, stream, "atBlock");
	          } else if (/^@(font-face|counter-style)/i.test(type)) {
	            state.stateArg = type;
	            return "restricted_atBlock_before";
	          } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)) {
	            return "keyframes";
	          } else if (type && type.charAt(0) == "@") {
	            return pushContext(state, stream, "at");
	          } else if (type == "hash") {
	            override = "builtin";
	          } else if (type == "word") {
	            override = "tag";
	          } else if (type == "variable-definition") {
	            return "maybeprop";
	          } else if (type == "interpolation") {
	            return pushContext(state, stream, "interpolation");
	          } else if (type == ":") {
	            return "pseudo";
	          } else if (allowNested && type == "(") {
	            return pushContext(state, stream, "parens");
	          }
	          return state.context.type;
	        };
	        states.block = function (type, stream, state) {
	          if (type == "word") {
	            var word = stream.current().toLowerCase();
	            if (propertyKeywords.hasOwnProperty(word)) {
	              override = "property";
	              return "maybeprop";
	            } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) {
	              override = highlightNonStandardPropertyKeywords ? "string-2" : "property";
	              return "maybeprop";
	            } else if (allowNested) {
	              override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag";
	              return "block";
	            } else {
	              override += " error";
	              return "maybeprop";
	            }
	          } else if (type == "meta") {
	            return "block";
	          } else if (!allowNested && (type == "hash" || type == "qualifier")) {
	            override = "error";
	            return "block";
	          } else {
	            return states.top(type, stream, state);
	          }
	        };
	        states.maybeprop = function (type, stream, state) {
	          if (type == ":") return pushContext(state, stream, "prop");
	          return pass(type, stream, state);
	        };
	        states.prop = function (type, stream, state) {
	          if (type == ";") return popContext(state);
	          if (type == "{" && allowNested) return pushContext(state, stream, "propBlock");
	          if (type == "}" || type == "{") return popAndPass(type, stream, state);
	          if (type == "(") return pushContext(state, stream, "parens");
	          if (type == "hash" && !/^#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(stream.current())) {
	            override += " error";
	          } else if (type == "word") {
	            wordAsValue(stream);
	          } else if (type == "interpolation") {
	            return pushContext(state, stream, "interpolation");
	          }
	          return "prop";
	        };
	        states.propBlock = function (type, _stream, state) {
	          if (type == "}") return popContext(state);
	          if (type == "word") {
	            override = "property";
	            return "maybeprop";
	          }
	          return state.context.type;
	        };
	        states.parens = function (type, stream, state) {
	          if (type == "{" || type == "}") return popAndPass(type, stream, state);
	          if (type == ")") return popContext(state);
	          if (type == "(") return pushContext(state, stream, "parens");
	          if (type == "interpolation") return pushContext(state, stream, "interpolation");
	          if (type == "word") wordAsValue(stream);
	          return "parens";
	        };
	        states.pseudo = function (type, stream, state) {
	          if (type == "meta") return "pseudo";
	          if (type == "word") {
	            override = "variable-3";
	            return state.context.type;
	          }
	          return pass(type, stream, state);
	        };
	        states.documentTypes = function (type, stream, state) {
	          if (type == "word" && documentTypes.hasOwnProperty(stream.current())) {
	            override = "tag";
	            return state.context.type;
	          } else {
	            return states.atBlock(type, stream, state);
	          }
	        };
	        states.atBlock = function (type, stream, state) {
	          if (type == "(") return pushContext(state, stream, "atBlock_parens");
	          if (type == "}" || type == ";") return popAndPass(type, stream, state);
	          if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top");
	          if (type == "interpolation") return pushContext(state, stream, "interpolation");
	          if (type == "word") {
	            var word = stream.current().toLowerCase();
	            if (word == "only" || word == "not" || word == "and" || word == "or") override = "keyword";else if (mediaTypes.hasOwnProperty(word)) override = "attribute";else if (mediaFeatures.hasOwnProperty(word)) override = "property";else if (mediaValueKeywords.hasOwnProperty(word)) override = "keyword";else if (propertyKeywords.hasOwnProperty(word)) override = "property";else if (nonStandardPropertyKeywords.hasOwnProperty(word)) override = highlightNonStandardPropertyKeywords ? "string-2" : "property";else if (valueKeywords.hasOwnProperty(word)) override = "atom";else if (colorKeywords.hasOwnProperty(word)) override = "keyword";else override = "error";
	          }
	          return state.context.type;
	        };
	        states.atComponentBlock = function (type, stream, state) {
	          if (type == "}") return popAndPass(type, stream, state);
	          if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false);
	          if (type == "word") override = "error";
	          return state.context.type;
	        };
	        states.atBlock_parens = function (type, stream, state) {
	          if (type == ")") return popContext(state);
	          if (type == "{" || type == "}") return popAndPass(type, stream, state, 2);
	          return states.atBlock(type, stream, state);
	        };
	        states.restricted_atBlock_before = function (type, stream, state) {
	          if (type == "{") return pushContext(state, stream, "restricted_atBlock");
	          if (type == "word" && state.stateArg == "@counter-style") {
	            override = "variable";
	            return "restricted_atBlock_before";
	          }
	          return pass(type, stream, state);
	        };
	        states.restricted_atBlock = function (type, stream, state) {
	          if (type == "}") {
	            state.stateArg = null;
	            return popContext(state);
	          }
	          if (type == "word") {
	            if (state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase()) || state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase())) override = "error";else override = "property";
	            return "maybeprop";
	          }
	          return "restricted_atBlock";
	        };
	        states.keyframes = function (type, stream, state) {
	          if (type == "word") {
	            override = "variable";
	            return "keyframes";
	          }
	          if (type == "{") return pushContext(state, stream, "top");
	          return pass(type, stream, state);
	        };
	        states.at = function (type, stream, state) {
	          if (type == ";") return popContext(state);
	          if (type == "{" || type == "}") return popAndPass(type, stream, state);
	          if (type == "word") override = "tag";else if (type == "hash") override = "builtin";
	          return "at";
	        };
	        states.interpolation = function (type, stream, state) {
	          if (type == "}") return popContext(state);
	          if (type == "{" || type == ";") return popAndPass(type, stream, state);
	          if (type == "word") override = "variable";else if (type != "variable" && type != "(" && type != ")") override = "error";
	          return "interpolation";
	        };
	        return {
	          startState: function (base) {
	            return {
	              tokenize: null,
	              state: inline ? "block" : "top",
	              stateArg: null,
	              context: new Context(inline ? "block" : "top", base || 0, null)
	            };
	          },
	          token: function (stream, state) {
	            if (!state.tokenize && stream.eatSpace()) return null;
	            var style = (state.tokenize || tokenBase)(stream, state);
	            if (style && typeof style == "object") {
	              type = style[1];
	              style = style[0];
	            }
	            override = style;
	            if (type != "comment") state.state = states[state.state](type, stream, state);
	            return override;
	          },
	          indent: function (state, textAfter) {
	            var cx = state.context,
	              ch = textAfter && textAfter.charAt(0);
	            var indent = cx.indent;
	            if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev;
	            if (cx.prev) {
	              if (ch == "}" && (cx.type == "block" || cx.type == "top" || cx.type == "interpolation" || cx.type == "restricted_atBlock")) {
	                // Resume indentation from parent context.
	                cx = cx.prev;
	                indent = cx.indent;
	              } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") || ch == "{" && (cx.type == "at" || cx.type == "atBlock")) {
	                // Dedent relative to current context.
	                indent = Math.max(0, cx.indent - indentUnit);
	              }
	            }
	            return indent;
	          },
	          electricChars: "}",
	          blockCommentStart: "/*",
	          blockCommentEnd: "*/",
	          blockCommentContinue: " * ",
	          lineComment: lineComment,
	          fold: "brace"
	        };
	      });
	      function keySet(array) {
	        var keys = {};
	        for (var i = 0; i < array.length; ++i) {
	          keys[array[i].toLowerCase()] = true;
	        }
	        return keys;
	      }
	      var documentTypes_ = ["domain", "regexp", "url", "url-prefix"],
	        documentTypes = keySet(documentTypes_);
	      var mediaTypes_ = ["all", "aural", "braille", "handheld", "print", "projection", "screen", "tty", "tv", "embossed"],
	        mediaTypes = keySet(mediaTypes_);
	      var mediaFeatures_ = ["width", "min-width", "max-width", "height", "min-height", "max-height", "device-width", "min-device-width", "max-device-width", "device-height", "min-device-height", "max-device-height", "aspect-ratio", "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio", "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color", "max-color", "color-index", "min-color-index", "max-color-index", "monochrome", "min-monochrome", "max-monochrome", "resolution", "min-resolution", "max-resolution", "scan", "grid", "orientation", "device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio", "pointer", "any-pointer", "hover", "any-hover", "prefers-color-scheme", "dynamic-range", "video-dynamic-range"],
	        mediaFeatures = keySet(mediaFeatures_);
	      var mediaValueKeywords_ = ["landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover", "interlace", "progressive", "dark", "light", "standard", "high"],
	        mediaValueKeywords = keySet(mediaValueKeywords_);
	      var propertyKeywords_ = ["align-content", "align-items", "align-self", "alignment-adjust", "alignment-baseline", "all", "anchor-point", "animation", "animation-delay", "animation-direction", "animation-duration", "animation-fill-mode", "animation-iteration-count", "animation-name", "animation-play-state", "animation-timing-function", "appearance", "azimuth", "backdrop-filter", "backface-visibility", "background", "background-attachment", "background-blend-mode", "background-clip", "background-color", "background-image", "background-origin", "background-position", "background-position-x", "background-position-y", "background-repeat", "background-size", "baseline-shift", "binding", "bleed", "block-size", "bookmark-label", "bookmark-level", "bookmark-state", "bookmark-target", "border", "border-bottom", "border-bottom-color", "border-bottom-left-radius", "border-bottom-right-radius", "border-bottom-style", "border-bottom-width", "border-collapse", "border-color", "border-image", "border-image-outset", "border-image-repeat", "border-image-slice", "border-image-source", "border-image-width", "border-left", "border-left-color", "border-left-style", "border-left-width", "border-radius", "border-right", "border-right-color", "border-right-style", "border-right-width", "border-spacing", "border-style", "border-top", "border-top-color", "border-top-left-radius", "border-top-right-radius", "border-top-style", "border-top-width", "border-width", "bottom", "box-decoration-break", "box-shadow", "box-sizing", "break-after", "break-before", "break-inside", "caption-side", "caret-color", "clear", "clip", "color", "color-profile", "column-count", "column-fill", "column-gap", "column-rule", "column-rule-color", "column-rule-style", "column-rule-width", "column-span", "column-width", "columns", "contain", "content", "counter-increment", "counter-reset", "crop", "cue", "cue-after", "cue-before", "cursor", "direction", "display", "dominant-baseline", "drop-initial-after-adjust", "drop-initial-after-align", "drop-initial-before-adjust", "drop-initial-before-align", "drop-initial-size", "drop-initial-value", "elevation", "empty-cells", "fit", "fit-content", "fit-position", "flex", "flex-basis", "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap", "float", "float-offset", "flow-from", "flow-into", "font", "font-family", "font-feature-settings", "font-kerning", "font-language-override", "font-optical-sizing", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-synthesis", "font-variant", "font-variant-alternates", "font-variant-caps", "font-variant-east-asian", "font-variant-ligatures", "font-variant-numeric", "font-variant-position", "font-variation-settings", "font-weight", "gap", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow", "grid-auto-rows", "grid-column", "grid-column-end", "grid-column-gap", "grid-column-start", "grid-gap", "grid-row", "grid-row-end", "grid-row-gap", "grid-row-start", "grid-template", "grid-template-areas", "grid-template-columns", "grid-template-rows", "hanging-punctuation", "height", "hyphens", "icon", "image-orientation", "image-rendering", "image-resolution", "inline-box-align", "inset", "inset-block", "inset-block-end", "inset-block-start", "inset-inline", "inset-inline-end", "inset-inline-start", "isolation", "justify-content", "justify-items", "justify-self", "left", "letter-spacing", "line-break", "line-height", "line-height-step", "line-stacking", "line-stacking-ruby", "line-stacking-shift", "line-stacking-strategy", "list-style", "list-style-image", "list-style-position", "list-style-type", "margin", "margin-bottom", "margin-left", "margin-right", "margin-top", "marks", "marquee-direction", "marquee-loop", "marquee-play-count", "marquee-speed", "marquee-style", "mask-clip", "mask-composite", "mask-image", "mask-mode", "mask-origin", "mask-position", "mask-repeat", "mask-size", "mask-type", "max-block-size", "max-height", "max-inline-size", "max-width", "min-block-size", "min-height", "min-inline-size", "min-width", "mix-blend-mode", "move-to", "nav-down", "nav-index", "nav-left", "nav-right", "nav-up", "object-fit", "object-position", "offset", "offset-anchor", "offset-distance", "offset-path", "offset-position", "offset-rotate", "opacity", "order", "orphans", "outline", "outline-color", "outline-offset", "outline-style", "outline-width", "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y", "padding", "padding-bottom", "padding-left", "padding-right", "padding-top", "page", "page-break-after", "page-break-before", "page-break-inside", "page-policy", "pause", "pause-after", "pause-before", "perspective", "perspective-origin", "pitch", "pitch-range", "place-content", "place-items", "place-self", "play-during", "position", "presentation-level", "punctuation-trim", "quotes", "region-break-after", "region-break-before", "region-break-inside", "region-fragment", "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness", "right", "rotate", "rotation", "rotation-point", "row-gap", "ruby-align", "ruby-overhang", "ruby-position", "ruby-span", "scale", "scroll-behavior", "scroll-margin", "scroll-margin-block", "scroll-margin-block-end", "scroll-margin-block-start", "scroll-margin-bottom", "scroll-margin-inline", "scroll-margin-inline-end", "scroll-margin-inline-start", "scroll-margin-left", "scroll-margin-right", "scroll-margin-top", "scroll-padding", "scroll-padding-block", "scroll-padding-block-end", "scroll-padding-block-start", "scroll-padding-bottom", "scroll-padding-inline", "scroll-padding-inline-end", "scroll-padding-inline-start", "scroll-padding-left", "scroll-padding-right", "scroll-padding-top", "scroll-snap-align", "scroll-snap-type", "shape-image-threshold", "shape-inside", "shape-margin", "shape-outside", "size", "speak", "speak-as", "speak-header", "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set", "tab-size", "table-layout", "target", "target-name", "target-new", "target-position", "text-align", "text-align-last", "text-combine-upright", "text-decoration", "text-decoration-color", "text-decoration-line", "text-decoration-skip", "text-decoration-skip-ink", "text-decoration-style", "text-emphasis", "text-emphasis-color", "text-emphasis-position", "text-emphasis-style", "text-height", "text-indent", "text-justify", "text-orientation", "text-outline", "text-overflow", "text-rendering", "text-shadow", "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position", "text-wrap", "top", "touch-action", "transform", "transform-origin", "transform-style", "transition", "transition-delay", "transition-duration", "transition-property", "transition-timing-function", "translate", "unicode-bidi", "user-select", "vertical-align", "visibility", "voice-balance", "voice-duration", "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress", "voice-volume", "volume", "white-space", "widows", "width", "will-change", "word-break", "word-spacing", "word-wrap", "writing-mode", "z-index",
	        // SVG-specific
	        "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color", "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events", "color-interpolation", "color-interpolation-filters", "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering", "marker", "marker-end", "marker-mid", "marker-start", "paint-order", "shape-rendering", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering", "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal", "glyph-orientation-vertical", "text-anchor", "writing-mode"],
	        propertyKeywords = keySet(propertyKeywords_);
	      var nonStandardPropertyKeywords_ = ["accent-color", "aspect-ratio", "border-block", "border-block-color", "border-block-end", "border-block-end-color", "border-block-end-style", "border-block-end-width", "border-block-start", "border-block-start-color", "border-block-start-style", "border-block-start-width", "border-block-style", "border-block-width", "border-inline", "border-inline-color", "border-inline-end", "border-inline-end-color", "border-inline-end-style", "border-inline-end-width", "border-inline-start", "border-inline-start-color", "border-inline-start-style", "border-inline-start-width", "border-inline-style", "border-inline-width", "content-visibility", "margin-block", "margin-block-end", "margin-block-start", "margin-inline", "margin-inline-end", "margin-inline-start", "overflow-anchor", "overscroll-behavior", "padding-block", "padding-block-end", "padding-block-start", "padding-inline", "padding-inline-end", "padding-inline-start", "scroll-snap-stop", "scrollbar-3d-light-color", "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color", "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color", "scrollbar-track-color", "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button", "searchfield-results-decoration", "shape-inside", "zoom"],
	        nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_);
	      var fontProperties_ = ["font-display", "font-family", "src", "unicode-range", "font-variant", "font-feature-settings", "font-stretch", "font-weight", "font-style"],
	        fontProperties = keySet(fontProperties_);
	      var counterDescriptors_ = ["additive-symbols", "fallback", "negative", "pad", "prefix", "range", "speak-as", "suffix", "symbols", "system"],
	        counterDescriptors = keySet(counterDescriptors_);
	      var colorKeywords_ = ["aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkgrey", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkslategrey", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dimgrey", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightgrey", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightslategrey", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "slategrey", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen"],
	        colorKeywords = keySet(colorKeywords_);
	      var valueKeywords_ = ["above", "absolute", "activeborder", "additive", "activecaption", "afar", "after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate", "always", "amharic", "amharic-abegede", "antialiased", "appworkspace", "arabic-indic", "armenian", "asterisks", "attr", "auto", "auto-flow", "avoid", "avoid-column", "avoid-page", "avoid-region", "axis-pan", "background", "backwards", "baseline", "below", "bidi-override", "binary", "bengali", "blink", "block", "block-axis", "blur", "bold", "bolder", "border", "border-box", "both", "bottom", "break", "break-all", "break-word", "brightness", "bullets", "button", "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian", "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret", "cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch", "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote", "col-resize", "collapse", "color", "color-burn", "color-dodge", "column", "column-reverse", "compact", "condensed", "conic-gradient", "contain", "content", "contents", "content-box", "context-menu", "continuous", "contrast", "copy", "counter", "counters", "cover", "crop", "cross", "crosshair", "cubic-bezier", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal", "decimal-leading-zero", "default", "default-button", "dense", "destination-atop", "destination-in", "destination-out", "destination-over", "devanagari", "difference", "disc", "discard", "disclosure-closed", "disclosure-open", "document", "dot-dash", "dot-dot-dash", "dotted", "double", "down", "drop-shadow", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede", "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er", "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er", "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et", "ethiopic-halehame-gez", "ethiopic-halehame-om-et", "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et", "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig", "ethiopic-numeric", "ew-resize", "exclusion", "expanded", "extends", "extra-condensed", "extra-expanded", "fantasy", "fast", "fill", "fill-box", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes", "forwards", "from", "geometricPrecision", "georgian", "grayscale", "graytext", "grid", "groove", "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew", "help", "hidden", "hide", "higher", "highlight", "highlighttext", "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "hue-rotate", "icon", "ignore", "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis", "inline-block", "inline-flex", "inline-grid", "inline-table", "inset", "inside", "intrinsic", "invert", "italic", "japanese-formal", "japanese-informal", "justify", "kannada", "katakana", "katakana-iroha", "keep-all", "khmer", "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal", "landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten", "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem", "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian", "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian", "lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "manipulation", "match", "matrix", "matrix3d", "media-play-button", "media-slider", "media-sliderthumb", "media-volume-slider", "media-volume-sliderthumb", "medium", "menu", "menulist", "menulist-button", "menutext", "message-box", "middle", "min-intrinsic", "mix", "mongolian", "monospace", "move", "multiple", "multiple_mask_images", "multiply", "myanmar", "n-resize", "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap", "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "opacity", "open-quote", "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset", "outside", "outside-shape", "overlay", "overline", "padding", "padding-box", "painted", "page", "paused", "persian", "perspective", "pinch-zoom", "plus-darker", "plus-lighter", "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button", "radial-gradient", "radio", "read-only", "read-write", "read-write-plaintext-only", "rectangle", "region", "relative", "repeat", "repeating-linear-gradient", "repeating-radial-gradient", "repeating-conic-gradient", "repeat-x", "repeat-y", "reset", "reverse", "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY", "rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running", "s-resize", "sans-serif", "saturate", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen", "scroll", "scrollbar", "scroll-position", "se-resize", "searchfield", "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button", "searchfield-results-decoration", "self-start", "self-end", "semi-condensed", "semi-expanded", "separate", "sepia", "serif", "show", "sidama", "simp-chinese-formal", "simp-chinese-informal", "single", "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal", "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", "small", "small-caps", "small-caption", "smaller", "soft-light", "solid", "somali", "source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "space-evenly", "spell-out", "square", "square-button", "start", "static", "status-bar", "stretch", "stroke", "stroke-box", "sub", "subpixel-antialiased", "svg_masks", "super", "sw-resize", "symbolic", "symbols", "system-ui", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-footer-group", "table-header-group", "table-row", "table-row-group", "tamil", "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai", "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight", "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er", "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top", "trad-chinese-formal", "trad-chinese-informal", "transform", "translate", "translate3d", "translateX", "translateY", "translateZ", "transparent", "ultra-condensed", "ultra-expanded", "underline", "unidirectional-pan", "unset", "up", "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal", "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", "var", "vertical", "vertical-text", "view-box", "visible", "visibleFill", "visiblePainted", "visibleStroke", "visual", "w-resize", "wait", "wave", "wider", "window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor", "xx-large", "xx-small"],
	        valueKeywords = keySet(valueKeywords_);
	      var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_).concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_).concat(valueKeywords_);
	      CodeMirror.registerHelper("hintWords", "css", allWords);
	      function tokenCComment(stream, state) {
	        var maybeEnd = false,
	          ch;
	        while ((ch = stream.next()) != null) {
	          if (maybeEnd && ch == "/") {
	            state.tokenize = null;
	            break;
	          }
	          maybeEnd = ch == "*";
	        }
	        return ["comment", "comment"];
	      }
	      CodeMirror.defineMIME("text/css", {
	        documentTypes: documentTypes,
	        mediaTypes: mediaTypes,
	        mediaFeatures: mediaFeatures,
	        mediaValueKeywords: mediaValueKeywords,
	        propertyKeywords: propertyKeywords,
	        nonStandardPropertyKeywords: nonStandardPropertyKeywords,
	        fontProperties: fontProperties,
	        counterDescriptors: counterDescriptors,
	        colorKeywords: colorKeywords,
	        valueKeywords: valueKeywords,
	        tokenHooks: {
	          "/": function (stream, state) {
	            if (!stream.eat("*")) return false;
	            state.tokenize = tokenCComment;
	            return tokenCComment(stream, state);
	          }
	        },
	        name: "css"
	      });
	      CodeMirror.defineMIME("text/x-scss", {
	        mediaTypes: mediaTypes,
	        mediaFeatures: mediaFeatures,
	        mediaValueKeywords: mediaValueKeywords,
	        propertyKeywords: propertyKeywords,
	        nonStandardPropertyKeywords: nonStandardPropertyKeywords,
	        colorKeywords: colorKeywords,
	        valueKeywords: valueKeywords,
	        fontProperties: fontProperties,
	        allowNested: true,
	        lineComment: "//",
	        tokenHooks: {
	          "/": function (stream, state) {
	            if (stream.eat("/")) {
	              stream.skipToEnd();
	              return ["comment", "comment"];
	            } else if (stream.eat("*")) {
	              state.tokenize = tokenCComment;
	              return tokenCComment(stream, state);
	            } else {
	              return ["operator", "operator"];
	            }
	          },
	          ":": function (stream) {
	            if (stream.match(/^\s*\{/, false)) return [null, null];
	            return false;
	          },
	          "$": function (stream) {
	            stream.match(/^[\w-]+/);
	            if (stream.match(/^\s*:/, false)) return ["variable-2", "variable-definition"];
	            return ["variable-2", "variable"];
	          },
	          "#": function (stream) {
	            if (!stream.eat("{")) return false;
	            return [null, "interpolation"];
	          }
	        },
	        name: "css",
	        helperType: "scss"
	      });
	      CodeMirror.defineMIME("text/x-less", {
	        mediaTypes: mediaTypes,
	        mediaFeatures: mediaFeatures,
	        mediaValueKeywords: mediaValueKeywords,
	        propertyKeywords: propertyKeywords,
	        nonStandardPropertyKeywords: nonStandardPropertyKeywords,
	        colorKeywords: colorKeywords,
	        valueKeywords: valueKeywords,
	        fontProperties: fontProperties,
	        allowNested: true,
	        lineComment: "//",
	        tokenHooks: {
	          "/": function (stream, state) {
	            if (stream.eat("/")) {
	              stream.skipToEnd();
	              return ["comment", "comment"];
	            } else if (stream.eat("*")) {
	              state.tokenize = tokenCComment;
	              return tokenCComment(stream, state);
	            } else {
	              return ["operator", "operator"];
	            }
	          },
	          "@": function (stream) {
	            if (stream.eat("{")) return [null, "interpolation"];
	            if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i, false)) return false;
	            stream.eatWhile(/[\w\\\-]/);
	            if (stream.match(/^\s*:/, false)) return ["variable-2", "variable-definition"];
	            return ["variable-2", "variable"];
	          },
	          "&": function () {
	            return ["atom", "atom"];
	          }
	        },
	        name: "css",
	        helperType: "less"
	      });
	      CodeMirror.defineMIME("text/x-gss", {
	        documentTypes: documentTypes,
	        mediaTypes: mediaTypes,
	        mediaFeatures: mediaFeatures,
	        propertyKeywords: propertyKeywords,
	        nonStandardPropertyKeywords: nonStandardPropertyKeywords,
	        fontProperties: fontProperties,
	        counterDescriptors: counterDescriptors,
	        colorKeywords: colorKeywords,
	        valueKeywords: valueKeywords,
	        supportsAtComponent: true,
	        tokenHooks: {
	          "/": function (stream, state) {
	            if (!stream.eat("*")) return false;
	            state.tokenize = tokenCComment;
	            return tokenCComment(stream, state);
	          }
	        },
	        name: "css",
	        helperType: "gss"
	      });
	    });
	  })();
	  return css.exports;
	}

	requireCss();

	var gfm = {exports: {}};

	var markdown = {exports: {}};

	var xml = {exports: {}};

	var hasRequiredXml;
	function requireXml() {
	  if (hasRequiredXml) return xml.exports;
	  hasRequiredXml = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      var htmlConfig = {
	        autoSelfClosers: {
	          'area': true,
	          'base': true,
	          'br': true,
	          'col': true,
	          'command': true,
	          'embed': true,
	          'frame': true,
	          'hr': true,
	          'img': true,
	          'input': true,
	          'keygen': true,
	          'link': true,
	          'meta': true,
	          'param': true,
	          'source': true,
	          'track': true,
	          'wbr': true,
	          'menuitem': true
	        },
	        implicitlyClosed: {
	          'dd': true,
	          'li': true,
	          'optgroup': true,
	          'option': true,
	          'p': true,
	          'rp': true,
	          'rt': true,
	          'tbody': true,
	          'td': true,
	          'tfoot': true,
	          'th': true,
	          'tr': true
	        },
	        contextGrabbers: {
	          'dd': {
	            'dd': true,
	            'dt': true
	          },
	          'dt': {
	            'dd': true,
	            'dt': true
	          },
	          'li': {
	            'li': true
	          },
	          'option': {
	            'option': true,
	            'optgroup': true
	          },
	          'optgroup': {
	            'optgroup': true
	          },
	          'p': {
	            'address': true,
	            'article': true,
	            'aside': true,
	            'blockquote': true,
	            'dir': true,
	            'div': true,
	            'dl': true,
	            'fieldset': true,
	            'footer': true,
	            'form': true,
	            'h1': true,
	            'h2': true,
	            'h3': true,
	            'h4': true,
	            'h5': true,
	            'h6': true,
	            'header': true,
	            'hgroup': true,
	            'hr': true,
	            'menu': true,
	            'nav': true,
	            'ol': true,
	            'p': true,
	            'pre': true,
	            'section': true,
	            'table': true,
	            'ul': true
	          },
	          'rp': {
	            'rp': true,
	            'rt': true
	          },
	          'rt': {
	            'rp': true,
	            'rt': true
	          },
	          'tbody': {
	            'tbody': true,
	            'tfoot': true
	          },
	          'td': {
	            'td': true,
	            'th': true
	          },
	          'tfoot': {
	            'tbody': true
	          },
	          'th': {
	            'td': true,
	            'th': true
	          },
	          'thead': {
	            'tbody': true,
	            'tfoot': true
	          },
	          'tr': {
	            'tr': true
	          }
	        },
	        doNotIndent: {
	          "pre": true
	        },
	        allowUnquoted: true,
	        allowMissing: true,
	        caseFold: true
	      };
	      var xmlConfig = {
	        autoSelfClosers: {},
	        implicitlyClosed: {},
	        contextGrabbers: {},
	        doNotIndent: {},
	        allowUnquoted: false,
	        allowMissing: false,
	        allowMissingTagName: false,
	        caseFold: false
	      };
	      CodeMirror.defineMode("xml", function (editorConf, config_) {
	        var indentUnit = editorConf.indentUnit;
	        var config = {};
	        var defaults = config_.htmlMode ? htmlConfig : xmlConfig;
	        for (var prop in defaults) config[prop] = defaults[prop];
	        for (var prop in config_) config[prop] = config_[prop];

	        // Return variables for tokenizers
	        var type, setStyle;
	        function inText(stream, state) {
	          function chain(parser) {
	            state.tokenize = parser;
	            return parser(stream, state);
	          }
	          var ch = stream.next();
	          if (ch == "<") {
	            if (stream.eat("!")) {
	              if (stream.eat("[")) {
	                if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));else return null;
	              } else if (stream.match("--")) {
	                return chain(inBlock("comment", "-->"));
	              } else if (stream.match("DOCTYPE", true, true)) {
	                stream.eatWhile(/[\w\._\-]/);
	                return chain(doctype(1));
	              } else {
	                return null;
	              }
	            } else if (stream.eat("?")) {
	              stream.eatWhile(/[\w\._\-]/);
	              state.tokenize = inBlock("meta", "?>");
	              return "meta";
	            } else {
	              type = stream.eat("/") ? "closeTag" : "openTag";
	              state.tokenize = inTag;
	              return "tag bracket";
	            }
	          } else if (ch == "&") {
	            var ok;
	            if (stream.eat("#")) {
	              if (stream.eat("x")) {
	                ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
	              } else {
	                ok = stream.eatWhile(/[\d]/) && stream.eat(";");
	              }
	            } else {
	              ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
	            }
	            return ok ? "atom" : "error";
	          } else {
	            stream.eatWhile(/[^&<]/);
	            return null;
	          }
	        }
	        inText.isInText = true;
	        function inTag(stream, state) {
	          var ch = stream.next();
	          if (ch == ">" || ch == "/" && stream.eat(">")) {
	            state.tokenize = inText;
	            type = ch == ">" ? "endTag" : "selfcloseTag";
	            return "tag bracket";
	          } else if (ch == "=") {
	            type = "equals";
	            return null;
	          } else if (ch == "<") {
	            state.tokenize = inText;
	            state.state = baseState;
	            state.tagName = state.tagStart = null;
	            var next = state.tokenize(stream, state);
	            return next ? next + " tag error" : "tag error";
	          } else if (/[\'\"]/.test(ch)) {
	            state.tokenize = inAttribute(ch);
	            state.stringStartCol = stream.column();
	            return state.tokenize(stream, state);
	          } else {
	            stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
	            return "word";
	          }
	        }
	        function inAttribute(quote) {
	          var closure = function (stream, state) {
	            while (!stream.eol()) {
	              if (stream.next() == quote) {
	                state.tokenize = inTag;
	                break;
	              }
	            }
	            return "string";
	          };
	          closure.isInAttribute = true;
	          return closure;
	        }
	        function inBlock(style, terminator) {
	          return function (stream, state) {
	            while (!stream.eol()) {
	              if (stream.match(terminator)) {
	                state.tokenize = inText;
	                break;
	              }
	              stream.next();
	            }
	            return style;
	          };
	        }
	        function doctype(depth) {
	          return function (stream, state) {
	            var ch;
	            while ((ch = stream.next()) != null) {
	              if (ch == "<") {
	                state.tokenize = doctype(depth + 1);
	                return state.tokenize(stream, state);
	              } else if (ch == ">") {
	                if (depth == 1) {
	                  state.tokenize = inText;
	                  break;
	                } else {
	                  state.tokenize = doctype(depth - 1);
	                  return state.tokenize(stream, state);
	                }
	              }
	            }
	            return "meta";
	          };
	        }
	        function lower(tagName) {
	          return tagName && tagName.toLowerCase();
	        }
	        function Context(state, tagName, startOfLine) {
	          this.prev = state.context;
	          this.tagName = tagName || "";
	          this.indent = state.indented;
	          this.startOfLine = startOfLine;
	          if (config.doNotIndent.hasOwnProperty(tagName) || state.context && state.context.noIndent) this.noIndent = true;
	        }
	        function popContext(state) {
	          if (state.context) state.context = state.context.prev;
	        }
	        function maybePopContext(state, nextTagName) {
	          var parentTagName;
	          while (true) {
	            if (!state.context) {
	              return;
	            }
	            parentTagName = state.context.tagName;
	            if (!config.contextGrabbers.hasOwnProperty(lower(parentTagName)) || !config.contextGrabbers[lower(parentTagName)].hasOwnProperty(lower(nextTagName))) {
	              return;
	            }
	            popContext(state);
	          }
	        }
	        function baseState(type, stream, state) {
	          if (type == "openTag") {
	            state.tagStart = stream.column();
	            return tagNameState;
	          } else if (type == "closeTag") {
	            return closeTagNameState;
	          } else {
	            return baseState;
	          }
	        }
	        function tagNameState(type, stream, state) {
	          if (type == "word") {
	            state.tagName = stream.current();
	            setStyle = "tag";
	            return attrState;
	          } else if (config.allowMissingTagName && type == "endTag") {
	            setStyle = "tag bracket";
	            return attrState(type, stream, state);
	          } else {
	            setStyle = "error";
	            return tagNameState;
	          }
	        }
	        function closeTagNameState(type, stream, state) {
	          if (type == "word") {
	            var tagName = stream.current();
	            if (state.context && state.context.tagName != tagName && config.implicitlyClosed.hasOwnProperty(lower(state.context.tagName))) popContext(state);
	            if (state.context && state.context.tagName == tagName || config.matchClosing === false) {
	              setStyle = "tag";
	              return closeState;
	            } else {
	              setStyle = "tag error";
	              return closeStateErr;
	            }
	          } else if (config.allowMissingTagName && type == "endTag") {
	            setStyle = "tag bracket";
	            return closeState(type, stream, state);
	          } else {
	            setStyle = "error";
	            return closeStateErr;
	          }
	        }
	        function closeState(type, _stream, state) {
	          if (type != "endTag") {
	            setStyle = "error";
	            return closeState;
	          }
	          popContext(state);
	          return baseState;
	        }
	        function closeStateErr(type, stream, state) {
	          setStyle = "error";
	          return closeState(type, stream, state);
	        }
	        function attrState(type, _stream, state) {
	          if (type == "word") {
	            setStyle = "attribute";
	            return attrEqState;
	          } else if (type == "endTag" || type == "selfcloseTag") {
	            var tagName = state.tagName,
	              tagStart = state.tagStart;
	            state.tagName = state.tagStart = null;
	            if (type == "selfcloseTag" || config.autoSelfClosers.hasOwnProperty(lower(tagName))) {
	              maybePopContext(state, tagName);
	            } else {
	              maybePopContext(state, tagName);
	              state.context = new Context(state, tagName, tagStart == state.indented);
	            }
	            return baseState;
	          }
	          setStyle = "error";
	          return attrState;
	        }
	        function attrEqState(type, stream, state) {
	          if (type == "equals") return attrValueState;
	          if (!config.allowMissing) setStyle = "error";
	          return attrState(type, stream, state);
	        }
	        function attrValueState(type, stream, state) {
	          if (type == "string") return attrContinuedState;
	          if (type == "word" && config.allowUnquoted) {
	            setStyle = "string";
	            return attrState;
	          }
	          setStyle = "error";
	          return attrState(type, stream, state);
	        }
	        function attrContinuedState(type, stream, state) {
	          if (type == "string") return attrContinuedState;
	          return attrState(type, stream, state);
	        }
	        return {
	          startState: function (baseIndent) {
	            var state = {
	              tokenize: inText,
	              state: baseState,
	              indented: baseIndent || 0,
	              tagName: null,
	              tagStart: null,
	              context: null
	            };
	            if (baseIndent != null) state.baseIndent = baseIndent;
	            return state;
	          },
	          token: function (stream, state) {
	            if (!state.tagName && stream.sol()) state.indented = stream.indentation();
	            if (stream.eatSpace()) return null;
	            type = null;
	            var style = state.tokenize(stream, state);
	            if ((style || type) && style != "comment") {
	              setStyle = null;
	              state.state = state.state(type || style, stream, state);
	              if (setStyle) style = setStyle == "error" ? style + " error" : setStyle;
	            }
	            return style;
	          },
	          indent: function (state, textAfter, fullLine) {
	            var context = state.context;
	            // Indent multi-line strings (e.g. css).
	            if (state.tokenize.isInAttribute) {
	              if (state.tagStart == state.indented) return state.stringStartCol + 1;else return state.indented + indentUnit;
	            }
	            if (context && context.noIndent) return CodeMirror.Pass;
	            if (state.tokenize != inTag && state.tokenize != inText) return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
	            // Indent the starts of attribute names.
	            if (state.tagName) {
	              if (config.multilineTagIndentPastTag !== false) return state.tagStart + state.tagName.length + 2;else return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
	            }
	            if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
	            var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
	            if (tagAfter && tagAfter[1]) {
	              // Closing tag spotted
	              while (context) {
	                if (context.tagName == tagAfter[2]) {
	                  context = context.prev;
	                  break;
	                } else if (config.implicitlyClosed.hasOwnProperty(lower(context.tagName))) {
	                  context = context.prev;
	                } else {
	                  break;
	                }
	              }
	            } else if (tagAfter) {
	              // Opening tag spotted
	              while (context) {
	                var grabbers = config.contextGrabbers[lower(context.tagName)];
	                if (grabbers && grabbers.hasOwnProperty(lower(tagAfter[2]))) context = context.prev;else break;
	              }
	            }
	            while (context && context.prev && !context.startOfLine) context = context.prev;
	            if (context) return context.indent + indentUnit;else return state.baseIndent || 0;
	          },
	          electricInput: /<\/[\s\w:]+>$/,
	          blockCommentStart: "<!--",
	          blockCommentEnd: "-->",
	          configuration: config.htmlMode ? "html" : "xml",
	          helperType: config.htmlMode ? "html" : "xml",
	          skipAttribute: function (state) {
	            if (state.state == attrValueState) state.state = attrState;
	          },
	          xmlCurrentTag: function (state) {
	            return state.tagName ? {
	              name: state.tagName,
	              close: state.type == "closeTag"
	            } : null;
	          },
	          xmlCurrentContext: function (state) {
	            var context = [];
	            for (var cx = state.context; cx; cx = cx.prev) context.push(cx.tagName);
	            return context.reverse();
	          }
	        };
	      });
	      CodeMirror.defineMIME("text/xml", "xml");
	      CodeMirror.defineMIME("application/xml", "xml");
	      if (!CodeMirror.mimeModes.hasOwnProperty("text/html")) CodeMirror.defineMIME("text/html", {
	        name: "xml",
	        htmlMode: true
	      });
	    });
	  })();
	  return xml.exports;
	}

	var meta = {exports: {}};

	var hasRequiredMeta;
	function requireMeta() {
	  if (hasRequiredMeta) return meta.exports;
	  hasRequiredMeta = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      CodeMirror.modeInfo = [{
	        name: "APL",
	        mime: "text/apl",
	        mode: "apl",
	        ext: ["dyalog", "apl"]
	      }, {
	        name: "PGP",
	        mimes: ["application/pgp", "application/pgp-encrypted", "application/pgp-keys", "application/pgp-signature"],
	        mode: "asciiarmor",
	        ext: ["asc", "pgp", "sig"]
	      }, {
	        name: "ASN.1",
	        mime: "text/x-ttcn-asn",
	        mode: "asn.1",
	        ext: ["asn", "asn1"]
	      }, {
	        name: "Asterisk",
	        mime: "text/x-asterisk",
	        mode: "asterisk",
	        file: /^extensions\.conf$/i
	      }, {
	        name: "Brainfuck",
	        mime: "text/x-brainfuck",
	        mode: "brainfuck",
	        ext: ["b", "bf"]
	      }, {
	        name: "C",
	        mime: "text/x-csrc",
	        mode: "clike",
	        ext: ["c", "h", "ino"]
	      }, {
	        name: "C++",
	        mime: "text/x-c++src",
	        mode: "clike",
	        ext: ["cpp", "c++", "cc", "cxx", "hpp", "h++", "hh", "hxx"],
	        alias: ["cpp"]
	      }, {
	        name: "Cobol",
	        mime: "text/x-cobol",
	        mode: "cobol",
	        ext: ["cob", "cpy", "cbl"]
	      }, {
	        name: "C#",
	        mime: "text/x-csharp",
	        mode: "clike",
	        ext: ["cs"],
	        alias: ["csharp", "cs"]
	      }, {
	        name: "Clojure",
	        mime: "text/x-clojure",
	        mode: "clojure",
	        ext: ["clj", "cljc", "cljx"]
	      }, {
	        name: "ClojureScript",
	        mime: "text/x-clojurescript",
	        mode: "clojure",
	        ext: ["cljs"]
	      }, {
	        name: "Closure Stylesheets (GSS)",
	        mime: "text/x-gss",
	        mode: "css",
	        ext: ["gss"]
	      }, {
	        name: "CMake",
	        mime: "text/x-cmake",
	        mode: "cmake",
	        ext: ["cmake", "cmake.in"],
	        file: /^CMakeLists\.txt$/
	      }, {
	        name: "CoffeeScript",
	        mimes: ["application/vnd.coffeescript", "text/coffeescript", "text/x-coffeescript"],
	        mode: "coffeescript",
	        ext: ["coffee"],
	        alias: ["coffee", "coffee-script"]
	      }, {
	        name: "Common Lisp",
	        mime: "text/x-common-lisp",
	        mode: "commonlisp",
	        ext: ["cl", "lisp", "el"],
	        alias: ["lisp"]
	      }, {
	        name: "Cypher",
	        mime: "application/x-cypher-query",
	        mode: "cypher",
	        ext: ["cyp", "cypher"]
	      }, {
	        name: "Cython",
	        mime: "text/x-cython",
	        mode: "python",
	        ext: ["pyx", "pxd", "pxi"]
	      }, {
	        name: "Crystal",
	        mime: "text/x-crystal",
	        mode: "crystal",
	        ext: ["cr"]
	      }, {
	        name: "CSS",
	        mime: "text/css",
	        mode: "css",
	        ext: ["css"]
	      }, {
	        name: "CQL",
	        mime: "text/x-cassandra",
	        mode: "sql",
	        ext: ["cql"]
	      }, {
	        name: "D",
	        mime: "text/x-d",
	        mode: "d",
	        ext: ["d"]
	      }, {
	        name: "Dart",
	        mimes: ["application/dart", "text/x-dart"],
	        mode: "dart",
	        ext: ["dart"]
	      }, {
	        name: "diff",
	        mime: "text/x-diff",
	        mode: "diff",
	        ext: ["diff", "patch"]
	      }, {
	        name: "Django",
	        mime: "text/x-django",
	        mode: "django"
	      }, {
	        name: "Dockerfile",
	        mime: "text/x-dockerfile",
	        mode: "dockerfile",
	        file: /^Dockerfile$/
	      }, {
	        name: "DTD",
	        mime: "application/xml-dtd",
	        mode: "dtd",
	        ext: ["dtd"]
	      }, {
	        name: "Dylan",
	        mime: "text/x-dylan",
	        mode: "dylan",
	        ext: ["dylan", "dyl", "intr"]
	      }, {
	        name: "EBNF",
	        mime: "text/x-ebnf",
	        mode: "ebnf"
	      }, {
	        name: "ECL",
	        mime: "text/x-ecl",
	        mode: "ecl",
	        ext: ["ecl"]
	      }, {
	        name: "edn",
	        mime: "application/edn",
	        mode: "clojure",
	        ext: ["edn"]
	      }, {
	        name: "Eiffel",
	        mime: "text/x-eiffel",
	        mode: "eiffel",
	        ext: ["e"]
	      }, {
	        name: "Elm",
	        mime: "text/x-elm",
	        mode: "elm",
	        ext: ["elm"]
	      }, {
	        name: "Embedded JavaScript",
	        mime: "application/x-ejs",
	        mode: "htmlembedded",
	        ext: ["ejs"]
	      }, {
	        name: "Embedded Ruby",
	        mime: "application/x-erb",
	        mode: "htmlembedded",
	        ext: ["erb"]
	      }, {
	        name: "Erlang",
	        mime: "text/x-erlang",
	        mode: "erlang",
	        ext: ["erl"]
	      }, {
	        name: "Esper",
	        mime: "text/x-esper",
	        mode: "sql"
	      }, {
	        name: "Factor",
	        mime: "text/x-factor",
	        mode: "factor",
	        ext: ["factor"]
	      }, {
	        name: "FCL",
	        mime: "text/x-fcl",
	        mode: "fcl"
	      }, {
	        name: "Forth",
	        mime: "text/x-forth",
	        mode: "forth",
	        ext: ["forth", "fth", "4th"]
	      }, {
	        name: "Fortran",
	        mime: "text/x-fortran",
	        mode: "fortran",
	        ext: ["f", "for", "f77", "f90", "f95"]
	      }, {
	        name: "F#",
	        mime: "text/x-fsharp",
	        mode: "mllike",
	        ext: ["fs"],
	        alias: ["fsharp"]
	      }, {
	        name: "Gas",
	        mime: "text/x-gas",
	        mode: "gas",
	        ext: ["s"]
	      }, {
	        name: "Gherkin",
	        mime: "text/x-feature",
	        mode: "gherkin",
	        ext: ["feature"]
	      }, {
	        name: "GitHub Flavored Markdown",
	        mime: "text/x-gfm",
	        mode: "gfm",
	        file: /^(readme|contributing|history)\.md$/i
	      }, {
	        name: "Go",
	        mime: "text/x-go",
	        mode: "go",
	        ext: ["go"]
	      }, {
	        name: "Groovy",
	        mime: "text/x-groovy",
	        mode: "groovy",
	        ext: ["groovy", "gradle"],
	        file: /^Jenkinsfile$/
	      }, {
	        name: "HAML",
	        mime: "text/x-haml",
	        mode: "haml",
	        ext: ["haml"]
	      }, {
	        name: "Haskell",
	        mime: "text/x-haskell",
	        mode: "haskell",
	        ext: ["hs"]
	      }, {
	        name: "Haskell (Literate)",
	        mime: "text/x-literate-haskell",
	        mode: "haskell-literate",
	        ext: ["lhs"]
	      }, {
	        name: "Haxe",
	        mime: "text/x-haxe",
	        mode: "haxe",
	        ext: ["hx"]
	      }, {
	        name: "HXML",
	        mime: "text/x-hxml",
	        mode: "haxe",
	        ext: ["hxml"]
	      }, {
	        name: "ASP.NET",
	        mime: "application/x-aspx",
	        mode: "htmlembedded",
	        ext: ["aspx"],
	        alias: ["asp", "aspx"]
	      }, {
	        name: "HTML",
	        mime: "text/html",
	        mode: "htmlmixed",
	        ext: ["html", "htm", "handlebars", "hbs"],
	        alias: ["xhtml"]
	      }, {
	        name: "HTTP",
	        mime: "message/http",
	        mode: "http"
	      }, {
	        name: "IDL",
	        mime: "text/x-idl",
	        mode: "idl",
	        ext: ["pro"]
	      }, {
	        name: "Pug",
	        mime: "text/x-pug",
	        mode: "pug",
	        ext: ["jade", "pug"],
	        alias: ["jade"]
	      }, {
	        name: "Java",
	        mime: "text/x-java",
	        mode: "clike",
	        ext: ["java"]
	      }, {
	        name: "Java Server Pages",
	        mime: "application/x-jsp",
	        mode: "htmlembedded",
	        ext: ["jsp"],
	        alias: ["jsp"]
	      }, {
	        name: "JavaScript",
	        mimes: ["text/javascript", "text/ecmascript", "application/javascript", "application/x-javascript", "application/ecmascript"],
	        mode: "javascript",
	        ext: ["js"],
	        alias: ["ecmascript", "js", "node"]
	      }, {
	        name: "JSON",
	        mimes: ["application/json", "application/x-json"],
	        mode: "javascript",
	        ext: ["json", "map"],
	        alias: ["json5"]
	      }, {
	        name: "JSON-LD",
	        mime: "application/ld+json",
	        mode: "javascript",
	        ext: ["jsonld"],
	        alias: ["jsonld"]
	      }, {
	        name: "JSX",
	        mime: "text/jsx",
	        mode: "jsx",
	        ext: ["jsx"]
	      }, {
	        name: "Jinja2",
	        mime: "text/jinja2",
	        mode: "jinja2",
	        ext: ["j2", "jinja", "jinja2"]
	      }, {
	        name: "Julia",
	        mime: "text/x-julia",
	        mode: "julia",
	        ext: ["jl"],
	        alias: ["jl"]
	      }, {
	        name: "Kotlin",
	        mime: "text/x-kotlin",
	        mode: "clike",
	        ext: ["kt"]
	      }, {
	        name: "LESS",
	        mime: "text/x-less",
	        mode: "css",
	        ext: ["less"]
	      }, {
	        name: "LiveScript",
	        mime: "text/x-livescript",
	        mode: "livescript",
	        ext: ["ls"],
	        alias: ["ls"]
	      }, {
	        name: "Lua",
	        mime: "text/x-lua",
	        mode: "lua",
	        ext: ["lua"]
	      }, {
	        name: "Markdown",
	        mime: "text/x-markdown",
	        mode: "markdown",
	        ext: ["markdown", "md", "mkd"]
	      }, {
	        name: "mIRC",
	        mime: "text/mirc",
	        mode: "mirc"
	      }, {
	        name: "MariaDB SQL",
	        mime: "text/x-mariadb",
	        mode: "sql"
	      }, {
	        name: "Mathematica",
	        mime: "text/x-mathematica",
	        mode: "mathematica",
	        ext: ["m", "nb", "wl", "wls"]
	      }, {
	        name: "Modelica",
	        mime: "text/x-modelica",
	        mode: "modelica",
	        ext: ["mo"]
	      }, {
	        name: "MUMPS",
	        mime: "text/x-mumps",
	        mode: "mumps",
	        ext: ["mps"]
	      }, {
	        name: "MS SQL",
	        mime: "text/x-mssql",
	        mode: "sql"
	      }, {
	        name: "mbox",
	        mime: "application/mbox",
	        mode: "mbox",
	        ext: ["mbox"]
	      }, {
	        name: "MySQL",
	        mime: "text/x-mysql",
	        mode: "sql"
	      }, {
	        name: "Nginx",
	        mime: "text/x-nginx-conf",
	        mode: "nginx",
	        file: /nginx.*\.conf$/i
	      }, {
	        name: "NSIS",
	        mime: "text/x-nsis",
	        mode: "nsis",
	        ext: ["nsh", "nsi"]
	      }, {
	        name: "NTriples",
	        mimes: ["application/n-triples", "application/n-quads", "text/n-triples"],
	        mode: "ntriples",
	        ext: ["nt", "nq"]
	      }, {
	        name: "Objective-C",
	        mime: "text/x-objectivec",
	        mode: "clike",
	        ext: ["m"],
	        alias: ["objective-c", "objc"]
	      }, {
	        name: "Objective-C++",
	        mime: "text/x-objectivec++",
	        mode: "clike",
	        ext: ["mm"],
	        alias: ["objective-c++", "objc++"]
	      }, {
	        name: "OCaml",
	        mime: "text/x-ocaml",
	        mode: "mllike",
	        ext: ["ml", "mli", "mll", "mly"]
	      }, {
	        name: "Octave",
	        mime: "text/x-octave",
	        mode: "octave",
	        ext: ["m"]
	      }, {
	        name: "Oz",
	        mime: "text/x-oz",
	        mode: "oz",
	        ext: ["oz"]
	      }, {
	        name: "Pascal",
	        mime: "text/x-pascal",
	        mode: "pascal",
	        ext: ["p", "pas"]
	      }, {
	        name: "PEG.js",
	        mime: "null",
	        mode: "pegjs",
	        ext: ["jsonld"]
	      }, {
	        name: "Perl",
	        mime: "text/x-perl",
	        mode: "perl",
	        ext: ["pl", "pm"]
	      }, {
	        name: "PHP",
	        mimes: ["text/x-php", "application/x-httpd-php", "application/x-httpd-php-open"],
	        mode: "php",
	        ext: ["php", "php3", "php4", "php5", "php7", "phtml"]
	      }, {
	        name: "Pig",
	        mime: "text/x-pig",
	        mode: "pig",
	        ext: ["pig"]
	      }, {
	        name: "Plain Text",
	        mime: "text/plain",
	        mode: "null",
	        ext: ["txt", "text", "conf", "def", "list", "log"]
	      }, {
	        name: "PLSQL",
	        mime: "text/x-plsql",
	        mode: "sql",
	        ext: ["pls"]
	      }, {
	        name: "PostgreSQL",
	        mime: "text/x-pgsql",
	        mode: "sql"
	      }, {
	        name: "PowerShell",
	        mime: "application/x-powershell",
	        mode: "powershell",
	        ext: ["ps1", "psd1", "psm1"]
	      }, {
	        name: "Properties files",
	        mime: "text/x-properties",
	        mode: "properties",
	        ext: ["properties", "ini", "in"],
	        alias: ["ini", "properties"]
	      }, {
	        name: "ProtoBuf",
	        mime: "text/x-protobuf",
	        mode: "protobuf",
	        ext: ["proto"]
	      }, {
	        name: "Python",
	        mime: "text/x-python",
	        mode: "python",
	        ext: ["BUILD", "bzl", "py", "pyw"],
	        file: /^(BUCK|BUILD)$/
	      }, {
	        name: "Puppet",
	        mime: "text/x-puppet",
	        mode: "puppet",
	        ext: ["pp"]
	      }, {
	        name: "Q",
	        mime: "text/x-q",
	        mode: "q",
	        ext: ["q"]
	      }, {
	        name: "R",
	        mime: "text/x-rsrc",
	        mode: "r",
	        ext: ["r", "R"],
	        alias: ["rscript"]
	      }, {
	        name: "reStructuredText",
	        mime: "text/x-rst",
	        mode: "rst",
	        ext: ["rst"],
	        alias: ["rst"]
	      }, {
	        name: "RPM Changes",
	        mime: "text/x-rpm-changes",
	        mode: "rpm"
	      }, {
	        name: "RPM Spec",
	        mime: "text/x-rpm-spec",
	        mode: "rpm",
	        ext: ["spec"]
	      }, {
	        name: "Ruby",
	        mime: "text/x-ruby",
	        mode: "ruby",
	        ext: ["rb"],
	        alias: ["jruby", "macruby", "rake", "rb", "rbx"]
	      }, {
	        name: "Rust",
	        mime: "text/x-rustsrc",
	        mode: "rust",
	        ext: ["rs"]
	      }, {
	        name: "SAS",
	        mime: "text/x-sas",
	        mode: "sas",
	        ext: ["sas"]
	      }, {
	        name: "Sass",
	        mime: "text/x-sass",
	        mode: "sass",
	        ext: ["sass"]
	      }, {
	        name: "Scala",
	        mime: "text/x-scala",
	        mode: "clike",
	        ext: ["scala"]
	      }, {
	        name: "Scheme",
	        mime: "text/x-scheme",
	        mode: "scheme",
	        ext: ["scm", "ss"]
	      }, {
	        name: "SCSS",
	        mime: "text/x-scss",
	        mode: "css",
	        ext: ["scss"]
	      }, {
	        name: "Shell",
	        mimes: ["text/x-sh", "application/x-sh"],
	        mode: "shell",
	        ext: ["sh", "ksh", "bash"],
	        alias: ["bash", "sh", "zsh"],
	        file: /^PKGBUILD$/
	      }, {
	        name: "Sieve",
	        mime: "application/sieve",
	        mode: "sieve",
	        ext: ["siv", "sieve"]
	      }, {
	        name: "Slim",
	        mimes: ["text/x-slim", "application/x-slim"],
	        mode: "slim",
	        ext: ["slim"]
	      }, {
	        name: "Smalltalk",
	        mime: "text/x-stsrc",
	        mode: "smalltalk",
	        ext: ["st"]
	      }, {
	        name: "Smarty",
	        mime: "text/x-smarty",
	        mode: "smarty",
	        ext: ["tpl"]
	      }, {
	        name: "Solr",
	        mime: "text/x-solr",
	        mode: "solr"
	      }, {
	        name: "SML",
	        mime: "text/x-sml",
	        mode: "mllike",
	        ext: ["sml", "sig", "fun", "smackspec"]
	      }, {
	        name: "Soy",
	        mime: "text/x-soy",
	        mode: "soy",
	        ext: ["soy"],
	        alias: ["closure template"]
	      }, {
	        name: "SPARQL",
	        mime: "application/sparql-query",
	        mode: "sparql",
	        ext: ["rq", "sparql"],
	        alias: ["sparul"]
	      }, {
	        name: "Spreadsheet",
	        mime: "text/x-spreadsheet",
	        mode: "spreadsheet",
	        alias: ["excel", "formula"]
	      }, {
	        name: "SQL",
	        mime: "text/x-sql",
	        mode: "sql",
	        ext: ["sql"]
	      }, {
	        name: "SQLite",
	        mime: "text/x-sqlite",
	        mode: "sql"
	      }, {
	        name: "Squirrel",
	        mime: "text/x-squirrel",
	        mode: "clike",
	        ext: ["nut"]
	      }, {
	        name: "Stylus",
	        mime: "text/x-styl",
	        mode: "stylus",
	        ext: ["styl"]
	      }, {
	        name: "Swift",
	        mime: "text/x-swift",
	        mode: "swift",
	        ext: ["swift"]
	      }, {
	        name: "sTeX",
	        mime: "text/x-stex",
	        mode: "stex"
	      }, {
	        name: "LaTeX",
	        mime: "text/x-latex",
	        mode: "stex",
	        ext: ["text", "ltx", "tex"],
	        alias: ["tex"]
	      }, {
	        name: "SystemVerilog",
	        mime: "text/x-systemverilog",
	        mode: "verilog",
	        ext: ["v", "sv", "svh"]
	      }, {
	        name: "Tcl",
	        mime: "text/x-tcl",
	        mode: "tcl",
	        ext: ["tcl"]
	      }, {
	        name: "Textile",
	        mime: "text/x-textile",
	        mode: "textile",
	        ext: ["textile"]
	      }, {
	        name: "TiddlyWiki",
	        mime: "text/x-tiddlywiki",
	        mode: "tiddlywiki"
	      }, {
	        name: "Tiki wiki",
	        mime: "text/tiki",
	        mode: "tiki"
	      }, {
	        name: "TOML",
	        mime: "text/x-toml",
	        mode: "toml",
	        ext: ["toml"]
	      }, {
	        name: "Tornado",
	        mime: "text/x-tornado",
	        mode: "tornado"
	      }, {
	        name: "troff",
	        mime: "text/troff",
	        mode: "troff",
	        ext: ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
	      }, {
	        name: "TTCN",
	        mime: "text/x-ttcn",
	        mode: "ttcn",
	        ext: ["ttcn", "ttcn3", "ttcnpp"]
	      }, {
	        name: "TTCN_CFG",
	        mime: "text/x-ttcn-cfg",
	        mode: "ttcn-cfg",
	        ext: ["cfg"]
	      }, {
	        name: "Turtle",
	        mime: "text/turtle",
	        mode: "turtle",
	        ext: ["ttl"]
	      }, {
	        name: "TypeScript",
	        mime: "application/typescript",
	        mode: "javascript",
	        ext: ["ts"],
	        alias: ["ts"]
	      }, {
	        name: "TypeScript-JSX",
	        mime: "text/typescript-jsx",
	        mode: "jsx",
	        ext: ["tsx"],
	        alias: ["tsx"]
	      }, {
	        name: "Twig",
	        mime: "text/x-twig",
	        mode: "twig"
	      }, {
	        name: "Web IDL",
	        mime: "text/x-webidl",
	        mode: "webidl",
	        ext: ["webidl"]
	      }, {
	        name: "VB.NET",
	        mime: "text/x-vb",
	        mode: "vb",
	        ext: ["vb"]
	      }, {
	        name: "VBScript",
	        mime: "text/vbscript",
	        mode: "vbscript",
	        ext: ["vbs"]
	      }, {
	        name: "Velocity",
	        mime: "text/velocity",
	        mode: "velocity",
	        ext: ["vtl"]
	      }, {
	        name: "Verilog",
	        mime: "text/x-verilog",
	        mode: "verilog",
	        ext: ["v"]
	      }, {
	        name: "VHDL",
	        mime: "text/x-vhdl",
	        mode: "vhdl",
	        ext: ["vhd", "vhdl"]
	      }, {
	        name: "Vue.js Component",
	        mimes: ["script/x-vue", "text/x-vue"],
	        mode: "vue",
	        ext: ["vue"]
	      }, {
	        name: "XML",
	        mimes: ["application/xml", "text/xml"],
	        mode: "xml",
	        ext: ["xml", "xsl", "xsd", "svg"],
	        alias: ["rss", "wsdl", "xsd"]
	      }, {
	        name: "XQuery",
	        mime: "application/xquery",
	        mode: "xquery",
	        ext: ["xy", "xquery"]
	      }, {
	        name: "Yacas",
	        mime: "text/x-yacas",
	        mode: "yacas",
	        ext: ["ys"]
	      }, {
	        name: "YAML",
	        mimes: ["text/x-yaml", "text/yaml"],
	        mode: "yaml",
	        ext: ["yaml", "yml"],
	        alias: ["yml"]
	      }, {
	        name: "Z80",
	        mime: "text/x-z80",
	        mode: "z80",
	        ext: ["z80"]
	      }, {
	        name: "mscgen",
	        mime: "text/x-mscgen",
	        mode: "mscgen",
	        ext: ["mscgen", "mscin", "msc"]
	      }, {
	        name: "xu",
	        mime: "text/x-xu",
	        mode: "mscgen",
	        ext: ["xu"]
	      }, {
	        name: "msgenny",
	        mime: "text/x-msgenny",
	        mode: "mscgen",
	        ext: ["msgenny"]
	      }, {
	        name: "WebAssembly",
	        mime: "text/webassembly",
	        mode: "wast",
	        ext: ["wat", "wast"]
	      }];
	      // Ensure all modes have a mime property for backwards compatibility
	      for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
	        var info = CodeMirror.modeInfo[i];
	        if (info.mimes) info.mime = info.mimes[0];
	      }
	      CodeMirror.findModeByMIME = function (mime) {
	        mime = mime.toLowerCase();
	        for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
	          var info = CodeMirror.modeInfo[i];
	          if (info.mime == mime) return info;
	          if (info.mimes) for (var j = 0; j < info.mimes.length; j++) if (info.mimes[j] == mime) return info;
	        }
	        if (/\+xml$/.test(mime)) return CodeMirror.findModeByMIME("application/xml");
	        if (/\+json$/.test(mime)) return CodeMirror.findModeByMIME("application/json");
	      };
	      CodeMirror.findModeByExtension = function (ext) {
	        ext = ext.toLowerCase();
	        for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
	          var info = CodeMirror.modeInfo[i];
	          if (info.ext) for (var j = 0; j < info.ext.length; j++) if (info.ext[j] == ext) return info;
	        }
	      };
	      CodeMirror.findModeByFileName = function (filename) {
	        for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
	          var info = CodeMirror.modeInfo[i];
	          if (info.file && info.file.test(filename)) return info;
	        }
	        var dot = filename.lastIndexOf(".");
	        var ext = dot > -1 && filename.substring(dot + 1, filename.length);
	        if (ext) return CodeMirror.findModeByExtension(ext);
	      };
	      CodeMirror.findModeByName = function (name) {
	        name = name.toLowerCase();
	        for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
	          var info = CodeMirror.modeInfo[i];
	          if (info.name.toLowerCase() == name) return info;
	          if (info.alias) for (var j = 0; j < info.alias.length; j++) if (info.alias[j].toLowerCase() == name) return info;
	        }
	      };
	    });
	  })();
	  return meta.exports;
	}

	var hasRequiredMarkdown;
	function requireMarkdown() {
	  if (hasRequiredMarkdown) return markdown.exports;
	  hasRequiredMarkdown = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror(), requireXml(), requireMeta());
	    })(function (CodeMirror) {

	      CodeMirror.defineMode("markdown", function (cmCfg, modeCfg) {
	        var htmlMode = CodeMirror.getMode(cmCfg, "text/html");
	        var htmlModeMissing = htmlMode.name == "null";
	        function getMode(name) {
	          if (CodeMirror.findModeByName) {
	            var found = CodeMirror.findModeByName(name);
	            if (found) name = found.mime || found.mimes[0];
	          }
	          var mode = CodeMirror.getMode(cmCfg, name);
	          return mode.name == "null" ? null : mode;
	        }

	        // Should characters that affect highlighting be highlighted separate?
	        // Does not include characters that will be output (such as `1.` and `-` for lists)
	        if (modeCfg.highlightFormatting === undefined) modeCfg.highlightFormatting = false;

	        // Maximum number of nested blockquotes. Set to 0 for infinite nesting.
	        // Excess `>` will emit `error` token.
	        if (modeCfg.maxBlockquoteDepth === undefined) modeCfg.maxBlockquoteDepth = 0;

	        // Turn on task lists? ("- [ ] " and "- [x] ")
	        if (modeCfg.taskLists === undefined) modeCfg.taskLists = false;

	        // Turn on strikethrough syntax
	        if (modeCfg.strikethrough === undefined) modeCfg.strikethrough = false;
	        if (modeCfg.emoji === undefined) modeCfg.emoji = false;
	        if (modeCfg.fencedCodeBlockHighlighting === undefined) modeCfg.fencedCodeBlockHighlighting = true;
	        if (modeCfg.fencedCodeBlockDefaultMode === undefined) modeCfg.fencedCodeBlockDefaultMode = 'text/plain';
	        if (modeCfg.xml === undefined) modeCfg.xml = true;

	        // Allow token types to be overridden by user-provided token types.
	        if (modeCfg.tokenTypeOverrides === undefined) modeCfg.tokenTypeOverrides = {};
	        var tokenTypes = {
	          header: "header",
	          code: "comment",
	          quote: "quote",
	          list1: "variable-2",
	          list2: "variable-3",
	          list3: "keyword",
	          hr: "hr",
	          image: "image",
	          imageAltText: "image-alt-text",
	          imageMarker: "image-marker",
	          formatting: "formatting",
	          linkInline: "link",
	          linkEmail: "link",
	          linkText: "link",
	          linkHref: "string",
	          em: "em",
	          strong: "strong",
	          strikethrough: "strikethrough",
	          emoji: "builtin"
	        };
	        for (var tokenType in tokenTypes) {
	          if (tokenTypes.hasOwnProperty(tokenType) && modeCfg.tokenTypeOverrides[tokenType]) {
	            tokenTypes[tokenType] = modeCfg.tokenTypeOverrides[tokenType];
	          }
	        }
	        var hrRE = /^([*\-_])(?:\s*\1){2,}\s*$/,
	          listRE = /^(?:[*\-+]|^[0-9]+([.)]))\s+/,
	          taskListRE = /^\[(x| )\](?=\s)/i // Must follow listRE
	          ,
	          atxHeaderRE = modeCfg.allowAtxHeaderWithoutSpace ? /^(#+)/ : /^(#+)(?: |$)/,
	          setextHeaderRE = /^ {0,3}(?:\={1,}|-{2,})\s*$/,
	          textRE = /^[^#!\[\]*_\\<>` "'(~:]+/,
	          fencedCodeRE = /^(~~~+|```+)[ \t]*([\w\/+#-]*)[^\n`]*$/,
	          linkDefRE = /^\s*\[[^\]]+?\]:.*$/ // naive link-definition
	          ,
	          punctuation = /[!"#$%&'()*+,\-.\/:;<=>?@\[\\\]^_`{|}~\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E42\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDF3C-\uDF3E]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]/,
	          expandedTab = "    "; // CommonMark specifies tab as 4 spaces

	        function switchInline(stream, state, f) {
	          state.f = state.inline = f;
	          return f(stream, state);
	        }
	        function switchBlock(stream, state, f) {
	          state.f = state.block = f;
	          return f(stream, state);
	        }
	        function lineIsEmpty(line) {
	          return !line || !/\S/.test(line.string);
	        }

	        // Blocks

	        function blankLine(state) {
	          // Reset linkTitle state
	          state.linkTitle = false;
	          state.linkHref = false;
	          state.linkText = false;
	          // Reset EM state
	          state.em = false;
	          // Reset STRONG state
	          state.strong = false;
	          // Reset strikethrough state
	          state.strikethrough = false;
	          // Reset state.quote
	          state.quote = 0;
	          // Reset state.indentedCode
	          state.indentedCode = false;
	          if (state.f == htmlBlock) {
	            var exit = htmlModeMissing;
	            if (!exit) {
	              var inner = CodeMirror.innerMode(htmlMode, state.htmlState);
	              exit = inner.mode.name == "xml" && inner.state.tagStart === null && !inner.state.context && inner.state.tokenize.isInText;
	            }
	            if (exit) {
	              state.f = inlineNormal;
	              state.block = blockNormal;
	              state.htmlState = null;
	            }
	          }
	          // Reset state.trailingSpace
	          state.trailingSpace = 0;
	          state.trailingSpaceNewLine = false;
	          // Mark this line as blank
	          state.prevLine = state.thisLine;
	          state.thisLine = {
	            stream: null
	          };
	          return null;
	        }
	        function blockNormal(stream, state) {
	          var firstTokenOnLine = stream.column() === state.indentation;
	          var prevLineLineIsEmpty = lineIsEmpty(state.prevLine.stream);
	          var prevLineIsIndentedCode = state.indentedCode;
	          var prevLineIsHr = state.prevLine.hr;
	          var prevLineIsList = state.list !== false;
	          var maxNonCodeIndentation = (state.listStack[state.listStack.length - 1] || 0) + 3;
	          state.indentedCode = false;
	          var lineIndentation = state.indentation;
	          // compute once per line (on first token)
	          if (state.indentationDiff === null) {
	            state.indentationDiff = state.indentation;
	            if (prevLineIsList) {
	              state.list = null;
	              // While this list item's marker's indentation is less than the deepest
	              //  list item's content's indentation,pop the deepest list item
	              //  indentation off the stack, and update block indentation state
	              while (lineIndentation < state.listStack[state.listStack.length - 1]) {
	                state.listStack.pop();
	                if (state.listStack.length) {
	                  state.indentation = state.listStack[state.listStack.length - 1];
	                  // less than the first list's indent -> the line is no longer a list
	                } else {
	                  state.list = false;
	                }
	              }
	              if (state.list !== false) {
	                state.indentationDiff = lineIndentation - state.listStack[state.listStack.length - 1];
	              }
	            }
	          }

	          // not comprehensive (currently only for setext detection purposes)
	          var allowsInlineContinuation = !prevLineLineIsEmpty && !prevLineIsHr && !state.prevLine.header && (!prevLineIsList || !prevLineIsIndentedCode) && !state.prevLine.fencedCodeEnd;
	          var isHr = (state.list === false || prevLineIsHr || prevLineLineIsEmpty) && state.indentation <= maxNonCodeIndentation && stream.match(hrRE);
	          var match = null;
	          if (state.indentationDiff >= 4 && (prevLineIsIndentedCode || state.prevLine.fencedCodeEnd || state.prevLine.header || prevLineLineIsEmpty)) {
	            stream.skipToEnd();
	            state.indentedCode = true;
	            return tokenTypes.code;
	          } else if (stream.eatSpace()) {
	            return null;
	          } else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(atxHeaderRE)) && match[1].length <= 6) {
	            state.quote = 0;
	            state.header = match[1].length;
	            state.thisLine.header = true;
	            if (modeCfg.highlightFormatting) state.formatting = "header";
	            state.f = state.inline;
	            return getType(state);
	          } else if (state.indentation <= maxNonCodeIndentation && stream.eat('>')) {
	            state.quote = firstTokenOnLine ? 1 : state.quote + 1;
	            if (modeCfg.highlightFormatting) state.formatting = "quote";
	            stream.eatSpace();
	            return getType(state);
	          } else if (!isHr && !state.setext && firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(listRE))) {
	            var listType = match[1] ? "ol" : "ul";
	            state.indentation = lineIndentation + stream.current().length;
	            state.list = true;
	            state.quote = 0;

	            // Add this list item's content's indentation to the stack
	            state.listStack.push(state.indentation);
	            // Reset inline styles which shouldn't propagate across list items
	            state.em = false;
	            state.strong = false;
	            state.code = false;
	            state.strikethrough = false;
	            if (modeCfg.taskLists && stream.match(taskListRE, false)) {
	              state.taskList = true;
	            }
	            state.f = state.inline;
	            if (modeCfg.highlightFormatting) state.formatting = ["list", "list-" + listType];
	            return getType(state);
	          } else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(fencedCodeRE, true))) {
	            state.quote = 0;
	            state.fencedEndRE = new RegExp(match[1] + "+ *$");
	            // try switching mode
	            state.localMode = modeCfg.fencedCodeBlockHighlighting && getMode(match[2] || modeCfg.fencedCodeBlockDefaultMode);
	            if (state.localMode) state.localState = CodeMirror.startState(state.localMode);
	            state.f = state.block = local;
	            if (modeCfg.highlightFormatting) state.formatting = "code-block";
	            state.code = -1;
	            return getType(state);
	            // SETEXT has lowest block-scope precedence after HR, so check it after
	            //  the others (code, blockquote, list...)
	          } else if (
	          // if setext set, indicates line after ---/===
	          state.setext ||
	          // line before ---/===
	          (!allowsInlineContinuation || !prevLineIsList) && !state.quote && state.list === false && !state.code && !isHr && !linkDefRE.test(stream.string) && (match = stream.lookAhead(1)) && (match = match.match(setextHeaderRE))) {
	            if (!state.setext) {
	              state.header = match[0].charAt(0) == '=' ? 1 : 2;
	              state.setext = state.header;
	            } else {
	              state.header = state.setext;
	              // has no effect on type so we can reset it now
	              state.setext = 0;
	              stream.skipToEnd();
	              if (modeCfg.highlightFormatting) state.formatting = "header";
	            }
	            state.thisLine.header = true;
	            state.f = state.inline;
	            return getType(state);
	          } else if (isHr) {
	            stream.skipToEnd();
	            state.hr = true;
	            state.thisLine.hr = true;
	            return tokenTypes.hr;
	          } else if (stream.peek() === '[') {
	            return switchInline(stream, state, footnoteLink);
	          }
	          return switchInline(stream, state, state.inline);
	        }
	        function htmlBlock(stream, state) {
	          var style = htmlMode.token(stream, state.htmlState);
	          if (!htmlModeMissing) {
	            var inner = CodeMirror.innerMode(htmlMode, state.htmlState);
	            if (inner.mode.name == "xml" && inner.state.tagStart === null && !inner.state.context && inner.state.tokenize.isInText || state.md_inside && stream.current().indexOf(">") > -1) {
	              state.f = inlineNormal;
	              state.block = blockNormal;
	              state.htmlState = null;
	            }
	          }
	          return style;
	        }
	        function local(stream, state) {
	          var currListInd = state.listStack[state.listStack.length - 1] || 0;
	          var hasExitedList = state.indentation < currListInd;
	          var maxFencedEndInd = currListInd + 3;
	          if (state.fencedEndRE && state.indentation <= maxFencedEndInd && (hasExitedList || stream.match(state.fencedEndRE))) {
	            if (modeCfg.highlightFormatting) state.formatting = "code-block";
	            var returnType;
	            if (!hasExitedList) returnType = getType(state);
	            state.localMode = state.localState = null;
	            state.block = blockNormal;
	            state.f = inlineNormal;
	            state.fencedEndRE = null;
	            state.code = 0;
	            state.thisLine.fencedCodeEnd = true;
	            if (hasExitedList) return switchBlock(stream, state, state.block);
	            return returnType;
	          } else if (state.localMode) {
	            return state.localMode.token(stream, state.localState);
	          } else {
	            stream.skipToEnd();
	            return tokenTypes.code;
	          }
	        }

	        // Inline
	        function getType(state) {
	          var styles = [];
	          if (state.formatting) {
	            styles.push(tokenTypes.formatting);
	            if (typeof state.formatting === "string") state.formatting = [state.formatting];
	            for (var i = 0; i < state.formatting.length; i++) {
	              styles.push(tokenTypes.formatting + "-" + state.formatting[i]);
	              if (state.formatting[i] === "header") {
	                styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.header);
	              }

	              // Add `formatting-quote` and `formatting-quote-#` for blockquotes
	              // Add `error` instead if the maximum blockquote nesting depth is passed
	              if (state.formatting[i] === "quote") {
	                if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
	                  styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.quote);
	                } else {
	                  styles.push("error");
	                }
	              }
	            }
	          }
	          if (state.taskOpen) {
	            styles.push("meta");
	            return styles.length ? styles.join(' ') : null;
	          }
	          if (state.taskClosed) {
	            styles.push("property");
	            return styles.length ? styles.join(' ') : null;
	          }
	          if (state.linkHref) {
	            styles.push(tokenTypes.linkHref, "url");
	          } else {
	            // Only apply inline styles to non-url text
	            if (state.strong) {
	              styles.push(tokenTypes.strong);
	            }
	            if (state.em) {
	              styles.push(tokenTypes.em);
	            }
	            if (state.strikethrough) {
	              styles.push(tokenTypes.strikethrough);
	            }
	            if (state.emoji) {
	              styles.push(tokenTypes.emoji);
	            }
	            if (state.linkText) {
	              styles.push(tokenTypes.linkText);
	            }
	            if (state.code) {
	              styles.push(tokenTypes.code);
	            }
	            if (state.image) {
	              styles.push(tokenTypes.image);
	            }
	            if (state.imageAltText) {
	              styles.push(tokenTypes.imageAltText, "link");
	            }
	            if (state.imageMarker) {
	              styles.push(tokenTypes.imageMarker);
	            }
	          }
	          if (state.header) {
	            styles.push(tokenTypes.header, tokenTypes.header + "-" + state.header);
	          }
	          if (state.quote) {
	            styles.push(tokenTypes.quote);

	            // Add `quote-#` where the maximum for `#` is modeCfg.maxBlockquoteDepth
	            if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
	              styles.push(tokenTypes.quote + "-" + state.quote);
	            } else {
	              styles.push(tokenTypes.quote + "-" + modeCfg.maxBlockquoteDepth);
	            }
	          }
	          if (state.list !== false) {
	            var listMod = (state.listStack.length - 1) % 3;
	            if (!listMod) {
	              styles.push(tokenTypes.list1);
	            } else if (listMod === 1) {
	              styles.push(tokenTypes.list2);
	            } else {
	              styles.push(tokenTypes.list3);
	            }
	          }
	          if (state.trailingSpaceNewLine) {
	            styles.push("trailing-space-new-line");
	          } else if (state.trailingSpace) {
	            styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b"));
	          }
	          return styles.length ? styles.join(' ') : null;
	        }
	        function handleText(stream, state) {
	          if (stream.match(textRE, true)) {
	            return getType(state);
	          }
	          return undefined;
	        }
	        function inlineNormal(stream, state) {
	          var style = state.text(stream, state);
	          if (typeof style !== 'undefined') return style;
	          if (state.list) {
	            // List marker (*, +, -, 1., etc)
	            state.list = null;
	            return getType(state);
	          }
	          if (state.taskList) {
	            var taskOpen = stream.match(taskListRE, true)[1] === " ";
	            if (taskOpen) state.taskOpen = true;else state.taskClosed = true;
	            if (modeCfg.highlightFormatting) state.formatting = "task";
	            state.taskList = false;
	            return getType(state);
	          }
	          state.taskOpen = false;
	          state.taskClosed = false;
	          if (state.header && stream.match(/^#+$/, true)) {
	            if (modeCfg.highlightFormatting) state.formatting = "header";
	            return getType(state);
	          }
	          var ch = stream.next();

	          // Matches link titles present on next line
	          if (state.linkTitle) {
	            state.linkTitle = false;
	            var matchCh = ch;
	            if (ch === '(') {
	              matchCh = ')';
	            }
	            matchCh = (matchCh + '').replace(/([.?*+^\[\]\\(){}|-])/g, "\\$1");
	            var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh;
	            if (stream.match(new RegExp(regex), true)) {
	              return tokenTypes.linkHref;
	            }
	          }

	          // If this block is changed, it may need to be updated in GFM mode
	          if (ch === '`') {
	            var previousFormatting = state.formatting;
	            if (modeCfg.highlightFormatting) state.formatting = "code";
	            stream.eatWhile('`');
	            var count = stream.current().length;
	            if (state.code == 0 && (!state.quote || count == 1)) {
	              state.code = count;
	              return getType(state);
	            } else if (count == state.code) {
	              // Must be exact
	              var t = getType(state);
	              state.code = 0;
	              return t;
	            } else {
	              state.formatting = previousFormatting;
	              return getType(state);
	            }
	          } else if (state.code) {
	            return getType(state);
	          }
	          if (ch === '\\') {
	            stream.next();
	            if (modeCfg.highlightFormatting) {
	              var type = getType(state);
	              var formattingEscape = tokenTypes.formatting + "-escape";
	              return type ? type + " " + formattingEscape : formattingEscape;
	            }
	          }
	          if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) {
	            state.imageMarker = true;
	            state.image = true;
	            if (modeCfg.highlightFormatting) state.formatting = "image";
	            return getType(state);
	          }
	          if (ch === '[' && state.imageMarker && stream.match(/[^\]]*\](\(.*?\)| ?\[.*?\])/, false)) {
	            state.imageMarker = false;
	            state.imageAltText = true;
	            if (modeCfg.highlightFormatting) state.formatting = "image";
	            return getType(state);
	          }
	          if (ch === ']' && state.imageAltText) {
	            if (modeCfg.highlightFormatting) state.formatting = "image";
	            var type = getType(state);
	            state.imageAltText = false;
	            state.image = false;
	            state.inline = state.f = linkHref;
	            return type;
	          }
	          if (ch === '[' && !state.image) {
	            if (state.linkText && stream.match(/^.*?\]/)) return getType(state);
	            state.linkText = true;
	            if (modeCfg.highlightFormatting) state.formatting = "link";
	            return getType(state);
	          }
	          if (ch === ']' && state.linkText) {
	            if (modeCfg.highlightFormatting) state.formatting = "link";
	            var type = getType(state);
	            state.linkText = false;
	            state.inline = state.f = stream.match(/\(.*?\)| ?\[.*?\]/, false) ? linkHref : inlineNormal;
	            return type;
	          }
	          if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) {
	            state.f = state.inline = linkInline;
	            if (modeCfg.highlightFormatting) state.formatting = "link";
	            var type = getType(state);
	            if (type) {
	              type += " ";
	            } else {
	              type = "";
	            }
	            return type + tokenTypes.linkInline;
	          }
	          if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) {
	            state.f = state.inline = linkInline;
	            if (modeCfg.highlightFormatting) state.formatting = "link";
	            var type = getType(state);
	            if (type) {
	              type += " ";
	            } else {
	              type = "";
	            }
	            return type + tokenTypes.linkEmail;
	          }
	          if (modeCfg.xml && ch === '<' && stream.match(/^(!--|\?|!\[CDATA\[|[a-z][a-z0-9-]*(?:\s+[a-z_:.\-]+(?:\s*=\s*[^>]+)?)*\s*(?:>|$))/i, false)) {
	            var end = stream.string.indexOf(">", stream.pos);
	            if (end != -1) {
	              var atts = stream.string.substring(stream.start, end);
	              if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) state.md_inside = true;
	            }
	            stream.backUp(1);
	            state.htmlState = CodeMirror.startState(htmlMode);
	            return switchBlock(stream, state, htmlBlock);
	          }
	          if (modeCfg.xml && ch === '<' && stream.match(/^\/\w*?>/)) {
	            state.md_inside = false;
	            return "tag";
	          } else if (ch === "*" || ch === "_") {
	            var len = 1,
	              before = stream.pos == 1 ? " " : stream.string.charAt(stream.pos - 2);
	            while (len < 3 && stream.eat(ch)) len++;
	            var after = stream.peek() || " ";
	            // See http://spec.commonmark.org/0.27/#emphasis-and-strong-emphasis
	            var leftFlanking = !/\s/.test(after) && (!punctuation.test(after) || /\s/.test(before) || punctuation.test(before));
	            var rightFlanking = !/\s/.test(before) && (!punctuation.test(before) || /\s/.test(after) || punctuation.test(after));
	            var setEm = null,
	              setStrong = null;
	            if (len % 2) {
	              // Em
	              if (!state.em && leftFlanking && (ch === "*" || !rightFlanking || punctuation.test(before))) setEm = true;else if (state.em == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation.test(after))) setEm = false;
	            }
	            if (len > 1) {
	              // Strong
	              if (!state.strong && leftFlanking && (ch === "*" || !rightFlanking || punctuation.test(before))) setStrong = true;else if (state.strong == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation.test(after))) setStrong = false;
	            }
	            if (setStrong != null || setEm != null) {
	              if (modeCfg.highlightFormatting) state.formatting = setEm == null ? "strong" : setStrong == null ? "em" : "strong em";
	              if (setEm === true) state.em = ch;
	              if (setStrong === true) state.strong = ch;
	              var t = getType(state);
	              if (setEm === false) state.em = false;
	              if (setStrong === false) state.strong = false;
	              return t;
	            }
	          } else if (ch === ' ') {
	            if (stream.eat('*') || stream.eat('_')) {
	              // Probably surrounded by spaces
	              if (stream.peek() === ' ') {
	                // Surrounded by spaces, ignore
	                return getType(state);
	              } else {
	                // Not surrounded by spaces, back up pointer
	                stream.backUp(1);
	              }
	            }
	          }
	          if (modeCfg.strikethrough) {
	            if (ch === '~' && stream.eatWhile(ch)) {
	              if (state.strikethrough) {
	                // Remove strikethrough
	                if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
	                var t = getType(state);
	                state.strikethrough = false;
	                return t;
	              } else if (stream.match(/^[^\s]/, false)) {
	                // Add strikethrough
	                state.strikethrough = true;
	                if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
	                return getType(state);
	              }
	            } else if (ch === ' ') {
	              if (stream.match('~~', true)) {
	                // Probably surrounded by space
	                if (stream.peek() === ' ') {
	                  // Surrounded by spaces, ignore
	                  return getType(state);
	                } else {
	                  // Not surrounded by spaces, back up pointer
	                  stream.backUp(2);
	                }
	              }
	            }
	          }
	          if (modeCfg.emoji && ch === ":" && stream.match(/^(?:[a-z_\d+][a-z_\d+-]*|\-[a-z_\d+][a-z_\d+-]*):/)) {
	            state.emoji = true;
	            if (modeCfg.highlightFormatting) state.formatting = "emoji";
	            var retType = getType(state);
	            state.emoji = false;
	            return retType;
	          }
	          if (ch === ' ') {
	            if (stream.match(/^ +$/, false)) {
	              state.trailingSpace++;
	            } else if (state.trailingSpace) {
	              state.trailingSpaceNewLine = true;
	            }
	          }
	          return getType(state);
	        }
	        function linkInline(stream, state) {
	          var ch = stream.next();
	          if (ch === ">") {
	            state.f = state.inline = inlineNormal;
	            if (modeCfg.highlightFormatting) state.formatting = "link";
	            var type = getType(state);
	            if (type) {
	              type += " ";
	            } else {
	              type = "";
	            }
	            return type + tokenTypes.linkInline;
	          }
	          stream.match(/^[^>]+/, true);
	          return tokenTypes.linkInline;
	        }
	        function linkHref(stream, state) {
	          // Check if space, and return NULL if so (to avoid marking the space)
	          if (stream.eatSpace()) {
	            return null;
	          }
	          var ch = stream.next();
	          if (ch === '(' || ch === '[') {
	            state.f = state.inline = getLinkHrefInside(ch === "(" ? ")" : "]");
	            if (modeCfg.highlightFormatting) state.formatting = "link-string";
	            state.linkHref = true;
	            return getType(state);
	          }
	          return 'error';
	        }
	        var linkRE = {
	          ")": /^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/,
	          "]": /^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\]]|\\.)*\])*?(?=\])/
	        };
	        function getLinkHrefInside(endChar) {
	          return function (stream, state) {
	            var ch = stream.next();
	            if (ch === endChar) {
	              state.f = state.inline = inlineNormal;
	              if (modeCfg.highlightFormatting) state.formatting = "link-string";
	              var returnState = getType(state);
	              state.linkHref = false;
	              return returnState;
	            }
	            stream.match(linkRE[endChar]);
	            state.linkHref = true;
	            return getType(state);
	          };
	        }
	        function footnoteLink(stream, state) {
	          if (stream.match(/^([^\]\\]|\\.)*\]:/, false)) {
	            state.f = footnoteLinkInside;
	            stream.next(); // Consume [
	            if (modeCfg.highlightFormatting) state.formatting = "link";
	            state.linkText = true;
	            return getType(state);
	          }
	          return switchInline(stream, state, inlineNormal);
	        }
	        function footnoteLinkInside(stream, state) {
	          if (stream.match(']:', true)) {
	            state.f = state.inline = footnoteUrl;
	            if (modeCfg.highlightFormatting) state.formatting = "link";
	            var returnType = getType(state);
	            state.linkText = false;
	            return returnType;
	          }
	          stream.match(/^([^\]\\]|\\.)+/, true);
	          return tokenTypes.linkText;
	        }
	        function footnoteUrl(stream, state) {
	          // Check if space, and return NULL if so (to avoid marking the space)
	          if (stream.eatSpace()) {
	            return null;
	          }
	          // Match URL
	          stream.match(/^[^\s]+/, true);
	          // Check for link title
	          if (stream.peek() === undefined) {
	            // End of line, set flag to check next line
	            state.linkTitle = true;
	          } else {
	            // More content on line, check if link title
	            stream.match(/^(?:\s+(?:"(?:[^"\\]|\\.)+"|'(?:[^'\\]|\\.)+'|\((?:[^)\\]|\\.)+\)))?/, true);
	          }
	          state.f = state.inline = inlineNormal;
	          return tokenTypes.linkHref + " url";
	        }
	        var mode = {
	          startState: function () {
	            return {
	              f: blockNormal,
	              prevLine: {
	                stream: null
	              },
	              thisLine: {
	                stream: null
	              },
	              block: blockNormal,
	              htmlState: null,
	              indentation: 0,
	              inline: inlineNormal,
	              text: handleText,
	              formatting: false,
	              linkText: false,
	              linkHref: false,
	              linkTitle: false,
	              code: 0,
	              em: false,
	              strong: false,
	              header: 0,
	              setext: 0,
	              hr: false,
	              taskList: false,
	              list: false,
	              listStack: [],
	              quote: 0,
	              trailingSpace: 0,
	              trailingSpaceNewLine: false,
	              strikethrough: false,
	              emoji: false,
	              fencedEndRE: null
	            };
	          },
	          copyState: function (s) {
	            return {
	              f: s.f,
	              prevLine: s.prevLine,
	              thisLine: s.thisLine,
	              block: s.block,
	              htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState),
	              indentation: s.indentation,
	              localMode: s.localMode,
	              localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null,
	              inline: s.inline,
	              text: s.text,
	              formatting: false,
	              linkText: s.linkText,
	              linkTitle: s.linkTitle,
	              linkHref: s.linkHref,
	              code: s.code,
	              em: s.em,
	              strong: s.strong,
	              strikethrough: s.strikethrough,
	              emoji: s.emoji,
	              header: s.header,
	              setext: s.setext,
	              hr: s.hr,
	              taskList: s.taskList,
	              list: s.list,
	              listStack: s.listStack.slice(0),
	              quote: s.quote,
	              indentedCode: s.indentedCode,
	              trailingSpace: s.trailingSpace,
	              trailingSpaceNewLine: s.trailingSpaceNewLine,
	              md_inside: s.md_inside,
	              fencedEndRE: s.fencedEndRE
	            };
	          },
	          token: function (stream, state) {
	            // Reset state.formatting
	            state.formatting = false;
	            if (stream != state.thisLine.stream) {
	              state.header = 0;
	              state.hr = false;
	              if (stream.match(/^\s*$/, true)) {
	                blankLine(state);
	                return null;
	              }
	              state.prevLine = state.thisLine;
	              state.thisLine = {
	                stream: stream
	              };

	              // Reset state.taskList
	              state.taskList = false;

	              // Reset state.trailingSpace
	              state.trailingSpace = 0;
	              state.trailingSpaceNewLine = false;
	              if (!state.localState) {
	                state.f = state.block;
	                if (state.f != htmlBlock) {
	                  var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, expandedTab).length;
	                  state.indentation = indentation;
	                  state.indentationDiff = null;
	                  if (indentation > 0) return null;
	                }
	              }
	            }
	            return state.f(stream, state);
	          },
	          innerMode: function (state) {
	            if (state.block == htmlBlock) return {
	              state: state.htmlState,
	              mode: htmlMode
	            };
	            if (state.localState) return {
	              state: state.localState,
	              mode: state.localMode
	            };
	            return {
	              state: state,
	              mode: mode
	            };
	          },
	          indent: function (state, textAfter, line) {
	            if (state.block == htmlBlock && htmlMode.indent) return htmlMode.indent(state.htmlState, textAfter, line);
	            if (state.localState && state.localMode.indent) return state.localMode.indent(state.localState, textAfter, line);
	            return CodeMirror.Pass;
	          },
	          blankLine: blankLine,
	          getType: getType,
	          blockCommentStart: "<!--",
	          blockCommentEnd: "-->",
	          closeBrackets: "()[]{}''\"\"``",
	          fold: "markdown"
	        };
	        return mode;
	      }, "xml");
	      CodeMirror.defineMIME("text/markdown", "markdown");
	      CodeMirror.defineMIME("text/x-markdown", "markdown");
	    });
	  })();
	  return markdown.exports;
	}

	var hasRequiredGfm;
	function requireGfm() {
	  if (hasRequiredGfm) return gfm.exports;
	  hasRequiredGfm = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror(), requireMarkdown(), requireOverlay());
	    })(function (CodeMirror) {

	      var urlRE = /^((?:(?:aaas?|about|acap|adiumxtra|af[ps]|aim|apt|attachment|aw|beshare|bitcoin|bolo|callto|cap|chrome(?:-extension)?|cid|coap|com-eventbrite-attendee|content|crid|cvs|data|dav|dict|dlna-(?:playcontainer|playsingle)|dns|doi|dtn|dvb|ed2k|facetime|feed|file|finger|fish|ftp|geo|gg|git|gizmoproject|go|gopher|gtalk|h323|hcp|https?|iax|icap|icon|im|imap|info|ipn|ipp|irc[6s]?|iris(?:\.beep|\.lwz|\.xpc|\.xpcs)?|itms|jar|javascript|jms|keyparc|lastfm|ldaps?|magnet|mailto|maps|market|message|mid|mms|ms-help|msnim|msrps?|mtqp|mumble|mupdate|mvn|news|nfs|nih?|nntp|notes|oid|opaquelocktoken|palm|paparazzi|platform|pop|pres|proxy|psyc|query|res(?:ource)?|rmi|rsync|rtmp|rtsp|secondlife|service|session|sftp|sgn|shttp|sieve|sips?|skype|sm[bs]|snmp|soap\.beeps?|soldat|spotify|ssh|steam|svn|tag|teamspeak|tel(?:net)?|tftp|things|thismessage|tip|tn3270|tv|udp|unreal|urn|ut2004|vemmi|ventrilo|view-source|webcal|wss?|wtai|wyciwyg|xcon(?:-userid)?|xfire|xmlrpc\.beeps?|xmpp|xri|ymsgr|z39\.50[rs]?):(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]|\([^\s()<>]*\))+(?:\([^\s()<>]*\)|[^\s`*!()\[\]{};:'".,<>?«»“”‘’]))/i;
	      CodeMirror.defineMode("gfm", function (config, modeConfig) {
	        var codeDepth = 0;
	        function blankLine(state) {
	          state.code = false;
	          return null;
	        }
	        var gfmOverlay = {
	          startState: function () {
	            return {
	              code: false,
	              codeBlock: false,
	              ateSpace: false
	            };
	          },
	          copyState: function (s) {
	            return {
	              code: s.code,
	              codeBlock: s.codeBlock,
	              ateSpace: s.ateSpace
	            };
	          },
	          token: function (stream, state) {
	            state.combineTokens = null;

	            // Hack to prevent formatting override inside code blocks (block and inline)
	            if (state.codeBlock) {
	              if (stream.match(/^```+/)) {
	                state.codeBlock = false;
	                return null;
	              }
	              stream.skipToEnd();
	              return null;
	            }
	            if (stream.sol()) {
	              state.code = false;
	            }
	            if (stream.sol() && stream.match(/^```+/)) {
	              stream.skipToEnd();
	              state.codeBlock = true;
	              return null;
	            }
	            // If this block is changed, it may need to be updated in Markdown mode
	            if (stream.peek() === '`') {
	              stream.next();
	              var before = stream.pos;
	              stream.eatWhile('`');
	              var difference = 1 + stream.pos - before;
	              if (!state.code) {
	                codeDepth = difference;
	                state.code = true;
	              } else {
	                if (difference === codeDepth) {
	                  // Must be exact
	                  state.code = false;
	                }
	              }
	              return null;
	            } else if (state.code) {
	              stream.next();
	              return null;
	            }
	            // Check if space. If so, links can be formatted later on
	            if (stream.eatSpace()) {
	              state.ateSpace = true;
	              return null;
	            }
	            if (stream.sol() || state.ateSpace) {
	              state.ateSpace = false;
	              if (modeConfig.gitHubSpice !== false) {
	                if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?=.{0,6}\d)(?:[a-f0-9]{7,40}\b)/)) {
	                  // User/Project@SHA
	                  // User@SHA
	                  // SHA
	                  state.combineTokens = true;
	                  return "link";
	                } else if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/)) {
	                  // User/Project#Num
	                  // User#Num
	                  // #Num
	                  state.combineTokens = true;
	                  return "link";
	                }
	              }
	            }
	            if (stream.match(urlRE) && stream.string.slice(stream.start - 2, stream.start) != "](" && (stream.start == 0 || /\W/.test(stream.string.charAt(stream.start - 1)))) {
	              // URLs
	              // Taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls
	              // And then (issue #1160) simplified to make it not crash the Chrome Regexp engine
	              // And then limited url schemes to the CommonMark list, so foo:bar isn't matched as a URL
	              state.combineTokens = true;
	              return "link";
	            }
	            stream.next();
	            return null;
	          },
	          blankLine: blankLine
	        };
	        var markdownConfig = {
	          taskLists: true,
	          strikethrough: true,
	          emoji: true
	        };
	        for (var attr in modeConfig) {
	          markdownConfig[attr] = modeConfig[attr];
	        }
	        markdownConfig.name = "markdown";
	        return CodeMirror.overlayMode(CodeMirror.getMode(config, markdownConfig), gfmOverlay);
	      }, "markdown");
	      CodeMirror.defineMIME("text/x-gfm", "gfm");
	    });
	  })();
	  return gfm.exports;
	}

	requireGfm();

	var go = {exports: {}};

	var hasRequiredGo;
	function requireGo() {
	  if (hasRequiredGo) return go.exports;
	  hasRequiredGo = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      CodeMirror.defineMode("go", function (config) {
	        var indentUnit = config.indentUnit;
	        var keywords = {
	          "break": true,
	          "case": true,
	          "chan": true,
	          "const": true,
	          "continue": true,
	          "default": true,
	          "defer": true,
	          "else": true,
	          "fallthrough": true,
	          "for": true,
	          "func": true,
	          "go": true,
	          "goto": true,
	          "if": true,
	          "import": true,
	          "interface": true,
	          "map": true,
	          "package": true,
	          "range": true,
	          "return": true,
	          "select": true,
	          "struct": true,
	          "switch": true,
	          "type": true,
	          "var": true,
	          "bool": true,
	          "byte": true,
	          "complex64": true,
	          "complex128": true,
	          "float32": true,
	          "float64": true,
	          "int8": true,
	          "int16": true,
	          "int32": true,
	          "int64": true,
	          "string": true,
	          "uint8": true,
	          "uint16": true,
	          "uint32": true,
	          "uint64": true,
	          "int": true,
	          "uint": true,
	          "uintptr": true,
	          "error": true,
	          "rune": true,
	          "any": true,
	          "comparable": true
	        };
	        var atoms = {
	          "true": true,
	          "false": true,
	          "iota": true,
	          "nil": true,
	          "append": true,
	          "cap": true,
	          "close": true,
	          "complex": true,
	          "copy": true,
	          "delete": true,
	          "imag": true,
	          "len": true,
	          "make": true,
	          "new": true,
	          "panic": true,
	          "print": true,
	          "println": true,
	          "real": true,
	          "recover": true
	        };
	        var isOperatorChar = /[+\-*&^%:=<>!|\/]/;
	        var curPunc;
	        function tokenBase(stream, state) {
	          var ch = stream.next();
	          if (ch == '"' || ch == "'" || ch == "`") {
	            state.tokenize = tokenString(ch);
	            return state.tokenize(stream, state);
	          }
	          if (/[\d\.]/.test(ch)) {
	            if (ch == ".") {
	              stream.match(/^[0-9_]+([eE][\-+]?[0-9_]+)?/);
	            } else if (ch == "0") {
	              stream.match(/^[xX][0-9a-fA-F_]+/) || stream.match(/^[0-7_]+/);
	            } else {
	              stream.match(/^[0-9_]*\.?[0-9_]*([eE][\-+]?[0-9_]+)?/);
	            }
	            return "number";
	          }
	          if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
	            curPunc = ch;
	            return null;
	          }
	          if (ch == "/") {
	            if (stream.eat("*")) {
	              state.tokenize = tokenComment;
	              return tokenComment(stream, state);
	            }
	            if (stream.eat("/")) {
	              stream.skipToEnd();
	              return "comment";
	            }
	          }
	          if (isOperatorChar.test(ch)) {
	            stream.eatWhile(isOperatorChar);
	            return "operator";
	          }
	          stream.eatWhile(/[\w\$_\xa1-\uffff]/);
	          var cur = stream.current();
	          if (keywords.propertyIsEnumerable(cur)) {
	            if (cur == "case" || cur == "default") curPunc = "case";
	            return "keyword";
	          }
	          if (atoms.propertyIsEnumerable(cur)) return "atom";
	          return "variable";
	        }
	        function tokenString(quote) {
	          return function (stream, state) {
	            var escaped = false,
	              next,
	              end = false;
	            while ((next = stream.next()) != null) {
	              if (next == quote && !escaped) {
	                end = true;
	                break;
	              }
	              escaped = !escaped && quote != "`" && next == "\\";
	            }
	            if (end || !(escaped || quote == "`")) state.tokenize = tokenBase;
	            return "string";
	          };
	        }
	        function tokenComment(stream, state) {
	          var maybeEnd = false,
	            ch;
	          while (ch = stream.next()) {
	            if (ch == "/" && maybeEnd) {
	              state.tokenize = tokenBase;
	              break;
	            }
	            maybeEnd = ch == "*";
	          }
	          return "comment";
	        }
	        function Context(indented, column, type, align, prev) {
	          this.indented = indented;
	          this.column = column;
	          this.type = type;
	          this.align = align;
	          this.prev = prev;
	        }
	        function pushContext(state, col, type) {
	          return state.context = new Context(state.indented, col, type, null, state.context);
	        }
	        function popContext(state) {
	          if (!state.context.prev) return;
	          var t = state.context.type;
	          if (t == ")" || t == "]" || t == "}") state.indented = state.context.indented;
	          return state.context = state.context.prev;
	        }

	        // Interface

	        return {
	          startState: function (basecolumn) {
	            return {
	              tokenize: null,
	              context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
	              indented: 0,
	              startOfLine: true
	            };
	          },
	          token: function (stream, state) {
	            var ctx = state.context;
	            if (stream.sol()) {
	              if (ctx.align == null) ctx.align = false;
	              state.indented = stream.indentation();
	              state.startOfLine = true;
	              if (ctx.type == "case") ctx.type = "}";
	            }
	            if (stream.eatSpace()) return null;
	            curPunc = null;
	            var style = (state.tokenize || tokenBase)(stream, state);
	            if (style == "comment") return style;
	            if (ctx.align == null) ctx.align = true;
	            if (curPunc == "{") pushContext(state, stream.column(), "}");else if (curPunc == "[") pushContext(state, stream.column(), "]");else if (curPunc == "(") pushContext(state, stream.column(), ")");else if (curPunc == "case") ctx.type = "case";else if (curPunc == "}" && ctx.type == "}") popContext(state);else if (curPunc == ctx.type) popContext(state);
	            state.startOfLine = false;
	            return style;
	          },
	          indent: function (state, textAfter) {
	            if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
	            var ctx = state.context,
	              firstChar = textAfter && textAfter.charAt(0);
	            if (ctx.type == "case" && /^(?:case|default)\b/.test(textAfter)) {
	              state.context.type = "}";
	              return ctx.indented;
	            }
	            var closing = firstChar == ctx.type;
	            if (ctx.align) return ctx.column + (closing ? 0 : 1);else return ctx.indented + (closing ? 0 : indentUnit);
	          },
	          electricChars: "{}):",
	          closeBrackets: "()[]{}''\"\"``",
	          fold: "brace",
	          blockCommentStart: "/*",
	          blockCommentEnd: "*/",
	          lineComment: "//"
	        };
	      });
	      CodeMirror.defineMIME("text/x-go", "go");
	    });
	  })();
	  return go.exports;
	}

	requireGo();

	var htmlmixed = {exports: {}};

	var javascript = {exports: {}};

	var hasRequiredJavascript;
	function requireJavascript() {
	  if (hasRequiredJavascript) return javascript.exports;
	  hasRequiredJavascript = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      CodeMirror.defineMode("javascript", function (config, parserConfig) {
	        var indentUnit = config.indentUnit;
	        var statementIndent = parserConfig.statementIndent;
	        var jsonldMode = parserConfig.jsonld;
	        var jsonMode = parserConfig.json || jsonldMode;
	        var trackScope = parserConfig.trackScope !== false;
	        var isTS = parserConfig.typescript;
	        var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;

	        // Tokenizer

	        var keywords = function () {
	          function kw(type) {
	            return {
	              type: type,
	              style: "keyword"
	            };
	          }
	          var A = kw("keyword a"),
	            B = kw("keyword b"),
	            C = kw("keyword c"),
	            D = kw("keyword d");
	          var operator = kw("operator"),
	            atom = {
	              type: "atom",
	              style: "atom"
	            };
	          return {
	            "if": kw("if"),
	            "while": A,
	            "with": A,
	            "else": B,
	            "do": B,
	            "try": B,
	            "finally": B,
	            "return": D,
	            "break": D,
	            "continue": D,
	            "new": kw("new"),
	            "delete": C,
	            "void": C,
	            "throw": C,
	            "debugger": kw("debugger"),
	            "var": kw("var"),
	            "const": kw("var"),
	            "let": kw("var"),
	            "function": kw("function"),
	            "catch": kw("catch"),
	            "for": kw("for"),
	            "switch": kw("switch"),
	            "case": kw("case"),
	            "default": kw("default"),
	            "in": operator,
	            "typeof": operator,
	            "instanceof": operator,
	            "true": atom,
	            "false": atom,
	            "null": atom,
	            "undefined": atom,
	            "NaN": atom,
	            "Infinity": atom,
	            "this": kw("this"),
	            "class": kw("class"),
	            "super": kw("atom"),
	            "yield": C,
	            "export": kw("export"),
	            "import": kw("import"),
	            "extends": C,
	            "await": C
	          };
	        }();
	        var isOperatorChar = /[+\-*&%=<>!?|~^@]/;
	        var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
	        function readRegexp(stream) {
	          var escaped = false,
	            next,
	            inSet = false;
	          while ((next = stream.next()) != null) {
	            if (!escaped) {
	              if (next == "/" && !inSet) return;
	              if (next == "[") inSet = true;else if (inSet && next == "]") inSet = false;
	            }
	            escaped = !escaped && next == "\\";
	          }
	        }

	        // Used as scratch variables to communicate multiple values without
	        // consing up tons of objects.
	        var type, content;
	        function ret(tp, style, cont) {
	          type = tp;
	          content = cont;
	          return style;
	        }
	        function tokenBase(stream, state) {
	          var ch = stream.next();
	          if (ch == '"' || ch == "'") {
	            state.tokenize = tokenString(ch);
	            return state.tokenize(stream, state);
	          } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) {
	            return ret("number", "number");
	          } else if (ch == "." && stream.match("..")) {
	            return ret("spread", "meta");
	          } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
	            return ret(ch);
	          } else if (ch == "=" && stream.eat(">")) {
	            return ret("=>", "operator");
	          } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) {
	            return ret("number", "number");
	          } else if (/\d/.test(ch)) {
	            stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/);
	            return ret("number", "number");
	          } else if (ch == "/") {
	            if (stream.eat("*")) {
	              state.tokenize = tokenComment;
	              return tokenComment(stream, state);
	            } else if (stream.eat("/")) {
	              stream.skipToEnd();
	              return ret("comment", "comment");
	            } else if (expressionAllowed(stream, state, 1)) {
	              readRegexp(stream);
	              stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/);
	              return ret("regexp", "string-2");
	            } else {
	              stream.eat("=");
	              return ret("operator", "operator", stream.current());
	            }
	          } else if (ch == "`") {
	            state.tokenize = tokenQuasi;
	            return tokenQuasi(stream, state);
	          } else if (ch == "#" && stream.peek() == "!") {
	            stream.skipToEnd();
	            return ret("meta", "meta");
	          } else if (ch == "#" && stream.eatWhile(wordRE)) {
	            return ret("variable", "property");
	          } else if (ch == "<" && stream.match("!--") || ch == "-" && stream.match("->") && !/\S/.test(stream.string.slice(0, stream.start))) {
	            stream.skipToEnd();
	            return ret("comment", "comment");
	          } else if (isOperatorChar.test(ch)) {
	            if (ch != ">" || !state.lexical || state.lexical.type != ">") {
	              if (stream.eat("=")) {
	                if (ch == "!" || ch == "=") stream.eat("=");
	              } else if (/[<>*+\-|&?]/.test(ch)) {
	                stream.eat(ch);
	                if (ch == ">") stream.eat(ch);
	              }
	            }
	            if (ch == "?" && stream.eat(".")) return ret(".");
	            return ret("operator", "operator", stream.current());
	          } else if (wordRE.test(ch)) {
	            stream.eatWhile(wordRE);
	            var word = stream.current();
	            if (state.lastType != ".") {
	              if (keywords.propertyIsEnumerable(word)) {
	                var kw = keywords[word];
	                return ret(kw.type, kw.style, word);
	              }
	              if (word == "async" && stream.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/, false)) return ret("async", "keyword", word);
	            }
	            return ret("variable", "variable", word);
	          }
	        }
	        function tokenString(quote) {
	          return function (stream, state) {
	            var escaped = false,
	              next;
	            if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)) {
	              state.tokenize = tokenBase;
	              return ret("jsonld-keyword", "meta");
	            }
	            while ((next = stream.next()) != null) {
	              if (next == quote && !escaped) break;
	              escaped = !escaped && next == "\\";
	            }
	            if (!escaped) state.tokenize = tokenBase;
	            return ret("string", "string");
	          };
	        }
	        function tokenComment(stream, state) {
	          var maybeEnd = false,
	            ch;
	          while (ch = stream.next()) {
	            if (ch == "/" && maybeEnd) {
	              state.tokenize = tokenBase;
	              break;
	            }
	            maybeEnd = ch == "*";
	          }
	          return ret("comment", "comment");
	        }
	        function tokenQuasi(stream, state) {
	          var escaped = false,
	            next;
	          while ((next = stream.next()) != null) {
	            if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
	              state.tokenize = tokenBase;
	              break;
	            }
	            escaped = !escaped && next == "\\";
	          }
	          return ret("quasi", "string-2", stream.current());
	        }
	        var brackets = "([{}])";
	        // This is a crude lookahead trick to try and notice that we're
	        // parsing the argument patterns for a fat-arrow function before we
	        // actually hit the arrow token. It only works if the arrow is on
	        // the same line as the arguments and there's no strange noise
	        // (comments) in between. Fallback is to only notice when we hit the
	        // arrow, and not declare the arguments as locals for the arrow
	        // body.
	        function findFatArrow(stream, state) {
	          if (state.fatArrowAt) state.fatArrowAt = null;
	          var arrow = stream.string.indexOf("=>", stream.start);
	          if (arrow < 0) return;
	          if (isTS) {
	            // Try to skip TypeScript return type declarations after the arguments
	            var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow));
	            if (m) arrow = m.index;
	          }
	          var depth = 0,
	            sawSomething = false;
	          for (var pos = arrow - 1; pos >= 0; --pos) {
	            var ch = stream.string.charAt(pos);
	            var bracket = brackets.indexOf(ch);
	            if (bracket >= 0 && bracket < 3) {
	              if (!depth) {
	                ++pos;
	                break;
	              }
	              if (--depth == 0) {
	                if (ch == "(") sawSomething = true;
	                break;
	              }
	            } else if (bracket >= 3 && bracket < 6) {
	              ++depth;
	            } else if (wordRE.test(ch)) {
	              sawSomething = true;
	            } else if (/["'\/`]/.test(ch)) {
	              for (;; --pos) {
	                if (pos == 0) return;
	                var next = stream.string.charAt(pos - 1);
	                if (next == ch && stream.string.charAt(pos - 2) != "\\") {
	                  pos--;
	                  break;
	                }
	              }
	            } else if (sawSomething && !depth) {
	              ++pos;
	              break;
	            }
	          }
	          if (sawSomething && !depth) state.fatArrowAt = pos;
	        }

	        // Parser

	        var atomicTypes = {
	          "atom": true,
	          "number": true,
	          "variable": true,
	          "string": true,
	          "regexp": true,
	          "this": true,
	          "import": true,
	          "jsonld-keyword": true
	        };
	        function JSLexical(indented, column, type, align, prev, info) {
	          this.indented = indented;
	          this.column = column;
	          this.type = type;
	          this.prev = prev;
	          this.info = info;
	          if (align != null) this.align = align;
	        }
	        function inScope(state, varname) {
	          if (!trackScope) return false;
	          for (var v = state.localVars; v; v = v.next) if (v.name == varname) return true;
	          for (var cx = state.context; cx; cx = cx.prev) {
	            for (var v = cx.vars; v; v = v.next) if (v.name == varname) return true;
	          }
	        }
	        function parseJS(state, style, type, content, stream) {
	          var cc = state.cc;
	          // Communicate our context to the combinators.
	          // (Less wasteful than consing up a hundred closures on every call.)
	          cx.state = state;
	          cx.stream = stream;
	          cx.marked = null, cx.cc = cc;
	          cx.style = style;
	          if (!state.lexical.hasOwnProperty("align")) state.lexical.align = true;
	          while (true) {
	            var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
	            if (combinator(type, content)) {
	              while (cc.length && cc[cc.length - 1].lex) cc.pop()();
	              if (cx.marked) return cx.marked;
	              if (type == "variable" && inScope(state, content)) return "variable-2";
	              return style;
	            }
	          }
	        }

	        // Combinator utils

	        var cx = {
	          state: null,
	          marked: null,
	          cc: null
	        };
	        function pass() {
	          for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
	        }
	        function cont() {
	          pass.apply(null, arguments);
	          return true;
	        }
	        function inList(name, list) {
	          for (var v = list; v; v = v.next) if (v.name == name) return true;
	          return false;
	        }
	        function register(varname) {
	          var state = cx.state;
	          cx.marked = "def";
	          if (!trackScope) return;
	          if (state.context) {
	            if (state.lexical.info == "var" && state.context && state.context.block) {
	              // FIXME function decls are also not block scoped
	              var newContext = registerVarScoped(varname, state.context);
	              if (newContext != null) {
	                state.context = newContext;
	                return;
	              }
	            } else if (!inList(varname, state.localVars)) {
	              state.localVars = new Var(varname, state.localVars);
	              return;
	            }
	          }
	          // Fall through means this is global
	          if (parserConfig.globalVars && !inList(varname, state.globalVars)) state.globalVars = new Var(varname, state.globalVars);
	        }
	        function registerVarScoped(varname, context) {
	          if (!context) {
	            return null;
	          } else if (context.block) {
	            var inner = registerVarScoped(varname, context.prev);
	            if (!inner) return null;
	            if (inner == context.prev) return context;
	            return new Context(inner, context.vars, true);
	          } else if (inList(varname, context.vars)) {
	            return context;
	          } else {
	            return new Context(context.prev, new Var(varname, context.vars), false);
	          }
	        }
	        function isModifier(name) {
	          return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly";
	        }

	        // Combinators

	        function Context(prev, vars, block) {
	          this.prev = prev;
	          this.vars = vars;
	          this.block = block;
	        }
	        function Var(name, next) {
	          this.name = name;
	          this.next = next;
	        }
	        var defaultVars = new Var("this", new Var("arguments", null));
	        function pushcontext() {
	          cx.state.context = new Context(cx.state.context, cx.state.localVars, false);
	          cx.state.localVars = defaultVars;
	        }
	        function pushblockcontext() {
	          cx.state.context = new Context(cx.state.context, cx.state.localVars, true);
	          cx.state.localVars = null;
	        }
	        pushcontext.lex = pushblockcontext.lex = true;
	        function popcontext() {
	          cx.state.localVars = cx.state.context.vars;
	          cx.state.context = cx.state.context.prev;
	        }
	        popcontext.lex = true;
	        function pushlex(type, info) {
	          var result = function () {
	            var state = cx.state,
	              indent = state.indented;
	            if (state.lexical.type == "stat") indent = state.lexical.indented;else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) indent = outer.indented;
	            state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
	          };
	          result.lex = true;
	          return result;
	        }
	        function poplex() {
	          var state = cx.state;
	          if (state.lexical.prev) {
	            if (state.lexical.type == ")") state.indented = state.lexical.indented;
	            state.lexical = state.lexical.prev;
	          }
	        }
	        poplex.lex = true;
	        function expect(wanted) {
	          function exp(type) {
	            if (type == wanted) return cont();else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass();else return cont(exp);
	          }
	          return exp;
	        }
	        function statement(type, value) {
	          if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex);
	          if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex);
	          if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
	          if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex);
	          if (type == "debugger") return cont(expect(";"));
	          if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext);
	          if (type == ";") return cont();
	          if (type == "if") {
	            if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) cx.state.cc.pop()();
	            return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse);
	          }
	          if (type == "function") return cont(functiondef);
	          if (type == "for") return cont(pushlex("form"), pushblockcontext, forspec, statement, popcontext, poplex);
	          if (type == "class" || isTS && value == "interface") {
	            cx.marked = "keyword";
	            return cont(pushlex("form", type == "class" ? type : value), className, poplex);
	          }
	          if (type == "variable") {
	            if (isTS && value == "declare") {
	              cx.marked = "keyword";
	              return cont(statement);
	            } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) {
	              cx.marked = "keyword";
	              if (value == "enum") return cont(enumdef);else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";"));else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex);
	            } else if (isTS && value == "namespace") {
	              cx.marked = "keyword";
	              return cont(pushlex("form"), expression, statement, poplex);
	            } else if (isTS && value == "abstract") {
	              cx.marked = "keyword";
	              return cont(statement);
	            } else {
	              return cont(pushlex("stat"), maybelabel);
	            }
	          }
	          if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext, block, poplex, poplex, popcontext);
	          if (type == "case") return cont(expression, expect(":"));
	          if (type == "default") return cont(expect(":"));
	          if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext);
	          if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
	          if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
	          if (type == "async") return cont(statement);
	          if (value == "@") return cont(expression, statement);
	          return pass(pushlex("stat"), expression, expect(";"), poplex);
	        }
	        function maybeCatchBinding(type) {
	          if (type == "(") return cont(funarg, expect(")"));
	        }
	        function expression(type, value) {
	          return expressionInner(type, value, false);
	        }
	        function expressionNoComma(type, value) {
	          return expressionInner(type, value, true);
	        }
	        function parenExpr(type) {
	          if (type != "(") return pass();
	          return cont(pushlex(")"), maybeexpression, expect(")"), poplex);
	        }
	        function expressionInner(type, value, noComma) {
	          if (cx.state.fatArrowAt == cx.stream.start) {
	            var body = noComma ? arrowBodyNoComma : arrowBody;
	            if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext);else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
	          }
	          var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
	          if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
	          if (type == "function") return cont(functiondef, maybeop);
	          if (type == "class" || isTS && value == "interface") {
	            cx.marked = "keyword";
	            return cont(pushlex("form"), classExpression, poplex);
	          }
	          if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression);
	          if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop);
	          if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
	          if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
	          if (type == "{") return contCommasep(objprop, "}", null, maybeop);
	          if (type == "quasi") return pass(quasi, maybeop);
	          if (type == "new") return cont(maybeTarget(noComma));
	          return cont();
	        }
	        function maybeexpression(type) {
	          if (type.match(/[;\}\)\],]/)) return pass();
	          return pass(expression);
	        }
	        function maybeoperatorComma(type, value) {
	          if (type == ",") return cont(maybeexpression);
	          return maybeoperatorNoComma(type, value, false);
	        }
	        function maybeoperatorNoComma(type, value, noComma) {
	          var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
	          var expr = noComma == false ? expression : expressionNoComma;
	          if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
	          if (type == "operator") {
	            if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me);
	            if (isTS && value == "<" && cx.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/, false)) return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me);
	            if (value == "?") return cont(expression, expect(":"), expr);
	            return cont(expr);
	          }
	          if (type == "quasi") {
	            return pass(quasi, me);
	          }
	          if (type == ";") return;
	          if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
	          if (type == ".") return cont(property, me);
	          if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
	          if (isTS && value == "as") {
	            cx.marked = "keyword";
	            return cont(typeexpr, me);
	          }
	          if (type == "regexp") {
	            cx.state.lastType = cx.marked = "operator";
	            cx.stream.backUp(cx.stream.pos - cx.stream.start - 1);
	            return cont(expr);
	          }
	        }
	        function quasi(type, value) {
	          if (type != "quasi") return pass();
	          if (value.slice(value.length - 2) != "${") return cont(quasi);
	          return cont(maybeexpression, continueQuasi);
	        }
	        function continueQuasi(type) {
	          if (type == "}") {
	            cx.marked = "string-2";
	            cx.state.tokenize = tokenQuasi;
	            return cont(quasi);
	          }
	        }
	        function arrowBody(type) {
	          findFatArrow(cx.stream, cx.state);
	          return pass(type == "{" ? statement : expression);
	        }
	        function arrowBodyNoComma(type) {
	          findFatArrow(cx.stream, cx.state);
	          return pass(type == "{" ? statement : expressionNoComma);
	        }
	        function maybeTarget(noComma) {
	          return function (type) {
	            if (type == ".") return cont(noComma ? targetNoComma : target);else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma);else return pass(noComma ? expressionNoComma : expression);
	          };
	        }
	        function target(_, value) {
	          if (value == "target") {
	            cx.marked = "keyword";
	            return cont(maybeoperatorComma);
	          }
	        }
	        function targetNoComma(_, value) {
	          if (value == "target") {
	            cx.marked = "keyword";
	            return cont(maybeoperatorNoComma);
	          }
	        }
	        function maybelabel(type) {
	          if (type == ":") return cont(poplex, statement);
	          return pass(maybeoperatorComma, expect(";"), poplex);
	        }
	        function property(type) {
	          if (type == "variable") {
	            cx.marked = "property";
	            return cont();
	          }
	        }
	        function objprop(type, value) {
	          if (type == "async") {
	            cx.marked = "property";
	            return cont(objprop);
	          } else if (type == "variable" || cx.style == "keyword") {
	            cx.marked = "property";
	            if (value == "get" || value == "set") return cont(getterSetter);
	            var m; // Work around fat-arrow-detection complication for detecting typescript typed arrow params
	            if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) cx.state.fatArrowAt = cx.stream.pos + m[0].length;
	            return cont(afterprop);
	          } else if (type == "number" || type == "string") {
	            cx.marked = jsonldMode ? "property" : cx.style + " property";
	            return cont(afterprop);
	          } else if (type == "jsonld-keyword") {
	            return cont(afterprop);
	          } else if (isTS && isModifier(value)) {
	            cx.marked = "keyword";
	            return cont(objprop);
	          } else if (type == "[") {
	            return cont(expression, maybetype, expect("]"), afterprop);
	          } else if (type == "spread") {
	            return cont(expressionNoComma, afterprop);
	          } else if (value == "*") {
	            cx.marked = "keyword";
	            return cont(objprop);
	          } else if (type == ":") {
	            return pass(afterprop);
	          }
	        }
	        function getterSetter(type) {
	          if (type != "variable") return pass(afterprop);
	          cx.marked = "property";
	          return cont(functiondef);
	        }
	        function afterprop(type) {
	          if (type == ":") return cont(expressionNoComma);
	          if (type == "(") return pass(functiondef);
	        }
	        function commasep(what, end, sep) {
	          function proceed(type, value) {
	            if (sep ? sep.indexOf(type) > -1 : type == ",") {
	              var lex = cx.state.lexical;
	              if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
	              return cont(function (type, value) {
	                if (type == end || value == end) return pass();
	                return pass(what);
	              }, proceed);
	            }
	            if (type == end || value == end) return cont();
	            if (sep && sep.indexOf(";") > -1) return pass(what);
	            return cont(expect(end));
	          }
	          return function (type, value) {
	            if (type == end || value == end) return cont();
	            return pass(what, proceed);
	          };
	        }
	        function contCommasep(what, end, info) {
	          for (var i = 3; i < arguments.length; i++) cx.cc.push(arguments[i]);
	          return cont(pushlex(end, info), commasep(what, end), poplex);
	        }
	        function block(type) {
	          if (type == "}") return cont();
	          return pass(statement, block);
	        }
	        function maybetype(type, value) {
	          if (isTS) {
	            if (type == ":") return cont(typeexpr);
	            if (value == "?") return cont(maybetype);
	          }
	        }
	        function maybetypeOrIn(type, value) {
	          if (isTS && (type == ":" || value == "in")) return cont(typeexpr);
	        }
	        function mayberettype(type) {
	          if (isTS && type == ":") {
	            if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr);else return cont(typeexpr);
	          }
	        }
	        function isKW(_, value) {
	          if (value == "is") {
	            cx.marked = "keyword";
	            return cont();
	          }
	        }
	        function typeexpr(type, value) {
	          if (value == "keyof" || value == "typeof" || value == "infer" || value == "readonly") {
	            cx.marked = "keyword";
	            return cont(value == "typeof" ? expressionNoComma : typeexpr);
	          }
	          if (type == "variable" || value == "void") {
	            cx.marked = "type";
	            return cont(afterType);
	          }
	          if (value == "|" || value == "&") return cont(typeexpr);
	          if (type == "string" || type == "number" || type == "atom") return cont(afterType);
	          if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType);
	          if (type == "{") return cont(pushlex("}"), typeprops, poplex, afterType);
	          if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType);
	          if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr);
	          if (type == "quasi") {
	            return pass(quasiType, afterType);
	          }
	        }
	        function maybeReturnType(type) {
	          if (type == "=>") return cont(typeexpr);
	        }
	        function typeprops(type) {
	          if (type.match(/[\}\)\]]/)) return cont();
	          if (type == "," || type == ";") return cont(typeprops);
	          return pass(typeprop, typeprops);
	        }
	        function typeprop(type, value) {
	          if (type == "variable" || cx.style == "keyword") {
	            cx.marked = "property";
	            return cont(typeprop);
	          } else if (value == "?" || type == "number" || type == "string") {
	            return cont(typeprop);
	          } else if (type == ":") {
	            return cont(typeexpr);
	          } else if (type == "[") {
	            return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop);
	          } else if (type == "(") {
	            return pass(functiondecl, typeprop);
	          } else if (!type.match(/[;\}\)\],]/)) {
	            return cont();
	          }
	        }
	        function quasiType(type, value) {
	          if (type != "quasi") return pass();
	          if (value.slice(value.length - 2) != "${") return cont(quasiType);
	          return cont(typeexpr, continueQuasiType);
	        }
	        function continueQuasiType(type) {
	          if (type == "}") {
	            cx.marked = "string-2";
	            cx.state.tokenize = tokenQuasi;
	            return cont(quasiType);
	          }
	        }
	        function typearg(type, value) {
	          if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg);
	          if (type == ":") return cont(typeexpr);
	          if (type == "spread") return cont(typearg);
	          return pass(typeexpr);
	        }
	        function afterType(type, value) {
	          if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType);
	          if (value == "|" || type == "." || value == "&") return cont(typeexpr);
	          if (type == "[") return cont(typeexpr, expect("]"), afterType);
	          if (value == "extends" || value == "implements") {
	            cx.marked = "keyword";
	            return cont(typeexpr);
	          }
	          if (value == "?") return cont(typeexpr, expect(":"), typeexpr);
	        }
	        function maybeTypeArgs(_, value) {
	          if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType);
	        }
	        function typeparam() {
	          return pass(typeexpr, maybeTypeDefault);
	        }
	        function maybeTypeDefault(_, value) {
	          if (value == "=") return cont(typeexpr);
	        }
	        function vardef(_, value) {
	          if (value == "enum") {
	            cx.marked = "keyword";
	            return cont(enumdef);
	          }
	          return pass(pattern, maybetype, maybeAssign, vardefCont);
	        }
	        function pattern(type, value) {
	          if (isTS && isModifier(value)) {
	            cx.marked = "keyword";
	            return cont(pattern);
	          }
	          if (type == "variable") {
	            register(value);
	            return cont();
	          }
	          if (type == "spread") return cont(pattern);
	          if (type == "[") return contCommasep(eltpattern, "]");
	          if (type == "{") return contCommasep(proppattern, "}");
	        }
	        function proppattern(type, value) {
	          if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
	            register(value);
	            return cont(maybeAssign);
	          }
	          if (type == "variable") cx.marked = "property";
	          if (type == "spread") return cont(pattern);
	          if (type == "}") return pass();
	          if (type == "[") return cont(expression, expect(']'), expect(':'), proppattern);
	          return cont(expect(":"), pattern, maybeAssign);
	        }
	        function eltpattern() {
	          return pass(pattern, maybeAssign);
	        }
	        function maybeAssign(_type, value) {
	          if (value == "=") return cont(expressionNoComma);
	        }
	        function vardefCont(type) {
	          if (type == ",") return cont(vardef);
	        }
	        function maybeelse(type, value) {
	          if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
	        }
	        function forspec(type, value) {
	          if (value == "await") return cont(forspec);
	          if (type == "(") return cont(pushlex(")"), forspec1, poplex);
	        }
	        function forspec1(type) {
	          if (type == "var") return cont(vardef, forspec2);
	          if (type == "variable") return cont(forspec2);
	          return pass(forspec2);
	        }
	        function forspec2(type, value) {
	          if (type == ")") return cont();
	          if (type == ";") return cont(forspec2);
	          if (value == "in" || value == "of") {
	            cx.marked = "keyword";
	            return cont(expression, forspec2);
	          }
	          return pass(expression, forspec2);
	        }
	        function functiondef(type, value) {
	          if (value == "*") {
	            cx.marked = "keyword";
	            return cont(functiondef);
	          }
	          if (type == "variable") {
	            register(value);
	            return cont(functiondef);
	          }
	          if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext);
	          if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef);
	        }
	        function functiondecl(type, value) {
	          if (value == "*") {
	            cx.marked = "keyword";
	            return cont(functiondecl);
	          }
	          if (type == "variable") {
	            register(value);
	            return cont(functiondecl);
	          }
	          if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext);
	          if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl);
	        }
	        function typename(type, value) {
	          if (type == "keyword" || type == "variable") {
	            cx.marked = "type";
	            return cont(typename);
	          } else if (value == "<") {
	            return cont(pushlex(">"), commasep(typeparam, ">"), poplex);
	          }
	        }
	        function funarg(type, value) {
	          if (value == "@") cont(expression, funarg);
	          if (type == "spread") return cont(funarg);
	          if (isTS && isModifier(value)) {
	            cx.marked = "keyword";
	            return cont(funarg);
	          }
	          if (isTS && type == "this") return cont(maybetype, maybeAssign);
	          return pass(pattern, maybetype, maybeAssign);
	        }
	        function classExpression(type, value) {
	          // Class expressions may have an optional name.
	          if (type == "variable") return className(type, value);
	          return classNameAfter(type, value);
	        }
	        function className(type, value) {
	          if (type == "variable") {
	            register(value);
	            return cont(classNameAfter);
	          }
	        }
	        function classNameAfter(type, value) {
	          if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter);
	          if (value == "extends" || value == "implements" || isTS && type == ",") {
	            if (value == "implements") cx.marked = "keyword";
	            return cont(isTS ? typeexpr : expression, classNameAfter);
	          }
	          if (type == "{") return cont(pushlex("}"), classBody, poplex);
	        }
	        function classBody(type, value) {
	          if (type == "async" || type == "variable" && (value == "static" || value == "get" || value == "set" || isTS && isModifier(value)) && cx.stream.match(/^\s+#?[\w$\xa1-\uffff]/, false)) {
	            cx.marked = "keyword";
	            return cont(classBody);
	          }
	          if (type == "variable" || cx.style == "keyword") {
	            cx.marked = "property";
	            return cont(classfield, classBody);
	          }
	          if (type == "number" || type == "string") return cont(classfield, classBody);
	          if (type == "[") return cont(expression, maybetype, expect("]"), classfield, classBody);
	          if (value == "*") {
	            cx.marked = "keyword";
	            return cont(classBody);
	          }
	          if (isTS && type == "(") return pass(functiondecl, classBody);
	          if (type == ";" || type == ",") return cont(classBody);
	          if (type == "}") return cont();
	          if (value == "@") return cont(expression, classBody);
	        }
	        function classfield(type, value) {
	          if (value == "!") return cont(classfield);
	          if (value == "?") return cont(classfield);
	          if (type == ":") return cont(typeexpr, maybeAssign);
	          if (value == "=") return cont(expressionNoComma);
	          var context = cx.state.lexical.prev,
	            isInterface = context && context.info == "interface";
	          return pass(isInterface ? functiondecl : functiondef);
	        }
	        function afterExport(type, value) {
	          if (value == "*") {
	            cx.marked = "keyword";
	            return cont(maybeFrom, expect(";"));
	          }
	          if (value == "default") {
	            cx.marked = "keyword";
	            return cont(expression, expect(";"));
	          }
	          if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";"));
	          return pass(statement);
	        }
	        function exportField(type, value) {
	          if (value == "as") {
	            cx.marked = "keyword";
	            return cont(expect("variable"));
	          }
	          if (type == "variable") return pass(expressionNoComma, exportField);
	        }
	        function afterImport(type) {
	          if (type == "string") return cont();
	          if (type == "(") return pass(expression);
	          if (type == ".") return pass(maybeoperatorComma);
	          return pass(importSpec, maybeMoreImports, maybeFrom);
	        }
	        function importSpec(type, value) {
	          if (type == "{") return contCommasep(importSpec, "}");
	          if (type == "variable") register(value);
	          if (value == "*") cx.marked = "keyword";
	          return cont(maybeAs);
	        }
	        function maybeMoreImports(type) {
	          if (type == ",") return cont(importSpec, maybeMoreImports);
	        }
	        function maybeAs(_type, value) {
	          if (value == "as") {
	            cx.marked = "keyword";
	            return cont(importSpec);
	          }
	        }
	        function maybeFrom(_type, value) {
	          if (value == "from") {
	            cx.marked = "keyword";
	            return cont(expression);
	          }
	        }
	        function arrayLiteral(type) {
	          if (type == "]") return cont();
	          return pass(commasep(expressionNoComma, "]"));
	        }
	        function enumdef() {
	          return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex);
	        }
	        function enummember() {
	          return pass(pattern, maybeAssign);
	        }
	        function isContinuedStatement(state, textAfter) {
	          return state.lastType == "operator" || state.lastType == "," || isOperatorChar.test(textAfter.charAt(0)) || /[,.]/.test(textAfter.charAt(0));
	        }
	        function expressionAllowed(stream, state, backUp) {
	          return state.tokenize == tokenBase && /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) || state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0)));
	        }

	        // Interface

	        return {
	          startState: function (basecolumn) {
	            var state = {
	              tokenize: tokenBase,
	              lastType: "sof",
	              cc: [],
	              lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
	              localVars: parserConfig.localVars,
	              context: parserConfig.localVars && new Context(null, null, false),
	              indented: basecolumn || 0
	            };
	            if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") state.globalVars = parserConfig.globalVars;
	            return state;
	          },
	          token: function (stream, state) {
	            if (stream.sol()) {
	              if (!state.lexical.hasOwnProperty("align")) state.lexical.align = false;
	              state.indented = stream.indentation();
	              findFatArrow(stream, state);
	            }
	            if (state.tokenize != tokenComment && stream.eatSpace()) return null;
	            var style = state.tokenize(stream, state);
	            if (type == "comment") return style;
	            state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
	            return parseJS(state, style, type, content, stream);
	          },
	          indent: function (state, textAfter) {
	            if (state.tokenize == tokenComment || state.tokenize == tokenQuasi) return CodeMirror.Pass;
	            if (state.tokenize != tokenBase) return 0;
	            var firstChar = textAfter && textAfter.charAt(0),
	              lexical = state.lexical,
	              top;
	            // Kludge to prevent 'maybelse' from blocking lexical scope pops
	            if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
	              var c = state.cc[i];
	              if (c == poplex) lexical = lexical.prev;else if (c != maybeelse && c != popcontext) break;
	            }
	            while ((lexical.type == "stat" || lexical.type == "form") && (firstChar == "}" || (top = state.cc[state.cc.length - 1]) && (top == maybeoperatorComma || top == maybeoperatorNoComma) && !/^[,\.=+\-*:?[\(]/.test(textAfter))) lexical = lexical.prev;
	            if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") lexical = lexical.prev;
	            var type = lexical.type,
	              closing = firstChar == type;
	            if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0);else if (type == "form" && firstChar == "{") return lexical.indented;else if (type == "form") return lexical.indented + indentUnit;else if (type == "stat") return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);else if (lexical.align) return lexical.column + (closing ? 0 : 1);else return lexical.indented + (closing ? 0 : indentUnit);
	          },
	          electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
	          blockCommentStart: jsonMode ? null : "/*",
	          blockCommentEnd: jsonMode ? null : "*/",
	          blockCommentContinue: jsonMode ? null : " * ",
	          lineComment: jsonMode ? null : "//",
	          fold: "brace",
	          closeBrackets: "()[]{}''\"\"``",
	          helperType: jsonMode ? "json" : "javascript",
	          jsonldMode: jsonldMode,
	          jsonMode: jsonMode,
	          expressionAllowed: expressionAllowed,
	          skipExpression: function (state) {
	            parseJS(state, "atom", "atom", "true", new CodeMirror.StringStream("", 2, null));
	          }
	        };
	      });
	      CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
	      CodeMirror.defineMIME("text/javascript", "javascript");
	      CodeMirror.defineMIME("text/ecmascript", "javascript");
	      CodeMirror.defineMIME("application/javascript", "javascript");
	      CodeMirror.defineMIME("application/x-javascript", "javascript");
	      CodeMirror.defineMIME("application/ecmascript", "javascript");
	      CodeMirror.defineMIME("application/json", {
	        name: "javascript",
	        json: true
	      });
	      CodeMirror.defineMIME("application/x-json", {
	        name: "javascript",
	        json: true
	      });
	      CodeMirror.defineMIME("application/manifest+json", {
	        name: "javascript",
	        json: true
	      });
	      CodeMirror.defineMIME("application/ld+json", {
	        name: "javascript",
	        jsonld: true
	      });
	      CodeMirror.defineMIME("text/typescript", {
	        name: "javascript",
	        typescript: true
	      });
	      CodeMirror.defineMIME("application/typescript", {
	        name: "javascript",
	        typescript: true
	      });
	    });
	  })();
	  return javascript.exports;
	}

	var hasRequiredHtmlmixed;
	function requireHtmlmixed() {
	  if (hasRequiredHtmlmixed) return htmlmixed.exports;
	  hasRequiredHtmlmixed = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror(), requireXml(), requireJavascript(), requireCss());
	    })(function (CodeMirror) {

	      var defaultTags = {
	        script: [["lang", /(javascript|babel)/i, "javascript"], ["type", /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i, "javascript"], ["type", /./, "text/plain"], [null, null, "javascript"]],
	        style: [["lang", /^css$/i, "css"], ["type", /^(text\/)?(x-)?(stylesheet|css)$/i, "css"], ["type", /./, "text/plain"], [null, null, "css"]]
	      };
	      function maybeBackup(stream, pat, style) {
	        var cur = stream.current(),
	          close = cur.search(pat);
	        if (close > -1) {
	          stream.backUp(cur.length - close);
	        } else if (cur.match(/<\/?$/)) {
	          stream.backUp(cur.length);
	          if (!stream.match(pat, false)) stream.match(cur);
	        }
	        return style;
	      }
	      var attrRegexpCache = {};
	      function getAttrRegexp(attr) {
	        var regexp = attrRegexpCache[attr];
	        if (regexp) return regexp;
	        return attrRegexpCache[attr] = new RegExp("\\s+" + attr + "\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*");
	      }
	      function getAttrValue(text, attr) {
	        var match = text.match(getAttrRegexp(attr));
	        return match ? /^\s*(.*?)\s*$/.exec(match[2])[1] : "";
	      }
	      function getTagRegexp(tagName, anchored) {
	        return new RegExp((anchored ? "^" : "") + "<\/\\s*" + tagName + "\\s*>", "i");
	      }
	      function addTags(from, to) {
	        for (var tag in from) {
	          var dest = to[tag] || (to[tag] = []);
	          var source = from[tag];
	          for (var i = source.length - 1; i >= 0; i--) dest.unshift(source[i]);
	        }
	      }
	      function findMatchingMode(tagInfo, tagText) {
	        for (var i = 0; i < tagInfo.length; i++) {
	          var spec = tagInfo[i];
	          if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2];
	        }
	      }
	      CodeMirror.defineMode("htmlmixed", function (config, parserConfig) {
	        var htmlMode = CodeMirror.getMode(config, {
	          name: "xml",
	          htmlMode: true,
	          multilineTagIndentFactor: parserConfig.multilineTagIndentFactor,
	          multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag,
	          allowMissingTagName: parserConfig.allowMissingTagName
	        });
	        var tags = {};
	        var configTags = parserConfig && parserConfig.tags,
	          configScript = parserConfig && parserConfig.scriptTypes;
	        addTags(defaultTags, tags);
	        if (configTags) addTags(configTags, tags);
	        if (configScript) for (var i = configScript.length - 1; i >= 0; i--) tags.script.unshift(["type", configScript[i].matches, configScript[i].mode]);
	        function html(stream, state) {
	          var style = htmlMode.token(stream, state.htmlState),
	            tag = /\btag\b/.test(style),
	            tagName;
	          if (tag && !/[<>\s\/]/.test(stream.current()) && (tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) && tags.hasOwnProperty(tagName)) {
	            state.inTag = tagName + " ";
	          } else if (state.inTag && tag && />$/.test(stream.current())) {
	            var inTag = /^([\S]+) (.*)/.exec(state.inTag);
	            state.inTag = null;
	            var modeSpec = stream.current() == ">" && findMatchingMode(tags[inTag[1]], inTag[2]);
	            var mode = CodeMirror.getMode(config, modeSpec);
	            var endTagA = getTagRegexp(inTag[1], true),
	              endTag = getTagRegexp(inTag[1], false);
	            state.token = function (stream, state) {
	              if (stream.match(endTagA, false)) {
	                state.token = html;
	                state.localState = state.localMode = null;
	                return null;
	              }
	              return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState));
	            };
	            state.localMode = mode;
	            state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, "", ""));
	          } else if (state.inTag) {
	            state.inTag += stream.current();
	            if (stream.eol()) state.inTag += " ";
	          }
	          return style;
	        }
	        return {
	          startState: function () {
	            var state = CodeMirror.startState(htmlMode);
	            return {
	              token: html,
	              inTag: null,
	              localMode: null,
	              localState: null,
	              htmlState: state
	            };
	          },
	          copyState: function (state) {
	            var local;
	            if (state.localState) {
	              local = CodeMirror.copyState(state.localMode, state.localState);
	            }
	            return {
	              token: state.token,
	              inTag: state.inTag,
	              localMode: state.localMode,
	              localState: local,
	              htmlState: CodeMirror.copyState(htmlMode, state.htmlState)
	            };
	          },
	          token: function (stream, state) {
	            return state.token(stream, state);
	          },
	          indent: function (state, textAfter, line) {
	            if (!state.localMode || /^\s*<\//.test(textAfter)) return htmlMode.indent(state.htmlState, textAfter, line);else if (state.localMode.indent) return state.localMode.indent(state.localState, textAfter, line);else return CodeMirror.Pass;
	          },
	          innerMode: function (state) {
	            return {
	              state: state.localState || state.htmlState,
	              mode: state.localMode || htmlMode
	            };
	          }
	        };
	      }, "xml", "javascript", "css");
	      CodeMirror.defineMIME("text/html", "htmlmixed");
	    });
	  })();
	  return htmlmixed.exports;
	}

	requireHtmlmixed();

	requireJavascript();

	var jsx = {exports: {}};

	var hasRequiredJsx;
	function requireJsx() {
	  if (hasRequiredJsx) return jsx.exports;
	  hasRequiredJsx = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror(), requireXml(), requireJavascript());
	    })(function (CodeMirror) {

	      // Depth means the amount of open braces in JS context, in XML
	      // context 0 means not in tag, 1 means in tag, and 2 means in tag
	      // and js block comment.
	      function Context(state, mode, depth, prev) {
	        this.state = state;
	        this.mode = mode;
	        this.depth = depth;
	        this.prev = prev;
	      }
	      function copyContext(context) {
	        return new Context(CodeMirror.copyState(context.mode, context.state), context.mode, context.depth, context.prev && copyContext(context.prev));
	      }
	      CodeMirror.defineMode("jsx", function (config, modeConfig) {
	        var xmlMode = CodeMirror.getMode(config, {
	          name: "xml",
	          allowMissing: true,
	          multilineTagIndentPastTag: false,
	          allowMissingTagName: true
	        });
	        var jsMode = CodeMirror.getMode(config, modeConfig && modeConfig.base || "javascript");
	        function flatXMLIndent(state) {
	          var tagName = state.tagName;
	          state.tagName = null;
	          var result = xmlMode.indent(state, "", "");
	          state.tagName = tagName;
	          return result;
	        }
	        function token(stream, state) {
	          if (state.context.mode == xmlMode) return xmlToken(stream, state, state.context);else return jsToken(stream, state, state.context);
	        }
	        function xmlToken(stream, state, cx) {
	          if (cx.depth == 2) {
	            // Inside a JS /* */ comment
	            if (stream.match(/^.*?\*\//)) cx.depth = 1;else stream.skipToEnd();
	            return "comment";
	          }
	          if (stream.peek() == "{") {
	            xmlMode.skipAttribute(cx.state);
	            var indent = flatXMLIndent(cx.state),
	              xmlContext = cx.state.context;
	            // If JS starts on same line as tag
	            if (xmlContext && stream.match(/^[^>]*>\s*$/, false)) {
	              while (xmlContext.prev && !xmlContext.startOfLine) xmlContext = xmlContext.prev;
	              // If tag starts the line, use XML indentation level
	              if (xmlContext.startOfLine) indent -= config.indentUnit;
	              // Else use JS indentation level
	              else if (cx.prev.state.lexical) indent = cx.prev.state.lexical.indented;
	              // Else if inside of tag
	            } else if (cx.depth == 1) {
	              indent += config.indentUnit;
	            }
	            state.context = new Context(CodeMirror.startState(jsMode, indent), jsMode, 0, state.context);
	            return null;
	          }
	          if (cx.depth == 1) {
	            // Inside of tag
	            if (stream.peek() == "<") {
	              // Tag inside of tag
	              xmlMode.skipAttribute(cx.state);
	              state.context = new Context(CodeMirror.startState(xmlMode, flatXMLIndent(cx.state)), xmlMode, 0, state.context);
	              return null;
	            } else if (stream.match("//")) {
	              stream.skipToEnd();
	              return "comment";
	            } else if (stream.match("/*")) {
	              cx.depth = 2;
	              return token(stream, state);
	            }
	          }
	          var style = xmlMode.token(stream, cx.state),
	            cur = stream.current(),
	            stop;
	          if (/\btag\b/.test(style)) {
	            if (/>$/.test(cur)) {
	              if (cx.state.context) cx.depth = 0;else state.context = state.context.prev;
	            } else if (/^</.test(cur)) {
	              cx.depth = 1;
	            }
	          } else if (!style && (stop = cur.indexOf("{")) > -1) {
	            stream.backUp(cur.length - stop);
	          }
	          return style;
	        }
	        function jsToken(stream, state, cx) {
	          if (stream.peek() == "<" && !stream.match(/^<([^<>]|<[^>]*>)+,\s*>/, false) && jsMode.expressionAllowed(stream, cx.state)) {
	            state.context = new Context(CodeMirror.startState(xmlMode, jsMode.indent(cx.state, "", "")), xmlMode, 0, state.context);
	            jsMode.skipExpression(cx.state);
	            return null;
	          }
	          var style = jsMode.token(stream, cx.state);
	          if (!style && cx.depth != null) {
	            var cur = stream.current();
	            if (cur == "{") {
	              cx.depth++;
	            } else if (cur == "}") {
	              if (--cx.depth == 0) state.context = state.context.prev;
	            }
	          }
	          return style;
	        }
	        return {
	          startState: function () {
	            return {
	              context: new Context(CodeMirror.startState(jsMode), jsMode)
	            };
	          },
	          copyState: function (state) {
	            return {
	              context: copyContext(state.context)
	            };
	          },
	          token: token,
	          indent: function (state, textAfter, fullLine) {
	            return state.context.mode.indent(state.context.state, textAfter, fullLine);
	          },
	          innerMode: function (state) {
	            return state.context;
	          }
	        };
	      }, "xml", "javascript");
	      CodeMirror.defineMIME("text/jsx", "jsx");
	      CodeMirror.defineMIME("text/typescript-jsx", {
	        name: "jsx",
	        base: {
	          name: "javascript",
	          typescript: true
	        }
	      });
	    });
	  })();
	  return jsx.exports;
	}

	requireJsx();

	requireMarkdown();

	var perl = {exports: {}};

	var hasRequiredPerl;
	function requirePerl() {
	  if (hasRequiredPerl) return perl.exports;
	  hasRequiredPerl = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    // CodeMirror2 mode/perl/perl.js (text/x-perl) beta 0.10 (2011-11-08)
	    // This is a part of CodeMirror from https://github.com/sabaca/CodeMirror_mode_perl (mail@sabaca.com)

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      CodeMirror.defineMode("perl", function () {
	        // http://perldoc.perl.org
	        var PERL = {
	          //   null - magic touch
	          //   1 - keyword
	          //   2 - def
	          //   3 - atom
	          //   4 - operator
	          //   5 - variable-2 (predefined)
	          //   [x,y] - x=1,2,3; y=must be defined if x{...}
	          //      PERL operators
	          '->': 4,
	          '++': 4,
	          '--': 4,
	          '**': 4,
	          //   ! ~ \ and unary + and -
	          '=~': 4,
	          '!~': 4,
	          '*': 4,
	          '/': 4,
	          '%': 4,
	          'x': 4,
	          '+': 4,
	          '-': 4,
	          '.': 4,
	          '<<': 4,
	          '>>': 4,
	          //   named unary operators
	          '<': 4,
	          '>': 4,
	          '<=': 4,
	          '>=': 4,
	          'lt': 4,
	          'gt': 4,
	          'le': 4,
	          'ge': 4,
	          '==': 4,
	          '!=': 4,
	          '<=>': 4,
	          'eq': 4,
	          'ne': 4,
	          'cmp': 4,
	          '~~': 4,
	          '&': 4,
	          '|': 4,
	          '^': 4,
	          '&&': 4,
	          '||': 4,
	          '//': 4,
	          '..': 4,
	          '...': 4,
	          '?': 4,
	          ':': 4,
	          '=': 4,
	          '+=': 4,
	          '-=': 4,
	          '*=': 4,
	          //   etc. ???
	          ',': 4,
	          '=>': 4,
	          '::': 4,
	          //   list operators (rightward)
	          'not': 4,
	          'and': 4,
	          'or': 4,
	          'xor': 4,
	          //      PERL predefined variables (I know, what this is a paranoid idea, but may be needed for people, who learn PERL, and for me as well, ...and may be for you?;)
	          'BEGIN': [5, 1],
	          'END': [5, 1],
	          'PRINT': [5, 1],
	          'PRINTF': [5, 1],
	          'GETC': [5, 1],
	          'READ': [5, 1],
	          'READLINE': [5, 1],
	          'DESTROY': [5, 1],
	          'TIE': [5, 1],
	          'TIEHANDLE': [5, 1],
	          'UNTIE': [5, 1],
	          'STDIN': 5,
	          'STDIN_TOP': 5,
	          'STDOUT': 5,
	          'STDOUT_TOP': 5,
	          'STDERR': 5,
	          'STDERR_TOP': 5,
	          '$ARG': 5,
	          '$_': 5,
	          '@ARG': 5,
	          '@_': 5,
	          '$LIST_SEPARATOR': 5,
	          '$"': 5,
	          '$PROCESS_ID': 5,
	          '$PID': 5,
	          '$$': 5,
	          '$REAL_GROUP_ID': 5,
	          '$GID': 5,
	          '$(': 5,
	          '$EFFECTIVE_GROUP_ID': 5,
	          '$EGID': 5,
	          '$)': 5,
	          '$PROGRAM_NAME': 5,
	          '$0': 5,
	          '$SUBSCRIPT_SEPARATOR': 5,
	          '$SUBSEP': 5,
	          '$;': 5,
	          '$REAL_USER_ID': 5,
	          '$UID': 5,
	          '$<': 5,
	          '$EFFECTIVE_USER_ID': 5,
	          '$EUID': 5,
	          '$>': 5,
	          '$a': 5,
	          '$b': 5,
	          '$COMPILING': 5,
	          '$^C': 5,
	          '$DEBUGGING': 5,
	          '$^D': 5,
	          '${^ENCODING}': 5,
	          '$ENV': 5,
	          '%ENV': 5,
	          '$SYSTEM_FD_MAX': 5,
	          '$^F': 5,
	          '@F': 5,
	          '${^GLOBAL_PHASE}': 5,
	          '$^H': 5,
	          '%^H': 5,
	          '@INC': 5,
	          '%INC': 5,
	          '$INPLACE_EDIT': 5,
	          '$^I': 5,
	          '$^M': 5,
	          '$OSNAME': 5,
	          '$^O': 5,
	          '${^OPEN}': 5,
	          '$PERLDB': 5,
	          '$^P': 5,
	          '$SIG': 5,
	          '%SIG': 5,
	          '$BASETIME': 5,
	          '$^T': 5,
	          '${^TAINT}': 5,
	          '${^UNICODE}': 5,
	          '${^UTF8CACHE}': 5,
	          '${^UTF8LOCALE}': 5,
	          '$PERL_VERSION': 5,
	          '$^V': 5,
	          '${^WIN32_SLOPPY_STAT}': 5,
	          '$EXECUTABLE_NAME': 5,
	          '$^X': 5,
	          '$1': 5,
	          // - regexp $1, $2...
	          '$MATCH': 5,
	          '$&': 5,
	          '${^MATCH}': 5,
	          '$PREMATCH': 5,
	          '$`': 5,
	          '${^PREMATCH}': 5,
	          '$POSTMATCH': 5,
	          "$'": 5,
	          '${^POSTMATCH}': 5,
	          '$LAST_PAREN_MATCH': 5,
	          '$+': 5,
	          '$LAST_SUBMATCH_RESULT': 5,
	          '$^N': 5,
	          '@LAST_MATCH_END': 5,
	          '@+': 5,
	          '%LAST_PAREN_MATCH': 5,
	          '%+': 5,
	          '@LAST_MATCH_START': 5,
	          '@-': 5,
	          '%LAST_MATCH_START': 5,
	          '%-': 5,
	          '$LAST_REGEXP_CODE_RESULT': 5,
	          '$^R': 5,
	          '${^RE_DEBUG_FLAGS}': 5,
	          '${^RE_TRIE_MAXBUF}': 5,
	          '$ARGV': 5,
	          '@ARGV': 5,
	          'ARGV': 5,
	          'ARGVOUT': 5,
	          '$OUTPUT_FIELD_SEPARATOR': 5,
	          '$OFS': 5,
	          '$,': 5,
	          '$INPUT_LINE_NUMBER': 5,
	          '$NR': 5,
	          '$.': 5,
	          '$INPUT_RECORD_SEPARATOR': 5,
	          '$RS': 5,
	          '$/': 5,
	          '$OUTPUT_RECORD_SEPARATOR': 5,
	          '$ORS': 5,
	          '$\\': 5,
	          '$OUTPUT_AUTOFLUSH': 5,
	          '$|': 5,
	          '$ACCUMULATOR': 5,
	          '$^A': 5,
	          '$FORMAT_FORMFEED': 5,
	          '$^L': 5,
	          '$FORMAT_PAGE_NUMBER': 5,
	          '$%': 5,
	          '$FORMAT_LINES_LEFT': 5,
	          '$-': 5,
	          '$FORMAT_LINE_BREAK_CHARACTERS': 5,
	          '$:': 5,
	          '$FORMAT_LINES_PER_PAGE': 5,
	          '$=': 5,
	          '$FORMAT_TOP_NAME': 5,
	          '$^': 5,
	          '$FORMAT_NAME': 5,
	          '$~': 5,
	          '${^CHILD_ERROR_NATIVE}': 5,
	          '$EXTENDED_OS_ERROR': 5,
	          '$^E': 5,
	          '$EXCEPTIONS_BEING_CAUGHT': 5,
	          '$^S': 5,
	          '$WARNING': 5,
	          '$^W': 5,
	          '${^WARNING_BITS}': 5,
	          '$OS_ERROR': 5,
	          '$ERRNO': 5,
	          '$!': 5,
	          '%OS_ERROR': 5,
	          '%ERRNO': 5,
	          '%!': 5,
	          '$CHILD_ERROR': 5,
	          '$?': 5,
	          '$EVAL_ERROR': 5,
	          '$@': 5,
	          '$OFMT': 5,
	          '$#': 5,
	          '$*': 5,
	          '$ARRAY_BASE': 5,
	          '$[': 5,
	          '$OLD_PERL_VERSION': 5,
	          '$]': 5,
	          //      PERL blocks
	          'if': [1, 1],
	          elsif: [1, 1],
	          'else': [1, 1],
	          'while': [1, 1],
	          unless: [1, 1],
	          'for': [1, 1],
	          foreach: [1, 1],
	          //      PERL functions
	          'abs': 1,
	          // - absolute value function
	          accept: 1,
	          // - accept an incoming socket connect
	          alarm: 1,
	          // - schedule a SIGALRM
	          'atan2': 1,
	          // - arctangent of Y/X in the range -PI to PI
	          bind: 1,
	          // - binds an address to a socket
	          binmode: 1,
	          // - prepare binary files for I/O
	          bless: 1,
	          // - create an object
	          bootstrap: 1,
	          //
	          'break': 1,
	          // - break out of a "given" block
	          caller: 1,
	          // - get context of the current subroutine call
	          chdir: 1,
	          // - change your current working directory
	          chmod: 1,
	          // - changes the permissions on a list of files
	          chomp: 1,
	          // - remove a trailing record separator from a string
	          chop: 1,
	          // - remove the last character from a string
	          chown: 1,
	          // - change the ownership on a list of files
	          chr: 1,
	          // - get character this number represents
	          chroot: 1,
	          // - make directory new root for path lookups
	          close: 1,
	          // - close file (or pipe or socket) handle
	          closedir: 1,
	          // - close directory handle
	          connect: 1,
	          // - connect to a remote socket
	          'continue': [1, 1],
	          // - optional trailing block in a while or foreach
	          'cos': 1,
	          // - cosine function
	          crypt: 1,
	          // - one-way passwd-style encryption
	          dbmclose: 1,
	          // - breaks binding on a tied dbm file
	          dbmopen: 1,
	          // - create binding on a tied dbm file
	          'default': 1,
	          //
	          defined: 1,
	          // - test whether a value, variable, or function is defined
	          'delete': 1,
	          // - deletes a value from a hash
	          die: 1,
	          // - raise an exception or bail out
	          'do': 1,
	          // - turn a BLOCK into a TERM
	          dump: 1,
	          // - create an immediate core dump
	          each: 1,
	          // - retrieve the next key/value pair from a hash
	          endgrent: 1,
	          // - be done using group file
	          endhostent: 1,
	          // - be done using hosts file
	          endnetent: 1,
	          // - be done using networks file
	          endprotoent: 1,
	          // - be done using protocols file
	          endpwent: 1,
	          // - be done using passwd file
	          endservent: 1,
	          // - be done using services file
	          eof: 1,
	          // - test a filehandle for its end
	          'eval': 1,
	          // - catch exceptions or compile and run code
	          'exec': 1,
	          // - abandon this program to run another
	          exists: 1,
	          // - test whether a hash key is present
	          exit: 1,
	          // - terminate this program
	          'exp': 1,
	          // - raise I to a power
	          fcntl: 1,
	          // - file control system call
	          fileno: 1,
	          // - return file descriptor from filehandle
	          flock: 1,
	          // - lock an entire file with an advisory lock
	          fork: 1,
	          // - create a new process just like this one
	          format: 1,
	          // - declare a picture format with use by the write() function
	          formline: 1,
	          // - internal function used for formats
	          getc: 1,
	          // - get the next character from the filehandle
	          getgrent: 1,
	          // - get next group record
	          getgrgid: 1,
	          // - get group record given group user ID
	          getgrnam: 1,
	          // - get group record given group name
	          gethostbyaddr: 1,
	          // - get host record given its address
	          gethostbyname: 1,
	          // - get host record given name
	          gethostent: 1,
	          // - get next hosts record
	          getlogin: 1,
	          // - return who logged in at this tty
	          getnetbyaddr: 1,
	          // - get network record given its address
	          getnetbyname: 1,
	          // - get networks record given name
	          getnetent: 1,
	          // - get next networks record
	          getpeername: 1,
	          // - find the other end of a socket connection
	          getpgrp: 1,
	          // - get process group
	          getppid: 1,
	          // - get parent process ID
	          getpriority: 1,
	          // - get current nice value
	          getprotobyname: 1,
	          // - get protocol record given name
	          getprotobynumber: 1,
	          // - get protocol record numeric protocol
	          getprotoent: 1,
	          // - get next protocols record
	          getpwent: 1,
	          // - get next passwd record
	          getpwnam: 1,
	          // - get passwd record given user login name
	          getpwuid: 1,
	          // - get passwd record given user ID
	          getservbyname: 1,
	          // - get services record given its name
	          getservbyport: 1,
	          // - get services record given numeric port
	          getservent: 1,
	          // - get next services record
	          getsockname: 1,
	          // - retrieve the sockaddr for a given socket
	          getsockopt: 1,
	          // - get socket options on a given socket
	          given: 1,
	          //
	          glob: 1,
	          // - expand filenames using wildcards
	          gmtime: 1,
	          // - convert UNIX time into record or string using Greenwich time
	          'goto': 1,
	          // - create spaghetti code
	          grep: 1,
	          // - locate elements in a list test true against a given criterion
	          hex: 1,
	          // - convert a string to a hexadecimal number
	          'import': 1,
	          // - patch a module's namespace into your own
	          index: 1,
	          // - find a substring within a string
	          'int': 1,
	          // - get the integer portion of a number
	          ioctl: 1,
	          // - system-dependent device control system call
	          'join': 1,
	          // - join a list into a string using a separator
	          keys: 1,
	          // - retrieve list of indices from a hash
	          kill: 1,
	          // - send a signal to a process or process group
	          last: 1,
	          // - exit a block prematurely
	          lc: 1,
	          // - return lower-case version of a string
	          lcfirst: 1,
	          // - return a string with just the next letter in lower case
	          length: 1,
	          // - return the number of bytes in a string
	          'link': 1,
	          // - create a hard link in the filesystem
	          listen: 1,
	          // - register your socket as a server
	          local: 2,
	          // - create a temporary value for a global variable (dynamic scoping)
	          localtime: 1,
	          // - convert UNIX time into record or string using local time
	          lock: 1,
	          // - get a thread lock on a variable, subroutine, or method
	          'log': 1,
	          // - retrieve the natural logarithm for a number
	          lstat: 1,
	          // - stat a symbolic link
	          m: null,
	          // - match a string with a regular expression pattern
	          map: 1,
	          // - apply a change to a list to get back a new list with the changes
	          mkdir: 1,
	          // - create a directory
	          msgctl: 1,
	          // - SysV IPC message control operations
	          msgget: 1,
	          // - get SysV IPC message queue
	          msgrcv: 1,
	          // - receive a SysV IPC message from a message queue
	          msgsnd: 1,
	          // - send a SysV IPC message to a message queue
	          my: 2,
	          // - declare and assign a local variable (lexical scoping)
	          'new': 1,
	          //
	          next: 1,
	          // - iterate a block prematurely
	          no: 1,
	          // - unimport some module symbols or semantics at compile time
	          oct: 1,
	          // - convert a string to an octal number
	          open: 1,
	          // - open a file, pipe, or descriptor
	          opendir: 1,
	          // - open a directory
	          ord: 1,
	          // - find a character's numeric representation
	          our: 2,
	          // - declare and assign a package variable (lexical scoping)
	          pack: 1,
	          // - convert a list into a binary representation
	          'package': 1,
	          // - declare a separate global namespace
	          pipe: 1,
	          // - open a pair of connected filehandles
	          pop: 1,
	          // - remove the last element from an array and return it
	          pos: 1,
	          // - find or set the offset for the last/next m//g search
	          print: 1,
	          // - output a list to a filehandle
	          printf: 1,
	          // - output a formatted list to a filehandle
	          prototype: 1,
	          // - get the prototype (if any) of a subroutine
	          push: 1,
	          // - append one or more elements to an array
	          q: null,
	          // - singly quote a string
	          qq: null,
	          // - doubly quote a string
	          qr: null,
	          // - Compile pattern
	          quotemeta: null,
	          // - quote regular expression magic characters
	          qw: null,
	          // - quote a list of words
	          qx: null,
	          // - backquote quote a string
	          rand: 1,
	          // - retrieve the next pseudorandom number
	          read: 1,
	          // - fixed-length buffered input from a filehandle
	          readdir: 1,
	          // - get a directory from a directory handle
	          readline: 1,
	          // - fetch a record from a file
	          readlink: 1,
	          // - determine where a symbolic link is pointing
	          readpipe: 1,
	          // - execute a system command and collect standard output
	          recv: 1,
	          // - receive a message over a Socket
	          redo: 1,
	          // - start this loop iteration over again
	          ref: 1,
	          // - find out the type of thing being referenced
	          rename: 1,
	          // - change a filename
	          require: 1,
	          // - load in external functions from a library at runtime
	          reset: 1,
	          // - clear all variables of a given name
	          'return': 1,
	          // - get out of a function early
	          reverse: 1,
	          // - flip a string or a list
	          rewinddir: 1,
	          // - reset directory handle
	          rindex: 1,
	          // - right-to-left substring search
	          rmdir: 1,
	          // - remove a directory
	          s: null,
	          // - replace a pattern with a string
	          say: 1,
	          // - print with newline
	          scalar: 1,
	          // - force a scalar context
	          seek: 1,
	          // - reposition file pointer for random-access I/O
	          seekdir: 1,
	          // - reposition directory pointer
	          select: 1,
	          // - reset default output or do I/O multiplexing
	          semctl: 1,
	          // - SysV semaphore control operations
	          semget: 1,
	          // - get set of SysV semaphores
	          semop: 1,
	          // - SysV semaphore operations
	          send: 1,
	          // - send a message over a socket
	          setgrent: 1,
	          // - prepare group file for use
	          sethostent: 1,
	          // - prepare hosts file for use
	          setnetent: 1,
	          // - prepare networks file for use
	          setpgrp: 1,
	          // - set the process group of a process
	          setpriority: 1,
	          // - set a process's nice value
	          setprotoent: 1,
	          // - prepare protocols file for use
	          setpwent: 1,
	          // - prepare passwd file for use
	          setservent: 1,
	          // - prepare services file for use
	          setsockopt: 1,
	          // - set some socket options
	          shift: 1,
	          // - remove the first element of an array, and return it
	          shmctl: 1,
	          // - SysV shared memory operations
	          shmget: 1,
	          // - get SysV shared memory segment identifier
	          shmread: 1,
	          // - read SysV shared memory
	          shmwrite: 1,
	          // - write SysV shared memory
	          shutdown: 1,
	          // - close down just half of a socket connection
	          'sin': 1,
	          // - return the sine of a number
	          sleep: 1,
	          // - block for some number of seconds
	          socket: 1,
	          // - create a socket
	          socketpair: 1,
	          // - create a pair of sockets
	          'sort': 1,
	          // - sort a list of values
	          splice: 1,
	          // - add or remove elements anywhere in an array
	          'split': 1,
	          // - split up a string using a regexp delimiter
	          sprintf: 1,
	          // - formatted print into a string
	          'sqrt': 1,
	          // - square root function
	          srand: 1,
	          // - seed the random number generator
	          stat: 1,
	          // - get a file's status information
	          state: 1,
	          // - declare and assign a state variable (persistent lexical scoping)
	          study: 1,
	          // - optimize input data for repeated searches
	          'sub': 1,
	          // - declare a subroutine, possibly anonymously
	          'substr': 1,
	          // - get or alter a portion of a string
	          symlink: 1,
	          // - create a symbolic link to a file
	          syscall: 1,
	          // - execute an arbitrary system call
	          sysopen: 1,
	          // - open a file, pipe, or descriptor
	          sysread: 1,
	          // - fixed-length unbuffered input from a filehandle
	          sysseek: 1,
	          // - position I/O pointer on handle used with sysread and syswrite
	          system: 1,
	          // - run a separate program
	          syswrite: 1,
	          // - fixed-length unbuffered output to a filehandle
	          tell: 1,
	          // - get current seekpointer on a filehandle
	          telldir: 1,
	          // - get current seekpointer on a directory handle
	          tie: 1,
	          // - bind a variable to an object class
	          tied: 1,
	          // - get a reference to the object underlying a tied variable
	          time: 1,
	          // - return number of seconds since 1970
	          times: 1,
	          // - return elapsed time for self and child processes
	          tr: null,
	          // - transliterate a string
	          truncate: 1,
	          // - shorten a file
	          uc: 1,
	          // - return upper-case version of a string
	          ucfirst: 1,
	          // - return a string with just the next letter in upper case
	          umask: 1,
	          // - set file creation mode mask
	          undef: 1,
	          // - remove a variable or function definition
	          unlink: 1,
	          // - remove one link to a file
	          unpack: 1,
	          // - convert binary structure into normal perl variables
	          unshift: 1,
	          // - prepend more elements to the beginning of a list
	          untie: 1,
	          // - break a tie binding to a variable
	          use: 1,
	          // - load in a module at compile time
	          utime: 1,
	          // - set a file's last access and modify times
	          values: 1,
	          // - return a list of the values in a hash
	          vec: 1,
	          // - test or set particular bits in a string
	          wait: 1,
	          // - wait for any child process to die
	          waitpid: 1,
	          // - wait for a particular child process to die
	          wantarray: 1,
	          // - get void vs scalar vs list context of current subroutine call
	          warn: 1,
	          // - print debugging info
	          when: 1,
	          //
	          write: 1,
	          // - print a picture record
	          y: null
	        }; // - transliterate a string

	        var RXstyle = "string-2";
	        var RXmodifiers = /[goseximacplud]/; // NOTE: "m", "s", "y" and "tr" need to correct real modifiers for each regexp type

	        function tokenChain(stream, state, chain, style, tail) {
	          // NOTE: chain.length > 2 is not working now (it's for s[...][...]geos;)
	          state.chain = null; //                                                          12   3tail
	          state.style = null;
	          state.tail = null;
	          state.tokenize = function (stream, state) {
	            var e = false,
	              c,
	              i = 0;
	            while (c = stream.next()) {
	              if (c === chain[i] && !e) {
	                if (chain[++i] !== undefined) {
	                  state.chain = chain[i];
	                  state.style = style;
	                  state.tail = tail;
	                } else if (tail) stream.eatWhile(tail);
	                state.tokenize = tokenPerl;
	                return style;
	              }
	              e = !e && c == "\\";
	            }
	            return style;
	          };
	          return state.tokenize(stream, state);
	        }
	        function tokenSOMETHING(stream, state, string) {
	          state.tokenize = function (stream, state) {
	            if (stream.string == string) state.tokenize = tokenPerl;
	            stream.skipToEnd();
	            return "string";
	          };
	          return state.tokenize(stream, state);
	        }
	        function tokenPerl(stream, state) {
	          if (stream.eatSpace()) return null;
	          if (state.chain) return tokenChain(stream, state, state.chain, state.style, state.tail);
	          if (stream.match(/^(\-?((\d[\d_]*)?\.\d+(e[+-]?\d+)?|\d+\.\d*)|0x[\da-fA-F_]+|0b[01_]+|\d[\d_]*(e[+-]?\d+)?)/)) return 'number';
	          if (stream.match(/^<<(?=[_a-zA-Z])/)) {
	            // NOTE: <<SOMETHING\n...\nSOMETHING\n
	            stream.eatWhile(/\w/);
	            return tokenSOMETHING(stream, state, stream.current().substr(2));
	          }
	          if (stream.sol() && stream.match(/^\=item(?!\w)/)) {
	            // NOTE: \n=item...\n=cut\n
	            return tokenSOMETHING(stream, state, '=cut');
	          }
	          var ch = stream.next();
	          if (ch == '"' || ch == "'") {
	            // NOTE: ' or " or <<'SOMETHING'\n...\nSOMETHING\n or <<"SOMETHING"\n...\nSOMETHING\n
	            if (prefix(stream, 3) == "<<" + ch) {
	              var p = stream.pos;
	              stream.eatWhile(/\w/);
	              var n = stream.current().substr(1);
	              if (n && stream.eat(ch)) return tokenSOMETHING(stream, state, n);
	              stream.pos = p;
	            }
	            return tokenChain(stream, state, [ch], "string");
	          }
	          if (ch == "q") {
	            var c = look(stream, -2);
	            if (!(c && /\w/.test(c))) {
	              c = look(stream, 0);
	              if (c == "x") {
	                c = look(stream, 1);
	                if (c == "(") {
	                  eatSuffix(stream, 2);
	                  return tokenChain(stream, state, [")"], RXstyle, RXmodifiers);
	                }
	                if (c == "[") {
	                  eatSuffix(stream, 2);
	                  return tokenChain(stream, state, ["]"], RXstyle, RXmodifiers);
	                }
	                if (c == "{") {
	                  eatSuffix(stream, 2);
	                  return tokenChain(stream, state, ["}"], RXstyle, RXmodifiers);
	                }
	                if (c == "<") {
	                  eatSuffix(stream, 2);
	                  return tokenChain(stream, state, [">"], RXstyle, RXmodifiers);
	                }
	                if (/[\^'"!~\/]/.test(c)) {
	                  eatSuffix(stream, 1);
	                  return tokenChain(stream, state, [stream.eat(c)], RXstyle, RXmodifiers);
	                }
	              } else if (c == "q") {
	                c = look(stream, 1);
	                if (c == "(") {
	                  eatSuffix(stream, 2);
	                  return tokenChain(stream, state, [")"], "string");
	                }
	                if (c == "[") {
	                  eatSuffix(stream, 2);
	                  return tokenChain(stream, state, ["]"], "string");
	                }
	                if (c == "{") {
	                  eatSuffix(stream, 2);
	                  return tokenChain(stream, state, ["}"], "string");
	                }
	                if (c == "<") {
	                  eatSuffix(stream, 2);
	                  return tokenChain(stream, state, [">"], "string");
	                }
	                if (/[\^'"!~\/]/.test(c)) {
	                  eatSuffix(stream, 1);
	                  return tokenChain(stream, state, [stream.eat(c)], "string");
	                }
	              } else if (c == "w") {
	                c = look(stream, 1);
	                if (c == "(") {
	                  eatSuffix(stream, 2);
	                  return tokenChain(stream, state, [")"], "bracket");
	                }
	                if (c == "[") {
	                  eatSuffix(stream, 2);
	                  return tokenChain(stream, state, ["]"], "bracket");
	                }
	                if (c == "{") {
	                  eatSuffix(stream, 2);
	                  return tokenChain(stream, state, ["}"], "bracket");
	                }
	                if (c == "<") {
	                  eatSuffix(stream, 2);
	                  return tokenChain(stream, state, [">"], "bracket");
	                }
	                if (/[\^'"!~\/]/.test(c)) {
	                  eatSuffix(stream, 1);
	                  return tokenChain(stream, state, [stream.eat(c)], "bracket");
	                }
	              } else if (c == "r") {
	                c = look(stream, 1);
	                if (c == "(") {
	                  eatSuffix(stream, 2);
	                  return tokenChain(stream, state, [")"], RXstyle, RXmodifiers);
	                }
	                if (c == "[") {
	                  eatSuffix(stream, 2);
	                  return tokenChain(stream, state, ["]"], RXstyle, RXmodifiers);
	                }
	                if (c == "{") {
	                  eatSuffix(stream, 2);
	                  return tokenChain(stream, state, ["}"], RXstyle, RXmodifiers);
	                }
	                if (c == "<") {
	                  eatSuffix(stream, 2);
	                  return tokenChain(stream, state, [">"], RXstyle, RXmodifiers);
	                }
	                if (/[\^'"!~\/]/.test(c)) {
	                  eatSuffix(stream, 1);
	                  return tokenChain(stream, state, [stream.eat(c)], RXstyle, RXmodifiers);
	                }
	              } else if (/[\^'"!~\/(\[{<]/.test(c)) {
	                if (c == "(") {
	                  eatSuffix(stream, 1);
	                  return tokenChain(stream, state, [")"], "string");
	                }
	                if (c == "[") {
	                  eatSuffix(stream, 1);
	                  return tokenChain(stream, state, ["]"], "string");
	                }
	                if (c == "{") {
	                  eatSuffix(stream, 1);
	                  return tokenChain(stream, state, ["}"], "string");
	                }
	                if (c == "<") {
	                  eatSuffix(stream, 1);
	                  return tokenChain(stream, state, [">"], "string");
	                }
	                if (/[\^'"!~\/]/.test(c)) {
	                  return tokenChain(stream, state, [stream.eat(c)], "string");
	                }
	              }
	            }
	          }
	          if (ch == "m") {
	            var c = look(stream, -2);
	            if (!(c && /\w/.test(c))) {
	              c = stream.eat(/[(\[{<\^'"!~\/]/);
	              if (c) {
	                if (/[\^'"!~\/]/.test(c)) {
	                  return tokenChain(stream, state, [c], RXstyle, RXmodifiers);
	                }
	                if (c == "(") {
	                  return tokenChain(stream, state, [")"], RXstyle, RXmodifiers);
	                }
	                if (c == "[") {
	                  return tokenChain(stream, state, ["]"], RXstyle, RXmodifiers);
	                }
	                if (c == "{") {
	                  return tokenChain(stream, state, ["}"], RXstyle, RXmodifiers);
	                }
	                if (c == "<") {
	                  return tokenChain(stream, state, [">"], RXstyle, RXmodifiers);
	                }
	              }
	            }
	          }
	          if (ch == "s") {
	            var c = /[\/>\]})\w]/.test(look(stream, -2));
	            if (!c) {
	              c = stream.eat(/[(\[{<\^'"!~\/]/);
	              if (c) {
	                if (c == "[") return tokenChain(stream, state, ["]", "]"], RXstyle, RXmodifiers);
	                if (c == "{") return tokenChain(stream, state, ["}", "}"], RXstyle, RXmodifiers);
	                if (c == "<") return tokenChain(stream, state, [">", ">"], RXstyle, RXmodifiers);
	                if (c == "(") return tokenChain(stream, state, [")", ")"], RXstyle, RXmodifiers);
	                return tokenChain(stream, state, [c, c], RXstyle, RXmodifiers);
	              }
	            }
	          }
	          if (ch == "y") {
	            var c = /[\/>\]})\w]/.test(look(stream, -2));
	            if (!c) {
	              c = stream.eat(/[(\[{<\^'"!~\/]/);
	              if (c) {
	                if (c == "[") return tokenChain(stream, state, ["]", "]"], RXstyle, RXmodifiers);
	                if (c == "{") return tokenChain(stream, state, ["}", "}"], RXstyle, RXmodifiers);
	                if (c == "<") return tokenChain(stream, state, [">", ">"], RXstyle, RXmodifiers);
	                if (c == "(") return tokenChain(stream, state, [")", ")"], RXstyle, RXmodifiers);
	                return tokenChain(stream, state, [c, c], RXstyle, RXmodifiers);
	              }
	            }
	          }
	          if (ch == "t") {
	            var c = /[\/>\]})\w]/.test(look(stream, -2));
	            if (!c) {
	              c = stream.eat("r");
	              if (c) {
	                c = stream.eat(/[(\[{<\^'"!~\/]/);
	                if (c) {
	                  if (c == "[") return tokenChain(stream, state, ["]", "]"], RXstyle, RXmodifiers);
	                  if (c == "{") return tokenChain(stream, state, ["}", "}"], RXstyle, RXmodifiers);
	                  if (c == "<") return tokenChain(stream, state, [">", ">"], RXstyle, RXmodifiers);
	                  if (c == "(") return tokenChain(stream, state, [")", ")"], RXstyle, RXmodifiers);
	                  return tokenChain(stream, state, [c, c], RXstyle, RXmodifiers);
	                }
	              }
	            }
	          }
	          if (ch == "`") {
	            return tokenChain(stream, state, [ch], "variable-2");
	          }
	          if (ch == "/") {
	            if (!/~\s*$/.test(prefix(stream))) return "operator";else return tokenChain(stream, state, [ch], RXstyle, RXmodifiers);
	          }
	          if (ch == "$") {
	            var p = stream.pos;
	            if (stream.eatWhile(/\d/) || stream.eat("{") && stream.eatWhile(/\d/) && stream.eat("}")) return "variable-2";else stream.pos = p;
	          }
	          if (/[$@%]/.test(ch)) {
	            var p = stream.pos;
	            if (stream.eat("^") && stream.eat(/[A-Z]/) || !/[@$%&]/.test(look(stream, -2)) && stream.eat(/[=|\\\-#?@;:&`~\^!\[\]*'"$+.,\/<>()]/)) {
	              var c = stream.current();
	              if (PERL[c]) return "variable-2";
	            }
	            stream.pos = p;
	          }
	          if (/[$@%&]/.test(ch)) {
	            if (stream.eatWhile(/[\w$]/) || stream.eat("{") && stream.eatWhile(/[\w$]/) && stream.eat("}")) {
	              var c = stream.current();
	              if (PERL[c]) return "variable-2";else return "variable";
	            }
	          }
	          if (ch == "#") {
	            if (look(stream, -2) != "$") {
	              stream.skipToEnd();
	              return "comment";
	            }
	          }
	          if (/[:+\-\^*$&%@=<>!?|\/~\.]/.test(ch)) {
	            var p = stream.pos;
	            stream.eatWhile(/[:+\-\^*$&%@=<>!?|\/~\.]/);
	            if (PERL[stream.current()]) return "operator";else stream.pos = p;
	          }
	          if (ch == "_") {
	            if (stream.pos == 1) {
	              if (suffix(stream, 6) == "_END__") {
	                return tokenChain(stream, state, ['\0'], "comment");
	              } else if (suffix(stream, 7) == "_DATA__") {
	                return tokenChain(stream, state, ['\0'], "variable-2");
	              } else if (suffix(stream, 7) == "_C__") {
	                return tokenChain(stream, state, ['\0'], "string");
	              }
	            }
	          }
	          if (/\w/.test(ch)) {
	            var p = stream.pos;
	            if (look(stream, -2) == "{" && (look(stream, 0) == "}" || stream.eatWhile(/\w/) && look(stream, 0) == "}")) return "string";else stream.pos = p;
	          }
	          if (/[A-Z]/.test(ch)) {
	            var l = look(stream, -2);
	            var p = stream.pos;
	            stream.eatWhile(/[A-Z_]/);
	            if (/[\da-z]/.test(look(stream, 0))) {
	              stream.pos = p;
	            } else {
	              var c = PERL[stream.current()];
	              if (!c) return "meta";
	              if (c[1]) c = c[0];
	              if (l != ":") {
	                if (c == 1) return "keyword";else if (c == 2) return "def";else if (c == 3) return "atom";else if (c == 4) return "operator";else if (c == 5) return "variable-2";else return "meta";
	              } else return "meta";
	            }
	          }
	          if (/[a-zA-Z_]/.test(ch)) {
	            var l = look(stream, -2);
	            stream.eatWhile(/\w/);
	            var c = PERL[stream.current()];
	            if (!c) return "meta";
	            if (c[1]) c = c[0];
	            if (l != ":") {
	              if (c == 1) return "keyword";else if (c == 2) return "def";else if (c == 3) return "atom";else if (c == 4) return "operator";else if (c == 5) return "variable-2";else return "meta";
	            } else return "meta";
	          }
	          return null;
	        }
	        return {
	          startState: function () {
	            return {
	              tokenize: tokenPerl,
	              chain: null,
	              style: null,
	              tail: null
	            };
	          },
	          token: function (stream, state) {
	            return (state.tokenize || tokenPerl)(stream, state);
	          },
	          lineComment: '#'
	        };
	      });
	      CodeMirror.registerHelper("wordChars", "perl", /[\w$]/);
	      CodeMirror.defineMIME("text/x-perl", "perl");

	      // it's like "peek", but need for look-ahead or look-behind if index < 0
	      function look(stream, c) {
	        return stream.string.charAt(stream.pos + (c || 0));
	      }

	      // return a part of prefix of current stream from current position
	      function prefix(stream, c) {
	        if (c) {
	          var x = stream.pos - c;
	          return stream.string.substr(x >= 0 ? x : 0, c);
	        } else {
	          return stream.string.substr(0, stream.pos - 1);
	        }
	      }

	      // return a part of suffix of current stream from current position
	      function suffix(stream, c) {
	        var y = stream.string.length;
	        var x = y - stream.pos + 1;
	        return stream.string.substr(stream.pos, c && c < y ? c : x);
	      }

	      // eating and vomiting a part of stream from current position
	      function eatSuffix(stream, c) {
	        var x = stream.pos + c;
	        var y;
	        if (x <= 0) stream.pos = 0;else if (x >= (y = stream.string.length - 1)) stream.pos = y;else stream.pos = x;
	      }
	    });
	  })();
	  return perl.exports;
	}

	requirePerl();

	var php = {exports: {}};

	var clike = {exports: {}};

	var hasRequiredClike;
	function requireClike() {
	  if (hasRequiredClike) return clike.exports;
	  hasRequiredClike = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      function Context(indented, column, type, info, align, prev) {
	        this.indented = indented;
	        this.column = column;
	        this.type = type;
	        this.info = info;
	        this.align = align;
	        this.prev = prev;
	      }
	      function pushContext(state, col, type, info) {
	        var indent = state.indented;
	        if (state.context && state.context.type == "statement" && type != "statement") indent = state.context.indented;
	        return state.context = new Context(indent, col, type, info, null, state.context);
	      }
	      function popContext(state) {
	        var t = state.context.type;
	        if (t == ")" || t == "]" || t == "}") state.indented = state.context.indented;
	        return state.context = state.context.prev;
	      }
	      function typeBefore(stream, state, pos) {
	        if (state.prevToken == "variable" || state.prevToken == "type") return true;
	        if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, pos))) return true;
	        if (state.typeAtEndOfLine && stream.column() == stream.indentation()) return true;
	      }
	      function isTopScope(context) {
	        for (;;) {
	          if (!context || context.type == "top") return true;
	          if (context.type == "}" && context.prev.info != "namespace") return false;
	          context = context.prev;
	        }
	      }
	      CodeMirror.defineMode("clike", function (config, parserConfig) {
	        var indentUnit = config.indentUnit,
	          statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
	          dontAlignCalls = parserConfig.dontAlignCalls,
	          keywords = parserConfig.keywords || {},
	          types = parserConfig.types || {},
	          builtin = parserConfig.builtin || {},
	          blockKeywords = parserConfig.blockKeywords || {},
	          defKeywords = parserConfig.defKeywords || {},
	          atoms = parserConfig.atoms || {},
	          hooks = parserConfig.hooks || {},
	          multiLineStrings = parserConfig.multiLineStrings,
	          indentStatements = parserConfig.indentStatements !== false,
	          indentSwitch = parserConfig.indentSwitch !== false,
	          namespaceSeparator = parserConfig.namespaceSeparator,
	          isPunctuationChar = parserConfig.isPunctuationChar || /[\[\]{}\(\),;\:\.]/,
	          numberStart = parserConfig.numberStart || /[\d\.]/,
	          number = parserConfig.number || /^(?:0x[a-f\d]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(u|ll?|l|f)?/i,
	          isOperatorChar = parserConfig.isOperatorChar || /[+\-*&%=<>!?|\/]/,
	          isIdentifierChar = parserConfig.isIdentifierChar || /[\w\$_\xa1-\uffff]/,
	          // An optional function that takes a {string} token and returns true if it
	          // should be treated as a builtin.
	          isReservedIdentifier = parserConfig.isReservedIdentifier || false;
	        var curPunc, isDefKeyword;
	        function tokenBase(stream, state) {
	          var ch = stream.next();
	          if (hooks[ch]) {
	            var result = hooks[ch](stream, state);
	            if (result !== false) return result;
	          }
	          if (ch == '"' || ch == "'") {
	            state.tokenize = tokenString(ch);
	            return state.tokenize(stream, state);
	          }
	          if (numberStart.test(ch)) {
	            stream.backUp(1);
	            if (stream.match(number)) return "number";
	            stream.next();
	          }
	          if (isPunctuationChar.test(ch)) {
	            curPunc = ch;
	            return null;
	          }
	          if (ch == "/") {
	            if (stream.eat("*")) {
	              state.tokenize = tokenComment;
	              return tokenComment(stream, state);
	            }
	            if (stream.eat("/")) {
	              stream.skipToEnd();
	              return "comment";
	            }
	          }
	          if (isOperatorChar.test(ch)) {
	            while (!stream.match(/^\/[\/*]/, false) && stream.eat(isOperatorChar)) {}
	            return "operator";
	          }
	          stream.eatWhile(isIdentifierChar);
	          if (namespaceSeparator) while (stream.match(namespaceSeparator)) stream.eatWhile(isIdentifierChar);
	          var cur = stream.current();
	          if (contains(keywords, cur)) {
	            if (contains(blockKeywords, cur)) curPunc = "newstatement";
	            if (contains(defKeywords, cur)) isDefKeyword = true;
	            return "keyword";
	          }
	          if (contains(types, cur)) return "type";
	          if (contains(builtin, cur) || isReservedIdentifier && isReservedIdentifier(cur)) {
	            if (contains(blockKeywords, cur)) curPunc = "newstatement";
	            return "builtin";
	          }
	          if (contains(atoms, cur)) return "atom";
	          return "variable";
	        }
	        function tokenString(quote) {
	          return function (stream, state) {
	            var escaped = false,
	              next,
	              end = false;
	            while ((next = stream.next()) != null) {
	              if (next == quote && !escaped) {
	                end = true;
	                break;
	              }
	              escaped = !escaped && next == "\\";
	            }
	            if (end || !(escaped || multiLineStrings)) state.tokenize = null;
	            return "string";
	          };
	        }
	        function tokenComment(stream, state) {
	          var maybeEnd = false,
	            ch;
	          while (ch = stream.next()) {
	            if (ch == "/" && maybeEnd) {
	              state.tokenize = null;
	              break;
	            }
	            maybeEnd = ch == "*";
	          }
	          return "comment";
	        }
	        function maybeEOL(stream, state) {
	          if (parserConfig.typeFirstDefinitions && stream.eol() && isTopScope(state.context)) state.typeAtEndOfLine = typeBefore(stream, state, stream.pos);
	        }

	        // Interface

	        return {
	          startState: function (basecolumn) {
	            return {
	              tokenize: null,
	              context: new Context((basecolumn || 0) - indentUnit, 0, "top", null, false),
	              indented: 0,
	              startOfLine: true,
	              prevToken: null
	            };
	          },
	          token: function (stream, state) {
	            var ctx = state.context;
	            if (stream.sol()) {
	              if (ctx.align == null) ctx.align = false;
	              state.indented = stream.indentation();
	              state.startOfLine = true;
	            }
	            if (stream.eatSpace()) {
	              maybeEOL(stream, state);
	              return null;
	            }
	            curPunc = isDefKeyword = null;
	            var style = (state.tokenize || tokenBase)(stream, state);
	            if (style == "comment" || style == "meta") return style;
	            if (ctx.align == null) ctx.align = true;
	            if (curPunc == ";" || curPunc == ":" || curPunc == "," && stream.match(/^\s*(?:\/\/.*)?$/, false)) while (state.context.type == "statement") popContext(state);else if (curPunc == "{") pushContext(state, stream.column(), "}");else if (curPunc == "[") pushContext(state, stream.column(), "]");else if (curPunc == "(") pushContext(state, stream.column(), ")");else if (curPunc == "}") {
	              while (ctx.type == "statement") ctx = popContext(state);
	              if (ctx.type == "}") ctx = popContext(state);
	              while (ctx.type == "statement") ctx = popContext(state);
	            } else if (curPunc == ctx.type) popContext(state);else if (indentStatements && ((ctx.type == "}" || ctx.type == "top") && curPunc != ";" || ctx.type == "statement" && curPunc == "newstatement")) {
	              pushContext(state, stream.column(), "statement", stream.current());
	            }
	            if (style == "variable" && (state.prevToken == "def" || parserConfig.typeFirstDefinitions && typeBefore(stream, state, stream.start) && isTopScope(state.context) && stream.match(/^\s*\(/, false))) style = "def";
	            if (hooks.token) {
	              var result = hooks.token(stream, state, style);
	              if (result !== undefined) style = result;
	            }
	            if (style == "def" && parserConfig.styleDefs === false) style = "variable";
	            state.startOfLine = false;
	            state.prevToken = isDefKeyword ? "def" : style || curPunc;
	            maybeEOL(stream, state);
	            return style;
	          },
	          indent: function (state, textAfter) {
	            if (state.tokenize != tokenBase && state.tokenize != null || state.typeAtEndOfLine && isTopScope(state.context)) return CodeMirror.Pass;
	            var ctx = state.context,
	              firstChar = textAfter && textAfter.charAt(0);
	            var closing = firstChar == ctx.type;
	            if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
	            if (parserConfig.dontIndentStatements) while (ctx.type == "statement" && parserConfig.dontIndentStatements.test(ctx.info)) ctx = ctx.prev;
	            if (hooks.indent) {
	              var hook = hooks.indent(state, ctx, textAfter, indentUnit);
	              if (typeof hook == "number") return hook;
	            }
	            var switchBlock = ctx.prev && ctx.prev.info == "switch";
	            if (parserConfig.allmanIndentation && /[{(]/.test(firstChar)) {
	              while (ctx.type != "top" && ctx.type != "}") ctx = ctx.prev;
	              return ctx.indented;
	            }
	            if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
	            if (ctx.align && (!dontAlignCalls || ctx.type != ")")) return ctx.column + (closing ? 0 : 1);
	            if (ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit;
	            return ctx.indented + (closing ? 0 : indentUnit) + (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0);
	          },
	          electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/,
	          blockCommentStart: "/*",
	          blockCommentEnd: "*/",
	          blockCommentContinue: " * ",
	          lineComment: "//",
	          fold: "brace"
	        };
	      });
	      function words(str) {
	        var obj = {},
	          words = str.split(" ");
	        for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
	        return obj;
	      }
	      function contains(words, word) {
	        if (typeof words === "function") {
	          return words(word);
	        } else {
	          return words.propertyIsEnumerable(word);
	        }
	      }
	      var cKeywords = "auto if break case register continue return default do sizeof " + "static else struct switch extern typedef union for goto while enum const " + "volatile inline restrict asm fortran";

	      // Keywords from https://en.cppreference.com/w/cpp/keyword includes C++20.
	      var cppKeywords = "alignas alignof and and_eq audit axiom bitand bitor catch " + "class compl concept constexpr const_cast decltype delete dynamic_cast " + "explicit export final friend import module mutable namespace new noexcept " + "not not_eq operator or or_eq override private protected public " + "reinterpret_cast requires static_assert static_cast template this " + "thread_local throw try typeid typename using virtual xor xor_eq";
	      var objCKeywords = "bycopy byref in inout oneway out self super atomic nonatomic retain copy " + "readwrite readonly strong weak assign typeof nullable nonnull null_resettable _cmd " + "@interface @implementation @end @protocol @encode @property @synthesize @dynamic @class " + "@public @package @private @protected @required @optional @try @catch @finally @import " + "@selector @encode @defs @synchronized @autoreleasepool @compatibility_alias @available";
	      var objCBuiltins = "FOUNDATION_EXPORT FOUNDATION_EXTERN NS_INLINE NS_FORMAT_FUNCTION " + " NS_RETURNS_RETAINEDNS_ERROR_ENUM NS_RETURNS_NOT_RETAINED NS_RETURNS_INNER_POINTER " + "NS_DESIGNATED_INITIALIZER NS_ENUM NS_OPTIONS NS_REQUIRES_NIL_TERMINATION " + "NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_SWIFT_NAME NS_REFINED_FOR_SWIFT";

	      // Do not use this. Use the cTypes function below. This is global just to avoid
	      // excessive calls when cTypes is being called multiple times during a parse.
	      var basicCTypes = words("int long char short double float unsigned signed " + "void bool");

	      // Do not use this. Use the objCTypes function below. This is global just to avoid
	      // excessive calls when objCTypes is being called multiple times during a parse.
	      var basicObjCTypes = words("SEL instancetype id Class Protocol BOOL");

	      // Returns true if identifier is a "C" type.
	      // C type is defined as those that are reserved by the compiler (basicTypes),
	      // and those that end in _t (Reserved by POSIX for types)
	      // http://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html
	      function cTypes(identifier) {
	        return contains(basicCTypes, identifier) || /.+_t$/.test(identifier);
	      }

	      // Returns true if identifier is a "Objective C" type.
	      function objCTypes(identifier) {
	        return cTypes(identifier) || contains(basicObjCTypes, identifier);
	      }
	      var cBlockKeywords = "case do else for if switch while struct enum union";
	      var cDefKeywords = "struct enum union";
	      function cppHook(stream, state) {
	        if (!state.startOfLine) return false;
	        for (var ch, next = null; ch = stream.peek();) {
	          if (ch == "\\" && stream.match(/^.$/)) {
	            next = cppHook;
	            break;
	          } else if (ch == "/" && stream.match(/^\/[\/\*]/, false)) {
	            break;
	          }
	          stream.next();
	        }
	        state.tokenize = next;
	        return "meta";
	      }
	      function pointerHook(_stream, state) {
	        if (state.prevToken == "type") return "type";
	        return false;
	      }

	      // For C and C++ (and ObjC): identifiers starting with __
	      // or _ followed by a capital letter are reserved for the compiler.
	      function cIsReservedIdentifier(token) {
	        if (!token || token.length < 2) return false;
	        if (token[0] != '_') return false;
	        return token[1] == '_' || token[1] !== token[1].toLowerCase();
	      }
	      function cpp14Literal(stream) {
	        stream.eatWhile(/[\w\.']/);
	        return "number";
	      }
	      function cpp11StringHook(stream, state) {
	        stream.backUp(1);
	        // Raw strings.
	        if (stream.match(/^(?:R|u8R|uR|UR|LR)/)) {
	          var match = stream.match(/^"([^\s\\()]{0,16})\(/);
	          if (!match) {
	            return false;
	          }
	          state.cpp11RawStringDelim = match[1];
	          state.tokenize = tokenRawString;
	          return tokenRawString(stream, state);
	        }
	        // Unicode strings/chars.
	        if (stream.match(/^(?:u8|u|U|L)/)) {
	          if (stream.match(/^["']/, /* eat */false)) {
	            return "string";
	          }
	          return false;
	        }
	        // Ignore this hook.
	        stream.next();
	        return false;
	      }
	      function cppLooksLikeConstructor(word) {
	        var lastTwo = /(\w+)::~?(\w+)$/.exec(word);
	        return lastTwo && lastTwo[1] == lastTwo[2];
	      }

	      // C#-style strings where "" escapes a quote.
	      function tokenAtString(stream, state) {
	        var next;
	        while ((next = stream.next()) != null) {
	          if (next == '"' && !stream.eat('"')) {
	            state.tokenize = null;
	            break;
	          }
	        }
	        return "string";
	      }

	      // C++11 raw string literal is <prefix>"<delim>( anything )<delim>", where
	      // <delim> can be a string up to 16 characters long.
	      function tokenRawString(stream, state) {
	        // Escape characters that have special regex meanings.
	        var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&');
	        var match = stream.match(new RegExp(".*?\\)" + delim + '"'));
	        if (match) state.tokenize = null;else stream.skipToEnd();
	        return "string";
	      }
	      function def(mimes, mode) {
	        if (typeof mimes == "string") mimes = [mimes];
	        var words = [];
	        function add(obj) {
	          if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop)) words.push(prop);
	        }
	        add(mode.keywords);
	        add(mode.types);
	        add(mode.builtin);
	        add(mode.atoms);
	        if (words.length) {
	          mode.helperType = mimes[0];
	          CodeMirror.registerHelper("hintWords", mimes[0], words);
	        }
	        for (var i = 0; i < mimes.length; ++i) CodeMirror.defineMIME(mimes[i], mode);
	      }
	      def(["text/x-csrc", "text/x-c", "text/x-chdr"], {
	        name: "clike",
	        keywords: words(cKeywords),
	        types: cTypes,
	        blockKeywords: words(cBlockKeywords),
	        defKeywords: words(cDefKeywords),
	        typeFirstDefinitions: true,
	        atoms: words("NULL true false"),
	        isReservedIdentifier: cIsReservedIdentifier,
	        hooks: {
	          "#": cppHook,
	          "*": pointerHook
	        },
	        modeProps: {
	          fold: ["brace", "include"]
	        }
	      });
	      def(["text/x-c++src", "text/x-c++hdr"], {
	        name: "clike",
	        keywords: words(cKeywords + " " + cppKeywords),
	        types: cTypes,
	        blockKeywords: words(cBlockKeywords + " class try catch"),
	        defKeywords: words(cDefKeywords + " class namespace"),
	        typeFirstDefinitions: true,
	        atoms: words("true false NULL nullptr"),
	        dontIndentStatements: /^template$/,
	        isIdentifierChar: /[\w\$_~\xa1-\uffff]/,
	        isReservedIdentifier: cIsReservedIdentifier,
	        hooks: {
	          "#": cppHook,
	          "*": pointerHook,
	          "u": cpp11StringHook,
	          "U": cpp11StringHook,
	          "L": cpp11StringHook,
	          "R": cpp11StringHook,
	          "0": cpp14Literal,
	          "1": cpp14Literal,
	          "2": cpp14Literal,
	          "3": cpp14Literal,
	          "4": cpp14Literal,
	          "5": cpp14Literal,
	          "6": cpp14Literal,
	          "7": cpp14Literal,
	          "8": cpp14Literal,
	          "9": cpp14Literal,
	          token: function (stream, state, style) {
	            if (style == "variable" && stream.peek() == "(" && (state.prevToken == ";" || state.prevToken == null || state.prevToken == "}") && cppLooksLikeConstructor(stream.current())) return "def";
	          }
	        },
	        namespaceSeparator: "::",
	        modeProps: {
	          fold: ["brace", "include"]
	        }
	      });
	      def("text/x-java", {
	        name: "clike",
	        keywords: words("abstract assert break case catch class const continue default " + "do else enum extends final finally for goto if implements import " + "instanceof interface native new package private protected public " + "return static strictfp super switch synchronized this throw throws transient " + "try volatile while @interface"),
	        types: words("var byte short int long float double boolean char void Boolean Byte Character Double Float " + "Integer Long Number Object Short String StringBuffer StringBuilder Void"),
	        blockKeywords: words("catch class do else finally for if switch try while"),
	        defKeywords: words("class interface enum @interface"),
	        typeFirstDefinitions: true,
	        atoms: words("true false null"),
	        number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,
	        hooks: {
	          "@": function (stream) {
	            // Don't match the @interface keyword.
	            if (stream.match('interface', false)) return false;
	            stream.eatWhile(/[\w\$_]/);
	            return "meta";
	          },
	          '"': function (stream, state) {
	            if (!stream.match(/""$/)) return false;
	            state.tokenize = tokenTripleString;
	            return state.tokenize(stream, state);
	          }
	        },
	        modeProps: {
	          fold: ["brace", "import"]
	        }
	      });
	      def("text/x-csharp", {
	        name: "clike",
	        keywords: words("abstract as async await base break case catch checked class const continue" + " default delegate do else enum event explicit extern finally fixed for" + " foreach goto if implicit in init interface internal is lock namespace new" + " operator out override params private protected public readonly record ref required return sealed" + " sizeof stackalloc static struct switch this throw try typeof unchecked" + " unsafe using virtual void volatile while add alias ascending descending dynamic from get" + " global group into join let orderby partial remove select set value var yield"),
	        types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" + " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" + " UInt64 bool byte char decimal double short int long object" + " sbyte float string ushort uint ulong"),
	        blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
	        defKeywords: words("class interface namespace record struct var"),
	        typeFirstDefinitions: true,
	        atoms: words("true false null"),
	        hooks: {
	          "@": function (stream, state) {
	            if (stream.eat('"')) {
	              state.tokenize = tokenAtString;
	              return tokenAtString(stream, state);
	            }
	            stream.eatWhile(/[\w\$_]/);
	            return "meta";
	          }
	        }
	      });
	      function tokenTripleString(stream, state) {
	        var escaped = false;
	        while (!stream.eol()) {
	          if (!escaped && stream.match('"""')) {
	            state.tokenize = null;
	            break;
	          }
	          escaped = stream.next() == "\\" && !escaped;
	        }
	        return "string";
	      }
	      function tokenNestedComment(depth) {
	        return function (stream, state) {
	          var ch;
	          while (ch = stream.next()) {
	            if (ch == "*" && stream.eat("/")) {
	              if (depth == 1) {
	                state.tokenize = null;
	                break;
	              } else {
	                state.tokenize = tokenNestedComment(depth - 1);
	                return state.tokenize(stream, state);
	              }
	            } else if (ch == "/" && stream.eat("*")) {
	              state.tokenize = tokenNestedComment(depth + 1);
	              return state.tokenize(stream, state);
	            }
	          }
	          return "comment";
	        };
	      }
	      def("text/x-scala", {
	        name: "clike",
	        keywords: words(/* scala */
	        "abstract case catch class def do else extends final finally for forSome if " + "implicit import lazy match new null object override package private protected return " + "sealed super this throw trait try type val var while with yield _ " + /* package scala */
	        "assert assume require print println printf readLine readBoolean readByte readShort " + "readChar readInt readLong readFloat readDouble"),
	        types: words("AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " + "Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable " + "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " + "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " + "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector " + /* package java.lang */
	        "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"),
	        multiLineStrings: true,
	        blockKeywords: words("catch class enum do else finally for forSome if match switch try while"),
	        defKeywords: words("class enum def object package trait type val var"),
	        atoms: words("true false null"),
	        indentStatements: false,
	        indentSwitch: false,
	        isOperatorChar: /[+\-*&%=<>!?|\/#:@]/,
	        hooks: {
	          "@": function (stream) {
	            stream.eatWhile(/[\w\$_]/);
	            return "meta";
	          },
	          '"': function (stream, state) {
	            if (!stream.match('""')) return false;
	            state.tokenize = tokenTripleString;
	            return state.tokenize(stream, state);
	          },
	          "'": function (stream) {
	            if (stream.match(/^(\\[^'\s]+|[^\\'])'/)) return "string-2";
	            stream.eatWhile(/[\w\$_\xa1-\uffff]/);
	            return "atom";
	          },
	          "=": function (stream, state) {
	            var cx = state.context;
	            if (cx.type == "}" && cx.align && stream.eat(">")) {
	              state.context = new Context(cx.indented, cx.column, cx.type, cx.info, null, cx.prev);
	              return "operator";
	            } else {
	              return false;
	            }
	          },
	          "/": function (stream, state) {
	            if (!stream.eat("*")) return false;
	            state.tokenize = tokenNestedComment(1);
	            return state.tokenize(stream, state);
	          }
	        },
	        modeProps: {
	          closeBrackets: {
	            pairs: '()[]{}""',
	            triples: '"'
	          }
	        }
	      });
	      function tokenKotlinString(tripleString) {
	        return function (stream, state) {
	          var escaped = false,
	            next,
	            end = false;
	          while (!stream.eol()) {
	            if (!tripleString && !escaped && stream.match('"')) {
	              end = true;
	              break;
	            }
	            if (tripleString && stream.match('"""')) {
	              end = true;
	              break;
	            }
	            next = stream.next();
	            if (!escaped && next == "$" && stream.match('{')) stream.skipTo("}");
	            escaped = !escaped && next == "\\" && !tripleString;
	          }
	          if (end || !tripleString) state.tokenize = null;
	          return "string";
	        };
	      }
	      def("text/x-kotlin", {
	        name: "clike",
	        keywords: words(/*keywords*/
	        "package as typealias class interface this super val operator " + "var fun for is in This throw return annotation " + "break continue object if else while do try when !in !is as? " + /*soft keywords*/
	        "file import where by get set abstract enum open inner override private public internal " + "protected catch finally out final vararg reified dynamic companion constructor init " + "sealed field property receiver param sparam lateinit data inline noinline tailrec " + "external annotation crossinline const operator infix suspend actual expect setparam value"),
	        types: words(/* package java.lang */
	        "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void Annotation Any BooleanArray " + "ByteArray Char CharArray DeprecationLevel DoubleArray Enum FloatArray Function Int IntArray Lazy " + "LazyThreadSafetyMode LongArray Nothing ShortArray Unit"),
	        indentSwitch: false,
	        indentStatements: false,
	        multiLineStrings: true,
	        number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+(\.\d+)?|\.\d+)(?:e[-+]?[\d_]+)?)(ul?|l|f)?/i,
	        blockKeywords: words("catch class do else finally for if where try while enum"),
	        defKeywords: words("class val var object interface fun"),
	        atoms: words("true false null this"),
	        hooks: {
	          "@": function (stream) {
	            stream.eatWhile(/[\w\$_]/);
	            return "meta";
	          },
	          '*': function (_stream, state) {
	            return state.prevToken == '.' ? 'variable' : 'operator';
	          },
	          '"': function (stream, state) {
	            state.tokenize = tokenKotlinString(stream.match('""'));
	            return state.tokenize(stream, state);
	          },
	          "/": function (stream, state) {
	            if (!stream.eat("*")) return false;
	            state.tokenize = tokenNestedComment(1);
	            return state.tokenize(stream, state);
	          },
	          indent: function (state, ctx, textAfter, indentUnit) {
	            var firstChar = textAfter && textAfter.charAt(0);
	            if ((state.prevToken == "}" || state.prevToken == ")") && textAfter == "") return state.indented;
	            if (state.prevToken == "operator" && textAfter != "}" && state.context.type != "}" || state.prevToken == "variable" && firstChar == "." || (state.prevToken == "}" || state.prevToken == ")") && firstChar == ".") return indentUnit * 2 + ctx.indented;
	            if (ctx.align && ctx.type == "}") return ctx.indented + (state.context.type == (textAfter || "").charAt(0) ? 0 : indentUnit);
	          }
	        },
	        modeProps: {
	          closeBrackets: {
	            triples: '"'
	          }
	        }
	      });
	      def(["x-shader/x-vertex", "x-shader/x-fragment"], {
	        name: "clike",
	        keywords: words("sampler1D sampler2D sampler3D samplerCube " + "sampler1DShadow sampler2DShadow " + "const attribute uniform varying " + "break continue discard return " + "for while do if else struct " + "in out inout"),
	        types: words("float int bool void " + "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " + "mat2 mat3 mat4"),
	        blockKeywords: words("for while do if else struct"),
	        builtin: words("radians degrees sin cos tan asin acos atan " + "pow exp log exp2 sqrt inversesqrt " + "abs sign floor ceil fract mod min max clamp mix step smoothstep " + "length distance dot cross normalize ftransform faceforward " + "reflect refract matrixCompMult " + "lessThan lessThanEqual greaterThan greaterThanEqual " + "equal notEqual any all not " + "texture1D texture1DProj texture1DLod texture1DProjLod " + "texture2D texture2DProj texture2DLod texture2DProjLod " + "texture3D texture3DProj texture3DLod texture3DProjLod " + "textureCube textureCubeLod " + "shadow1D shadow2D shadow1DProj shadow2DProj " + "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " + "dFdx dFdy fwidth " + "noise1 noise2 noise3 noise4"),
	        atoms: words("true false " + "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " + "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " + "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " + "gl_FogCoord gl_PointCoord " + "gl_Position gl_PointSize gl_ClipVertex " + "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " + "gl_TexCoord gl_FogFragCoord " + "gl_FragCoord gl_FrontFacing " + "gl_FragData gl_FragDepth " + "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " + "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " + "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " + "gl_TextureMatrixTranspose gl_ModelViewMatrixInverseTranspose " + "gl_ProjectionMatrixInverseTranspose " + "gl_ModelViewProjectionMatrixInverseTranspose " + "gl_TextureMatrixInverseTranspose " + "gl_NormalScale gl_DepthRange gl_ClipPlane " + "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " + "gl_FrontLightModelProduct gl_BackLightModelProduct " + "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " + "gl_FogParameters " + "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " + "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " + "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " + "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " + "gl_MaxDrawBuffers"),
	        indentSwitch: false,
	        hooks: {
	          "#": cppHook
	        },
	        modeProps: {
	          fold: ["brace", "include"]
	        }
	      });
	      def("text/x-nesc", {
	        name: "clike",
	        keywords: words(cKeywords + " as atomic async call command component components configuration event generic " + "implementation includes interface module new norace nx_struct nx_union post provides " + "signal task uses abstract extends"),
	        types: cTypes,
	        blockKeywords: words(cBlockKeywords),
	        atoms: words("null true false"),
	        hooks: {
	          "#": cppHook
	        },
	        modeProps: {
	          fold: ["brace", "include"]
	        }
	      });
	      def("text/x-objectivec", {
	        name: "clike",
	        keywords: words(cKeywords + " " + objCKeywords),
	        types: objCTypes,
	        builtin: words(objCBuiltins),
	        blockKeywords: words(cBlockKeywords + " @synthesize @try @catch @finally @autoreleasepool @synchronized"),
	        defKeywords: words(cDefKeywords + " @interface @implementation @protocol @class"),
	        dontIndentStatements: /^@.*$/,
	        typeFirstDefinitions: true,
	        atoms: words("YES NO NULL Nil nil true false nullptr"),
	        isReservedIdentifier: cIsReservedIdentifier,
	        hooks: {
	          "#": cppHook,
	          "*": pointerHook
	        },
	        modeProps: {
	          fold: ["brace", "include"]
	        }
	      });
	      def("text/x-objectivec++", {
	        name: "clike",
	        keywords: words(cKeywords + " " + objCKeywords + " " + cppKeywords),
	        types: objCTypes,
	        builtin: words(objCBuiltins),
	        blockKeywords: words(cBlockKeywords + " @synthesize @try @catch @finally @autoreleasepool @synchronized class try catch"),
	        defKeywords: words(cDefKeywords + " @interface @implementation @protocol @class class namespace"),
	        dontIndentStatements: /^@.*$|^template$/,
	        typeFirstDefinitions: true,
	        atoms: words("YES NO NULL Nil nil true false nullptr"),
	        isReservedIdentifier: cIsReservedIdentifier,
	        hooks: {
	          "#": cppHook,
	          "*": pointerHook,
	          "u": cpp11StringHook,
	          "U": cpp11StringHook,
	          "L": cpp11StringHook,
	          "R": cpp11StringHook,
	          "0": cpp14Literal,
	          "1": cpp14Literal,
	          "2": cpp14Literal,
	          "3": cpp14Literal,
	          "4": cpp14Literal,
	          "5": cpp14Literal,
	          "6": cpp14Literal,
	          "7": cpp14Literal,
	          "8": cpp14Literal,
	          "9": cpp14Literal,
	          token: function (stream, state, style) {
	            if (style == "variable" && stream.peek() == "(" && (state.prevToken == ";" || state.prevToken == null || state.prevToken == "}") && cppLooksLikeConstructor(stream.current())) return "def";
	          }
	        },
	        namespaceSeparator: "::",
	        modeProps: {
	          fold: ["brace", "include"]
	        }
	      });
	      def("text/x-squirrel", {
	        name: "clike",
	        keywords: words("base break clone continue const default delete enum extends function in class" + " foreach local resume return this throw typeof yield constructor instanceof static"),
	        types: cTypes,
	        blockKeywords: words("case catch class else for foreach if switch try while"),
	        defKeywords: words("function local class"),
	        typeFirstDefinitions: true,
	        atoms: words("true false null"),
	        hooks: {
	          "#": cppHook
	        },
	        modeProps: {
	          fold: ["brace", "include"]
	        }
	      });

	      // Ceylon Strings need to deal with interpolation
	      var stringTokenizer = null;
	      function tokenCeylonString(type) {
	        return function (stream, state) {
	          var escaped = false,
	            next,
	            end = false;
	          while (!stream.eol()) {
	            if (!escaped && stream.match('"') && (type == "single" || stream.match('""'))) {
	              end = true;
	              break;
	            }
	            if (!escaped && stream.match('``')) {
	              stringTokenizer = tokenCeylonString(type);
	              end = true;
	              break;
	            }
	            next = stream.next();
	            escaped = type == "single" && !escaped && next == "\\";
	          }
	          if (end) state.tokenize = null;
	          return "string";
	        };
	      }
	      def("text/x-ceylon", {
	        name: "clike",
	        keywords: words("abstracts alias assembly assert assign break case catch class continue dynamic else" + " exists extends finally for function given if import in interface is let module new" + " nonempty object of out outer package return satisfies super switch then this throw" + " try value void while"),
	        types: function (word) {
	          // In Ceylon all identifiers that start with an uppercase are types
	          var first = word.charAt(0);
	          return first === first.toUpperCase() && first !== first.toLowerCase();
	        },
	        blockKeywords: words("case catch class dynamic else finally for function if interface module new object switch try while"),
	        defKeywords: words("class dynamic function interface module object package value"),
	        builtin: words("abstract actual aliased annotation by default deprecated doc final formal late license" + " native optional sealed see serializable shared suppressWarnings tagged throws variable"),
	        isPunctuationChar: /[\[\]{}\(\),;\:\.`]/,
	        isOperatorChar: /[+\-*&%=<>!?|^~:\/]/,
	        numberStart: /[\d#$]/,
	        number: /^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i,
	        multiLineStrings: true,
	        typeFirstDefinitions: true,
	        atoms: words("true false null larger smaller equal empty finished"),
	        indentSwitch: false,
	        styleDefs: false,
	        hooks: {
	          "@": function (stream) {
	            stream.eatWhile(/[\w\$_]/);
	            return "meta";
	          },
	          '"': function (stream, state) {
	            state.tokenize = tokenCeylonString(stream.match('""') ? "triple" : "single");
	            return state.tokenize(stream, state);
	          },
	          '`': function (stream, state) {
	            if (!stringTokenizer || !stream.match('`')) return false;
	            state.tokenize = stringTokenizer;
	            stringTokenizer = null;
	            return state.tokenize(stream, state);
	          },
	          "'": function (stream) {
	            stream.eatWhile(/[\w\$_\xa1-\uffff]/);
	            return "atom";
	          },
	          token: function (_stream, state, style) {
	            if ((style == "variable" || style == "type") && state.prevToken == ".") {
	              return "variable-2";
	            }
	          }
	        },
	        modeProps: {
	          fold: ["brace", "import"],
	          closeBrackets: {
	            triples: '"'
	          }
	        }
	      });
	    });
	  })();
	  return clike.exports;
	}

	var hasRequiredPhp;
	function requirePhp() {
	  if (hasRequiredPhp) return php.exports;
	  hasRequiredPhp = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror(), requireHtmlmixed(), requireClike());
	    })(function (CodeMirror) {

	      function keywords(str) {
	        var obj = {},
	          words = str.split(" ");
	        for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
	        return obj;
	      }

	      // Helper for phpString
	      function matchSequence(list, end, escapes) {
	        if (list.length == 0) return phpString(end);
	        return function (stream, state) {
	          var patterns = list[0];
	          for (var i = 0; i < patterns.length; i++) if (stream.match(patterns[i][0])) {
	            state.tokenize = matchSequence(list.slice(1), end);
	            return patterns[i][1];
	          }
	          state.tokenize = phpString(end, escapes);
	          return "string";
	        };
	      }
	      function phpString(closing, escapes) {
	        return function (stream, state) {
	          return phpString_(stream, state, closing, escapes);
	        };
	      }
	      function phpString_(stream, state, closing, escapes) {
	        // "Complex" syntax
	        if (escapes !== false && stream.match("${", false) || stream.match("{$", false)) {
	          state.tokenize = null;
	          return "string";
	        }

	        // Simple syntax
	        if (escapes !== false && stream.match(/^\$[a-zA-Z_][a-zA-Z0-9_]*/)) {
	          // After the variable name there may appear array or object operator.
	          if (stream.match("[", false)) {
	            // Match array operator
	            state.tokenize = matchSequence([[["[", null]], [[/\d[\w\.]*/, "number"], [/\$[a-zA-Z_][a-zA-Z0-9_]*/, "variable-2"], [/[\w\$]+/, "variable"]], [["]", null]]], closing, escapes);
	          }
	          if (stream.match(/^->\w/, false)) {
	            // Match object operator
	            state.tokenize = matchSequence([[["->", null]], [[/[\w]+/, "variable"]]], closing, escapes);
	          }
	          return "variable-2";
	        }
	        var escaped = false;
	        // Normal string
	        while (!stream.eol() && (escaped || escapes === false || !stream.match("{$", false) && !stream.match(/^(\$[a-zA-Z_][a-zA-Z0-9_]*|\$\{)/, false))) {
	          if (!escaped && stream.match(closing)) {
	            state.tokenize = null;
	            state.tokStack.pop();
	            state.tokStack.pop();
	            break;
	          }
	          escaped = stream.next() == "\\" && !escaped;
	        }
	        return "string";
	      }
	      var phpKeywords = "abstract and array as break case catch class clone const continue declare default " + "do else elseif enddeclare endfor endforeach endif endswitch endwhile enum extends final " + "for foreach function global goto if implements interface instanceof namespace " + "new or private protected public static switch throw trait try use var while xor " + "die echo empty exit eval include include_once isset list require require_once return " + "print unset __halt_compiler self static parent yield insteadof finally readonly match";
	      var phpAtoms = "true false null TRUE FALSE NULL __CLASS__ __DIR__ __FILE__ __LINE__ __METHOD__ __FUNCTION__ __NAMESPACE__ __TRAIT__";
	      var phpBuiltin = "func_num_args func_get_arg func_get_args strlen strcmp strncmp strcasecmp strncasecmp each error_reporting define defined trigger_error user_error set_error_handler restore_error_handler get_declared_classes get_loaded_extensions extension_loaded get_extension_funcs debug_backtrace constant bin2hex hex2bin sleep usleep time mktime gmmktime strftime gmstrftime strtotime date gmdate getdate localtime checkdate flush wordwrap htmlspecialchars htmlentities html_entity_decode md5 md5_file crc32 getimagesize image_type_to_mime_type phpinfo phpversion phpcredits strnatcmp strnatcasecmp substr_count strspn strcspn strtok strtoupper strtolower strpos strrpos strrev hebrev hebrevc nl2br basename dirname pathinfo stripslashes stripcslashes strstr stristr strrchr str_shuffle str_word_count strcoll substr substr_replace quotemeta ucfirst ucwords strtr addslashes addcslashes rtrim str_replace str_repeat count_chars chunk_split trim ltrim strip_tags similar_text explode implode setlocale localeconv parse_str str_pad chop strchr sprintf printf vprintf vsprintf sscanf fscanf parse_url urlencode urldecode rawurlencode rawurldecode readlink linkinfo link unlink exec system escapeshellcmd escapeshellarg passthru shell_exec proc_open proc_close rand srand getrandmax mt_rand mt_srand mt_getrandmax base64_decode base64_encode abs ceil floor round is_finite is_nan is_infinite bindec hexdec octdec decbin decoct dechex base_convert number_format fmod ip2long long2ip getenv putenv getopt microtime gettimeofday getrusage uniqid quoted_printable_decode set_time_limit get_cfg_var magic_quotes_runtime set_magic_quotes_runtime get_magic_quotes_gpc get_magic_quotes_runtime import_request_variables error_log serialize unserialize memory_get_usage memory_get_peak_usage var_dump var_export debug_zval_dump print_r highlight_file show_source highlight_string ini_get ini_get_all ini_set ini_alter ini_restore get_include_path set_include_path restore_include_path setcookie header headers_sent connection_aborted connection_status ignore_user_abort parse_ini_file is_uploaded_file move_uploaded_file intval floatval doubleval strval gettype settype is_null is_resource is_bool is_long is_float is_int is_integer is_double is_real is_numeric is_string is_array is_object is_scalar ereg ereg_replace eregi eregi_replace split spliti join sql_regcase dl pclose popen readfile rewind rmdir umask fclose feof fgetc fgets fgetss fread fopen fpassthru ftruncate fstat fseek ftell fflush fwrite fputs mkdir rename copy tempnam tmpfile file file_get_contents file_put_contents stream_select stream_context_create stream_context_set_params stream_context_set_option stream_context_get_options stream_filter_prepend stream_filter_append fgetcsv flock get_meta_tags stream_set_write_buffer set_file_buffer set_socket_blocking stream_set_blocking socket_set_blocking stream_get_meta_data stream_register_wrapper stream_wrapper_register stream_set_timeout socket_set_timeout socket_get_status realpath fnmatch fsockopen pfsockopen pack unpack get_browser crypt opendir closedir chdir getcwd rewinddir readdir dir glob fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype file_exists is_writable is_writeable is_readable is_executable is_file is_dir is_link stat lstat chown touch clearstatcache mail ob_start ob_flush ob_clean ob_end_flush ob_end_clean ob_get_flush ob_get_clean ob_get_length ob_get_level ob_get_status ob_get_contents ob_implicit_flush ob_list_handlers ksort krsort natsort natcasesort asort arsort sort rsort usort uasort uksort shuffle array_walk count end prev next reset current key min max in_array array_search extract compact array_fill range array_multisort array_push array_pop array_shift array_unshift array_splice array_slice array_merge array_merge_recursive array_keys array_values array_count_values array_reverse array_reduce array_pad array_flip array_change_key_case array_rand array_unique array_intersect array_intersect_assoc array_diff array_diff_assoc array_sum array_filter array_map array_chunk array_key_exists array_intersect_key array_combine array_column pos sizeof key_exists assert assert_options version_compare ftok str_rot13 aggregate session_name session_module_name session_save_path session_id session_regenerate_id session_decode session_register session_unregister session_is_registered session_encode session_start session_destroy session_unset session_set_save_handler session_cache_limiter session_cache_expire session_set_cookie_params session_get_cookie_params session_write_close preg_match preg_match_all preg_replace preg_replace_callback preg_split preg_quote preg_grep overload ctype_alnum ctype_alpha ctype_cntrl ctype_digit ctype_lower ctype_graph ctype_print ctype_punct ctype_space ctype_upper ctype_xdigit virtual apache_request_headers apache_note apache_lookup_uri apache_child_terminate apache_setenv apache_response_headers apache_get_version getallheaders mysql_connect mysql_pconnect mysql_close mysql_select_db mysql_create_db mysql_drop_db mysql_query mysql_unbuffered_query mysql_db_query mysql_list_dbs mysql_list_tables mysql_list_fields mysql_list_processes mysql_error mysql_errno mysql_affected_rows mysql_insert_id mysql_result mysql_num_rows mysql_num_fields mysql_fetch_row mysql_fetch_array mysql_fetch_assoc mysql_fetch_object mysql_data_seek mysql_fetch_lengths mysql_fetch_field mysql_field_seek mysql_free_result mysql_field_name mysql_field_table mysql_field_len mysql_field_type mysql_field_flags mysql_escape_string mysql_real_escape_string mysql_stat mysql_thread_id mysql_client_encoding mysql_get_client_info mysql_get_host_info mysql_get_proto_info mysql_get_server_info mysql_info mysql mysql_fieldname mysql_fieldtable mysql_fieldlen mysql_fieldtype mysql_fieldflags mysql_selectdb mysql_createdb mysql_dropdb mysql_freeresult mysql_numfields mysql_numrows mysql_listdbs mysql_listtables mysql_listfields mysql_db_name mysql_dbname mysql_tablename mysql_table_name pg_connect pg_pconnect pg_close pg_connection_status pg_connection_busy pg_connection_reset pg_host pg_dbname pg_port pg_tty pg_options pg_ping pg_query pg_send_query pg_cancel_query pg_fetch_result pg_fetch_row pg_fetch_assoc pg_fetch_array pg_fetch_object pg_fetch_all pg_affected_rows pg_get_result pg_result_seek pg_result_status pg_free_result pg_last_oid pg_num_rows pg_num_fields pg_field_name pg_field_num pg_field_size pg_field_type pg_field_prtlen pg_field_is_null pg_get_notify pg_get_pid pg_result_error pg_last_error pg_last_notice pg_put_line pg_end_copy pg_copy_to pg_copy_from pg_trace pg_untrace pg_lo_create pg_lo_unlink pg_lo_open pg_lo_close pg_lo_read pg_lo_write pg_lo_read_all pg_lo_import pg_lo_export pg_lo_seek pg_lo_tell pg_escape_string pg_escape_bytea pg_unescape_bytea pg_client_encoding pg_set_client_encoding pg_meta_data pg_convert pg_insert pg_update pg_delete pg_select pg_exec pg_getlastoid pg_cmdtuples pg_errormessage pg_numrows pg_numfields pg_fieldname pg_fieldsize pg_fieldtype pg_fieldnum pg_fieldprtlen pg_fieldisnull pg_freeresult pg_result pg_loreadall pg_locreate pg_lounlink pg_loopen pg_loclose pg_loread pg_lowrite pg_loimport pg_loexport http_response_code get_declared_traits getimagesizefromstring socket_import_stream stream_set_chunk_size trait_exists header_register_callback class_uses session_status session_register_shutdown echo print global static exit array empty eval isset unset die include require include_once require_once json_decode json_encode json_last_error json_last_error_msg curl_close curl_copy_handle curl_errno curl_error curl_escape curl_exec curl_file_create curl_getinfo curl_init curl_multi_add_handle curl_multi_close curl_multi_exec curl_multi_getcontent curl_multi_info_read curl_multi_init curl_multi_remove_handle curl_multi_select curl_multi_setopt curl_multi_strerror curl_pause curl_reset curl_setopt_array curl_setopt curl_share_close curl_share_init curl_share_setopt curl_strerror curl_unescape curl_version mysqli_affected_rows mysqli_autocommit mysqli_change_user mysqli_character_set_name mysqli_close mysqli_commit mysqli_connect_errno mysqli_connect_error mysqli_connect mysqli_data_seek mysqli_debug mysqli_dump_debug_info mysqli_errno mysqli_error_list mysqli_error mysqli_fetch_all mysqli_fetch_array mysqli_fetch_assoc mysqli_fetch_field_direct mysqli_fetch_field mysqli_fetch_fields mysqli_fetch_lengths mysqli_fetch_object mysqli_fetch_row mysqli_field_count mysqli_field_seek mysqli_field_tell mysqli_free_result mysqli_get_charset mysqli_get_client_info mysqli_get_client_stats mysqli_get_client_version mysqli_get_connection_stats mysqli_get_host_info mysqli_get_proto_info mysqli_get_server_info mysqli_get_server_version mysqli_info mysqli_init mysqli_insert_id mysqli_kill mysqli_more_results mysqli_multi_query mysqli_next_result mysqli_num_fields mysqli_num_rows mysqli_options mysqli_ping mysqli_prepare mysqli_query mysqli_real_connect mysqli_real_escape_string mysqli_real_query mysqli_reap_async_query mysqli_refresh mysqli_rollback mysqli_select_db mysqli_set_charset mysqli_set_local_infile_default mysqli_set_local_infile_handler mysqli_sqlstate mysqli_ssl_set mysqli_stat mysqli_stmt_init mysqli_store_result mysqli_thread_id mysqli_thread_safe mysqli_use_result mysqli_warning_count";
	      CodeMirror.registerHelper("hintWords", "php", [phpKeywords, phpAtoms, phpBuiltin].join(" ").split(" "));
	      CodeMirror.registerHelper("wordChars", "php", /[\w$]/);
	      var phpConfig = {
	        name: "clike",
	        helperType: "php",
	        keywords: keywords(phpKeywords),
	        blockKeywords: keywords("catch do else elseif for foreach if switch try while finally"),
	        defKeywords: keywords("class enum function interface namespace trait"),
	        atoms: keywords(phpAtoms),
	        builtin: keywords(phpBuiltin),
	        multiLineStrings: true,
	        hooks: {
	          "$": function (stream) {
	            stream.eatWhile(/[\w\$_]/);
	            return "variable-2";
	          },
	          "<": function (stream, state) {
	            var before;
	            if (before = stream.match(/^<<\s*/)) {
	              var quoted = stream.eat(/['"]/);
	              stream.eatWhile(/[\w\.]/);
	              var delim = stream.current().slice(before[0].length + (quoted ? 2 : 1));
	              if (quoted) stream.eat(quoted);
	              if (delim) {
	                (state.tokStack || (state.tokStack = [])).push(delim, 0);
	                state.tokenize = phpString(delim, quoted != "'");
	                return "string";
	              }
	            }
	            return false;
	          },
	          "#": function (stream) {
	            while (!stream.eol() && !stream.match("?>", false)) stream.next();
	            return "comment";
	          },
	          "/": function (stream) {
	            if (stream.eat("/")) {
	              while (!stream.eol() && !stream.match("?>", false)) stream.next();
	              return "comment";
	            }
	            return false;
	          },
	          '"': function (_stream, state) {
	            (state.tokStack || (state.tokStack = [])).push('"', 0);
	            state.tokenize = phpString('"');
	            return "string";
	          },
	          "{": function (_stream, state) {
	            if (state.tokStack && state.tokStack.length) state.tokStack[state.tokStack.length - 1]++;
	            return false;
	          },
	          "}": function (_stream, state) {
	            if (state.tokStack && state.tokStack.length > 0 && ! --state.tokStack[state.tokStack.length - 1]) {
	              state.tokenize = phpString(state.tokStack[state.tokStack.length - 2]);
	            }
	            return false;
	          }
	        }
	      };
	      CodeMirror.defineMode("php", function (config, parserConfig) {
	        var htmlMode = CodeMirror.getMode(config, parserConfig && parserConfig.htmlMode || "text/html");
	        var phpMode = CodeMirror.getMode(config, phpConfig);
	        function dispatch(stream, state) {
	          var isPHP = state.curMode == phpMode;
	          if (stream.sol() && state.pending && state.pending != '"' && state.pending != "'") state.pending = null;
	          if (!isPHP) {
	            if (stream.match(/^<\?\w*/)) {
	              state.curMode = phpMode;
	              if (!state.php) state.php = CodeMirror.startState(phpMode, htmlMode.indent(state.html, "", ""));
	              state.curState = state.php;
	              return "meta";
	            }
	            if (state.pending == '"' || state.pending == "'") {
	              while (!stream.eol() && stream.next() != state.pending) {}
	              var style = "string";
	            } else if (state.pending && stream.pos < state.pending.end) {
	              stream.pos = state.pending.end;
	              var style = state.pending.style;
	            } else {
	              var style = htmlMode.token(stream, state.curState);
	            }
	            if (state.pending) state.pending = null;
	            var cur = stream.current(),
	              openPHP = cur.search(/<\?/),
	              m;
	            if (openPHP != -1) {
	              if (style == "string" && (m = cur.match(/[\'\"]$/)) && !/\?>/.test(cur)) state.pending = m[0];else state.pending = {
	                end: stream.pos,
	                style: style
	              };
	              stream.backUp(cur.length - openPHP);
	            }
	            return style;
	          } else if (isPHP && state.php.tokenize == null && stream.match("?>")) {
	            state.curMode = htmlMode;
	            state.curState = state.html;
	            if (!state.php.context.prev) state.php = null;
	            return "meta";
	          } else {
	            return phpMode.token(stream, state.curState);
	          }
	        }
	        return {
	          startState: function () {
	            var html = CodeMirror.startState(htmlMode);
	            var php = parserConfig.startOpen ? CodeMirror.startState(phpMode) : null;
	            return {
	              html: html,
	              php: php,
	              curMode: parserConfig.startOpen ? phpMode : htmlMode,
	              curState: parserConfig.startOpen ? php : html,
	              pending: null
	            };
	          },
	          copyState: function (state) {
	            var html = state.html,
	              htmlNew = CodeMirror.copyState(htmlMode, html),
	              php = state.php,
	              phpNew = php && CodeMirror.copyState(phpMode, php),
	              cur;
	            if (state.curMode == htmlMode) cur = htmlNew;else cur = phpNew;
	            return {
	              html: htmlNew,
	              php: phpNew,
	              curMode: state.curMode,
	              curState: cur,
	              pending: state.pending
	            };
	          },
	          token: dispatch,
	          indent: function (state, textAfter, line) {
	            if (state.curMode != phpMode && /^\s*<\//.test(textAfter) || state.curMode == phpMode && /^\?>/.test(textAfter)) return htmlMode.indent(state.html, textAfter, line);
	            return state.curMode.indent(state.curState, textAfter, line);
	          },
	          blockCommentStart: "/*",
	          blockCommentEnd: "*/",
	          lineComment: "//",
	          innerMode: function (state) {
	            return {
	              state: state.curState,
	              mode: state.curMode
	            };
	          }
	        };
	      }, "htmlmixed", "clike");
	      CodeMirror.defineMIME("application/x-httpd-php", "php");
	      CodeMirror.defineMIME("application/x-httpd-php-open", {
	        name: "php",
	        startOpen: true
	      });
	      CodeMirror.defineMIME("text/x-php", phpConfig);
	    });
	  })();
	  return php.exports;
	}

	requirePhp();

	var python = {exports: {}};

	var hasRequiredPython;
	function requirePython() {
	  if (hasRequiredPython) return python.exports;
	  hasRequiredPython = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      function wordRegexp(words) {
	        return new RegExp("^((" + words.join(")|(") + "))\\b");
	      }
	      var wordOperators = wordRegexp(["and", "or", "not", "is"]);
	      var commonKeywords = ["as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "lambda", "pass", "raise", "return", "try", "while", "with", "yield", "in", "False", "True"];
	      var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr", "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod", "enumerate", "eval", "filter", "float", "format", "frozenset", "getattr", "globals", "hasattr", "hash", "help", "hex", "id", "input", "int", "isinstance", "issubclass", "iter", "len", "list", "locals", "map", "max", "memoryview", "min", "next", "object", "oct", "open", "ord", "pow", "property", "range", "repr", "reversed", "round", "set", "setattr", "slice", "sorted", "staticmethod", "str", "sum", "super", "tuple", "type", "vars", "zip", "__import__", "NotImplemented", "Ellipsis", "__debug__"];
	      CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins).concat(["exec", "print"]));
	      function top(state) {
	        return state.scopes[state.scopes.length - 1];
	      }
	      CodeMirror.defineMode("python", function (conf, parserConf) {
	        var ERRORCLASS = "error";
	        var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.\\]/;
	        //               (Backwards-compatibility with old, cumbersome config system)
	        var operators = [parserConf.singleOperators, parserConf.doubleOperators, parserConf.doubleDelimiters, parserConf.tripleDelimiters, parserConf.operators || /^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@]|\.\.\.)/];
	        for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1);
	        var hangingIndent = parserConf.hangingIndent || conf.indentUnit;
	        var myKeywords = commonKeywords,
	          myBuiltins = commonBuiltins;
	        if (parserConf.extra_keywords != undefined) myKeywords = myKeywords.concat(parserConf.extra_keywords);
	        if (parserConf.extra_builtins != undefined) myBuiltins = myBuiltins.concat(parserConf.extra_builtins);
	        var py3 = !(parserConf.version && Number(parserConf.version) < 3);
	        if (py3) {
	          // since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator
	          var identifiers = parserConf.identifiers || /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;
	          myKeywords = myKeywords.concat(["nonlocal", "None", "aiter", "anext", "async", "await", "breakpoint", "match", "case"]);
	          myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]);
	          var stringPrefixes = new RegExp("^(([rbuf]|(br)|(rb)|(fr)|(rf))?('{3}|\"{3}|['\"]))", "i");
	        } else {
	          var identifiers = parserConf.identifiers || /^[_A-Za-z][_A-Za-z0-9]*/;
	          myKeywords = myKeywords.concat(["exec", "print"]);
	          myBuiltins = myBuiltins.concat(["apply", "basestring", "buffer", "cmp", "coerce", "execfile", "file", "intern", "long", "raw_input", "reduce", "reload", "unichr", "unicode", "xrange", "None"]);
	          var stringPrefixes = new RegExp("^(([rubf]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
	        }
	        var keywords = wordRegexp(myKeywords);
	        var builtins = wordRegexp(myBuiltins);

	        // tokenizers
	        function tokenBase(stream, state) {
	          var sol = stream.sol() && state.lastToken != "\\";
	          if (sol) state.indent = stream.indentation();
	          // Handle scope changes
	          if (sol && top(state).type == "py") {
	            var scopeOffset = top(state).offset;
	            if (stream.eatSpace()) {
	              var lineOffset = stream.indentation();
	              if (lineOffset > scopeOffset) pushPyScope(state);else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != "#") state.errorToken = true;
	              return null;
	            } else {
	              var style = tokenBaseInner(stream, state);
	              if (scopeOffset > 0 && dedent(stream, state)) style += " " + ERRORCLASS;
	              return style;
	            }
	          }
	          return tokenBaseInner(stream, state);
	        }
	        function tokenBaseInner(stream, state, inFormat) {
	          if (stream.eatSpace()) return null;

	          // Handle Comments
	          if (!inFormat && stream.match(/^#.*/)) return "comment";

	          // Handle Number Literals
	          if (stream.match(/^[0-9\.]/, false)) {
	            var floatLiteral = false;
	            // Floats
	            if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) {
	              floatLiteral = true;
	            }
	            if (stream.match(/^[\d_]+\.\d*/)) {
	              floatLiteral = true;
	            }
	            if (stream.match(/^\.\d+/)) {
	              floatLiteral = true;
	            }
	            if (floatLiteral) {
	              // Float literals may be "imaginary"
	              stream.eat(/J/i);
	              return "number";
	            }
	            // Integers
	            var intLiteral = false;
	            // Hex
	            if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true;
	            // Binary
	            if (stream.match(/^0b[01_]+/i)) intLiteral = true;
	            // Octal
	            if (stream.match(/^0o[0-7_]+/i)) intLiteral = true;
	            // Decimal
	            if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) {
	              // Decimal literals may be "imaginary"
	              stream.eat(/J/i);
	              // TODO - Can you have imaginary longs?
	              intLiteral = true;
	            }
	            // Zero by itself with no other piece of number.
	            if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
	            if (intLiteral) {
	              // Integer literals may be "long"
	              stream.eat(/L/i);
	              return "number";
	            }
	          }

	          // Handle Strings
	          if (stream.match(stringPrefixes)) {
	            var isFmtString = stream.current().toLowerCase().indexOf('f') !== -1;
	            if (!isFmtString) {
	              state.tokenize = tokenStringFactory(stream.current(), state.tokenize);
	              return state.tokenize(stream, state);
	            } else {
	              state.tokenize = formatStringFactory(stream.current(), state.tokenize);
	              return state.tokenize(stream, state);
	            }
	          }
	          for (var i = 0; i < operators.length; i++) if (stream.match(operators[i])) return "operator";
	          if (stream.match(delimiters)) return "punctuation";
	          if (state.lastToken == "." && stream.match(identifiers)) return "property";
	          if (stream.match(keywords) || stream.match(wordOperators)) return "keyword";
	          if (stream.match(builtins)) return "builtin";
	          if (stream.match(/^(self|cls)\b/)) return "variable-2";
	          if (stream.match(identifiers)) {
	            if (state.lastToken == "def" || state.lastToken == "class") return "def";
	            return "variable";
	          }

	          // Handle non-detected items
	          stream.next();
	          return inFormat ? null : ERRORCLASS;
	        }
	        function formatStringFactory(delimiter, tokenOuter) {
	          while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0) delimiter = delimiter.substr(1);
	          var singleline = delimiter.length == 1;
	          var OUTCLASS = "string";
	          function tokenNestedExpr(depth) {
	            return function (stream, state) {
	              var inner = tokenBaseInner(stream, state, true);
	              if (inner == "punctuation") {
	                if (stream.current() == "{") {
	                  state.tokenize = tokenNestedExpr(depth + 1);
	                } else if (stream.current() == "}") {
	                  if (depth > 1) state.tokenize = tokenNestedExpr(depth - 1);else state.tokenize = tokenString;
	                }
	              }
	              return inner;
	            };
	          }
	          function tokenString(stream, state) {
	            while (!stream.eol()) {
	              stream.eatWhile(/[^'"\{\}\\]/);
	              if (stream.eat("\\")) {
	                stream.next();
	                if (singleline && stream.eol()) return OUTCLASS;
	              } else if (stream.match(delimiter)) {
	                state.tokenize = tokenOuter;
	                return OUTCLASS;
	              } else if (stream.match('{{')) {
	                // ignore {{ in f-str
	                return OUTCLASS;
	              } else if (stream.match('{', false)) {
	                // switch to nested mode
	                state.tokenize = tokenNestedExpr(0);
	                if (stream.current()) return OUTCLASS;else return state.tokenize(stream, state);
	              } else if (stream.match('}}')) {
	                return OUTCLASS;
	              } else if (stream.match('}')) {
	                // single } in f-string is an error
	                return ERRORCLASS;
	              } else {
	                stream.eat(/['"]/);
	              }
	            }
	            if (singleline) {
	              if (parserConf.singleLineStringErrors) return ERRORCLASS;else state.tokenize = tokenOuter;
	            }
	            return OUTCLASS;
	          }
	          tokenString.isString = true;
	          return tokenString;
	        }
	        function tokenStringFactory(delimiter, tokenOuter) {
	          while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0) delimiter = delimiter.substr(1);
	          var singleline = delimiter.length == 1;
	          var OUTCLASS = "string";
	          function tokenString(stream, state) {
	            while (!stream.eol()) {
	              stream.eatWhile(/[^'"\\]/);
	              if (stream.eat("\\")) {
	                stream.next();
	                if (singleline && stream.eol()) return OUTCLASS;
	              } else if (stream.match(delimiter)) {
	                state.tokenize = tokenOuter;
	                return OUTCLASS;
	              } else {
	                stream.eat(/['"]/);
	              }
	            }
	            if (singleline) {
	              if (parserConf.singleLineStringErrors) return ERRORCLASS;else state.tokenize = tokenOuter;
	            }
	            return OUTCLASS;
	          }
	          tokenString.isString = true;
	          return tokenString;
	        }
	        function pushPyScope(state) {
	          while (top(state).type != "py") state.scopes.pop();
	          state.scopes.push({
	            offset: top(state).offset + conf.indentUnit,
	            type: "py",
	            align: null
	          });
	        }
	        function pushBracketScope(stream, state, type) {
	          var align = stream.match(/^[\s\[\{\(]*(?:#|$)/, false) ? null : stream.column() + 1;
	          state.scopes.push({
	            offset: state.indent + hangingIndent,
	            type: type,
	            align: align
	          });
	        }
	        function dedent(stream, state) {
	          var indented = stream.indentation();
	          while (state.scopes.length > 1 && top(state).offset > indented) {
	            if (top(state).type != "py") return true;
	            state.scopes.pop();
	          }
	          return top(state).offset != indented;
	        }
	        function tokenLexer(stream, state) {
	          if (stream.sol()) {
	            state.beginningOfLine = true;
	            state.dedent = false;
	          }
	          var style = state.tokenize(stream, state);
	          var current = stream.current();

	          // Handle decorators
	          if (state.beginningOfLine && current == "@") return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS;
	          if (/\S/.test(current)) state.beginningOfLine = false;
	          if ((style == "variable" || style == "builtin") && state.lastToken == "meta") style = "meta";

	          // Handle scope changes.
	          if (current == "pass" || current == "return") state.dedent = true;
	          if (current == "lambda") state.lambda = true;
	          if (current == ":" && !state.lambda && top(state).type == "py" && stream.match(/^\s*(?:#|$)/, false)) pushPyScope(state);
	          if (current.length == 1 && !/string|comment/.test(style)) {
	            var delimiter_index = "[({".indexOf(current);
	            if (delimiter_index != -1) pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index + 1));
	            delimiter_index = "])}".indexOf(current);
	            if (delimiter_index != -1) {
	              if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent;else return ERRORCLASS;
	            }
	          }
	          if (state.dedent && stream.eol() && top(state).type == "py" && state.scopes.length > 1) state.scopes.pop();
	          return style;
	        }
	        var external = {
	          startState: function (basecolumn) {
	            return {
	              tokenize: tokenBase,
	              scopes: [{
	                offset: basecolumn || 0,
	                type: "py",
	                align: null
	              }],
	              indent: basecolumn || 0,
	              lastToken: null,
	              lambda: false,
	              dedent: 0
	            };
	          },
	          token: function (stream, state) {
	            var addErr = state.errorToken;
	            if (addErr) state.errorToken = false;
	            var style = tokenLexer(stream, state);
	            if (style && style != "comment") state.lastToken = style == "keyword" || style == "punctuation" ? stream.current() : style;
	            if (style == "punctuation") style = null;
	            if (stream.eol() && state.lambda) state.lambda = false;
	            return addErr ? style + " " + ERRORCLASS : style;
	          },
	          indent: function (state, textAfter) {
	            if (state.tokenize != tokenBase) return state.tokenize.isString ? CodeMirror.Pass : 0;
	            var scope = top(state);
	            var closing = scope.type == textAfter.charAt(0) || scope.type == "py" && !state.dedent && /^(else:|elif |except |finally:)/.test(textAfter);
	            if (scope.align != null) return scope.align - (closing ? 1 : 0);else return scope.offset - (closing ? hangingIndent : 0);
	          },
	          electricInput: /^\s*([\}\]\)]|else:|elif |except |finally:)$/,
	          closeBrackets: {
	            triples: "'\""
	          },
	          lineComment: "#",
	          fold: "indent"
	        };
	        return external;
	      });
	      CodeMirror.defineMIME("text/x-python", "python");
	      var words = function (str) {
	        return str.split(" ");
	      };
	      CodeMirror.defineMIME("text/x-cython", {
	        name: "python",
	        extra_keywords: words("by cdef cimport cpdef ctypedef enum except " + "extern gil include nogil property public " + "readonly struct union DEF IF ELIF ELSE")
	      });
	    });
	  })();
	  return python.exports;
	}

	requirePython();

	var rst = {exports: {}};

	var stex = {exports: {}};

	var hasRequiredStex;
	function requireStex() {
	  if (hasRequiredStex) return stex.exports;
	  hasRequiredStex = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    /*
	     * Author: Constantin Jucovschi (c.jucovschi@jacobs-university.de)
	     * Licence: MIT
	     */

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      CodeMirror.defineMode("stex", function (_config, parserConfig) {

	        function pushCommand(state, command) {
	          state.cmdState.push(command);
	        }
	        function peekCommand(state) {
	          if (state.cmdState.length > 0) {
	            return state.cmdState[state.cmdState.length - 1];
	          } else {
	            return null;
	          }
	        }
	        function popCommand(state) {
	          var plug = state.cmdState.pop();
	          if (plug) {
	            plug.closeBracket();
	          }
	        }

	        // returns the non-default plugin closest to the end of the list
	        function getMostPowerful(state) {
	          var context = state.cmdState;
	          for (var i = context.length - 1; i >= 0; i--) {
	            var plug = context[i];
	            if (plug.name == "DEFAULT") {
	              continue;
	            }
	            return plug;
	          }
	          return {
	            styleIdentifier: function () {
	              return null;
	            }
	          };
	        }
	        function addPluginPattern(pluginName, cmdStyle, styles) {
	          return function () {
	            this.name = pluginName;
	            this.bracketNo = 0;
	            this.style = cmdStyle;
	            this.styles = styles;
	            this.argument = null; // \begin and \end have arguments that follow. These are stored in the plugin

	            this.styleIdentifier = function () {
	              return this.styles[this.bracketNo - 1] || null;
	            };
	            this.openBracket = function () {
	              this.bracketNo++;
	              return "bracket";
	            };
	            this.closeBracket = function () {};
	          };
	        }
	        var plugins = {};
	        plugins["importmodule"] = addPluginPattern("importmodule", "tag", ["string", "builtin"]);
	        plugins["documentclass"] = addPluginPattern("documentclass", "tag", ["", "atom"]);
	        plugins["usepackage"] = addPluginPattern("usepackage", "tag", ["atom"]);
	        plugins["begin"] = addPluginPattern("begin", "tag", ["atom"]);
	        plugins["end"] = addPluginPattern("end", "tag", ["atom"]);
	        plugins["label"] = addPluginPattern("label", "tag", ["atom"]);
	        plugins["ref"] = addPluginPattern("ref", "tag", ["atom"]);
	        plugins["eqref"] = addPluginPattern("eqref", "tag", ["atom"]);
	        plugins["cite"] = addPluginPattern("cite", "tag", ["atom"]);
	        plugins["bibitem"] = addPluginPattern("bibitem", "tag", ["atom"]);
	        plugins["Bibitem"] = addPluginPattern("Bibitem", "tag", ["atom"]);
	        plugins["RBibitem"] = addPluginPattern("RBibitem", "tag", ["atom"]);
	        plugins["DEFAULT"] = function () {
	          this.name = "DEFAULT";
	          this.style = "tag";
	          this.styleIdentifier = this.openBracket = this.closeBracket = function () {};
	        };
	        function setState(state, f) {
	          state.f = f;
	        }

	        // called when in a normal (no environment) context
	        function normal(source, state) {
	          var plug;
	          // Do we look like '\command' ?  If so, attempt to apply the plugin 'command'
	          if (source.match(/^\\[a-zA-Z@]+/)) {
	            var cmdName = source.current().slice(1);
	            plug = plugins.hasOwnProperty(cmdName) ? plugins[cmdName] : plugins["DEFAULT"];
	            plug = new plug();
	            pushCommand(state, plug);
	            setState(state, beginParams);
	            return plug.style;
	          }

	          // escape characters
	          if (source.match(/^\\[$&%#{}_]/)) {
	            return "tag";
	          }

	          // white space control characters
	          if (source.match(/^\\[,;!\/\\]/)) {
	            return "tag";
	          }

	          // find if we're starting various math modes
	          if (source.match("\\[")) {
	            setState(state, function (source, state) {
	              return inMathMode(source, state, "\\]");
	            });
	            return "keyword";
	          }
	          if (source.match("\\(")) {
	            setState(state, function (source, state) {
	              return inMathMode(source, state, "\\)");
	            });
	            return "keyword";
	          }
	          if (source.match("$$")) {
	            setState(state, function (source, state) {
	              return inMathMode(source, state, "$$");
	            });
	            return "keyword";
	          }
	          if (source.match("$")) {
	            setState(state, function (source, state) {
	              return inMathMode(source, state, "$");
	            });
	            return "keyword";
	          }
	          var ch = source.next();
	          if (ch == "%") {
	            source.skipToEnd();
	            return "comment";
	          } else if (ch == '}' || ch == ']') {
	            plug = peekCommand(state);
	            if (plug) {
	              plug.closeBracket(ch);
	              setState(state, beginParams);
	            } else {
	              return "error";
	            }
	            return "bracket";
	          } else if (ch == '{' || ch == '[') {
	            plug = plugins["DEFAULT"];
	            plug = new plug();
	            pushCommand(state, plug);
	            return "bracket";
	          } else if (/\d/.test(ch)) {
	            source.eatWhile(/[\w.%]/);
	            return "atom";
	          } else {
	            source.eatWhile(/[\w\-_]/);
	            plug = getMostPowerful(state);
	            if (plug.name == 'begin') {
	              plug.argument = source.current();
	            }
	            return plug.styleIdentifier();
	          }
	        }
	        function inMathMode(source, state, endModeSeq) {
	          if (source.eatSpace()) {
	            return null;
	          }
	          if (endModeSeq && source.match(endModeSeq)) {
	            setState(state, normal);
	            return "keyword";
	          }
	          if (source.match(/^\\[a-zA-Z@]+/)) {
	            return "tag";
	          }
	          if (source.match(/^[a-zA-Z]+/)) {
	            return "variable-2";
	          }
	          // escape characters
	          if (source.match(/^\\[$&%#{}_]/)) {
	            return "tag";
	          }
	          // white space control characters
	          if (source.match(/^\\[,;!\/]/)) {
	            return "tag";
	          }
	          // special math-mode characters
	          if (source.match(/^[\^_&]/)) {
	            return "tag";
	          }
	          // non-special characters
	          if (source.match(/^[+\-<>|=,\/@!*:;'"`~#?]/)) {
	            return null;
	          }
	          if (source.match(/^(\d+\.\d*|\d*\.\d+|\d+)/)) {
	            return "number";
	          }
	          var ch = source.next();
	          if (ch == "{" || ch == "}" || ch == "[" || ch == "]" || ch == "(" || ch == ")") {
	            return "bracket";
	          }
	          if (ch == "%") {
	            source.skipToEnd();
	            return "comment";
	          }
	          return "error";
	        }
	        function beginParams(source, state) {
	          var ch = source.peek(),
	            lastPlug;
	          if (ch == '{' || ch == '[') {
	            lastPlug = peekCommand(state);
	            lastPlug.openBracket(ch);
	            source.eat(ch);
	            setState(state, normal);
	            return "bracket";
	          }
	          if (/[ \t\r]/.test(ch)) {
	            source.eat(ch);
	            return null;
	          }
	          setState(state, normal);
	          popCommand(state);
	          return normal(source, state);
	        }
	        return {
	          startState: function () {
	            var f = parserConfig.inMathMode ? function (source, state) {
	              return inMathMode(source, state);
	            } : normal;
	            return {
	              cmdState: [],
	              f: f
	            };
	          },
	          copyState: function (s) {
	            return {
	              cmdState: s.cmdState.slice(),
	              f: s.f
	            };
	          },
	          token: function (stream, state) {
	            return state.f(stream, state);
	          },
	          blankLine: function (state) {
	            state.f = normal;
	            state.cmdState.length = 0;
	          },
	          lineComment: "%"
	        };
	      });
	      CodeMirror.defineMIME("text/x-stex", "stex");
	      CodeMirror.defineMIME("text/x-latex", "stex");
	    });
	  })();
	  return stex.exports;
	}

	var hasRequiredRst;
	function requireRst() {
	  if (hasRequiredRst) return rst.exports;
	  hasRequiredRst = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror(), requirePython(), requireStex(), requireOverlay());
	    })(function (CodeMirror) {

	      CodeMirror.defineMode('rst', function (config, options) {
	        var rx_strong = /^\*\*[^\*\s](?:[^\*]*[^\*\s])?\*\*/;
	        var rx_emphasis = /^\*[^\*\s](?:[^\*]*[^\*\s])?\*/;
	        var rx_literal = /^``[^`\s](?:[^`]*[^`\s])``/;
	        var rx_number = /^(?:[\d]+(?:[\.,]\d+)*)/;
	        var rx_positive = /^(?:\s\+[\d]+(?:[\.,]\d+)*)/;
	        var rx_negative = /^(?:\s\-[\d]+(?:[\.,]\d+)*)/;
	        var rx_uri_protocol = "[Hh][Tt][Tt][Pp][Ss]?://";
	        var rx_uri_domain = "(?:[\\d\\w.-]+)\\.(?:\\w{2,6})";
	        var rx_uri_path = "(?:/[\\d\\w\\#\\%\\&\\-\\.\\,\\/\\:\\=\\?\\~]+)*";
	        var rx_uri = new RegExp("^" + rx_uri_protocol + rx_uri_domain + rx_uri_path);
	        var overlay = {
	          token: function (stream) {
	            if (stream.match(rx_strong) && stream.match(/\W+|$/, false)) return 'strong';
	            if (stream.match(rx_emphasis) && stream.match(/\W+|$/, false)) return 'em';
	            if (stream.match(rx_literal) && stream.match(/\W+|$/, false)) return 'string-2';
	            if (stream.match(rx_number)) return 'number';
	            if (stream.match(rx_positive)) return 'positive';
	            if (stream.match(rx_negative)) return 'negative';
	            if (stream.match(rx_uri)) return 'link';
	            while (stream.next() != null) {
	              if (stream.match(rx_strong, false)) break;
	              if (stream.match(rx_emphasis, false)) break;
	              if (stream.match(rx_literal, false)) break;
	              if (stream.match(rx_number, false)) break;
	              if (stream.match(rx_positive, false)) break;
	              if (stream.match(rx_negative, false)) break;
	              if (stream.match(rx_uri, false)) break;
	            }
	            return null;
	          }
	        };
	        var mode = CodeMirror.getMode(config, options.backdrop || 'rst-base');
	        return CodeMirror.overlayMode(mode, overlay, true); // combine
	      }, 'python', 'stex');

	      ///////////////////////////////////////////////////////////////////////////////
	      ///////////////////////////////////////////////////////////////////////////////

	      CodeMirror.defineMode('rst-base', function (config) {
	        ///////////////////////////////////////////////////////////////////////////
	        ///////////////////////////////////////////////////////////////////////////

	        function format(string) {
	          var args = Array.prototype.slice.call(arguments, 1);
	          return string.replace(/{(\d+)}/g, function (match, n) {
	            return typeof args[n] != 'undefined' ? args[n] : match;
	          });
	        }

	        ///////////////////////////////////////////////////////////////////////////
	        ///////////////////////////////////////////////////////////////////////////

	        var mode_python = CodeMirror.getMode(config, 'python');
	        var mode_stex = CodeMirror.getMode(config, 'stex');

	        ///////////////////////////////////////////////////////////////////////////
	        ///////////////////////////////////////////////////////////////////////////

	        var SEPA = "\\s+";
	        var TAIL = "(?:\\s*|\\W|$)",
	          rx_TAIL = new RegExp(format('^{0}', TAIL));
	        var NAME = "(?:[^\\W\\d_](?:[\\w!\"#$%&'()\\*\\+,\\-\\.\/:;<=>\\?]*[^\\W_])?)",
	          rx_NAME = new RegExp(format('^{0}', NAME));
	        var NAME_WWS = "(?:[^\\W\\d_](?:[\\w\\s!\"#$%&'()\\*\\+,\\-\\.\/:;<=>\\?]*[^\\W_])?)";
	        var REF_NAME = format('(?:{0}|`{1}`)', NAME, NAME_WWS);
	        var TEXT1 = "(?:[^\\s\\|](?:[^\\|]*[^\\s\\|])?)";
	        var TEXT2 = "(?:[^\\`]+)",
	          rx_TEXT2 = new RegExp(format('^{0}', TEXT2));
	        var rx_section = new RegExp("^([!'#$%&\"()*+,-./:;<=>?@\\[\\\\\\]^_`{|}~])\\1{3,}\\s*$");
	        var rx_explicit = new RegExp(format('^\\.\\.{0}', SEPA));
	        var rx_link = new RegExp(format('^_{0}:{1}|^__:{1}', REF_NAME, TAIL));
	        var rx_directive = new RegExp(format('^{0}::{1}', REF_NAME, TAIL));
	        var rx_substitution = new RegExp(format('^\\|{0}\\|{1}{2}::{3}', TEXT1, SEPA, REF_NAME, TAIL));
	        var rx_footnote = new RegExp(format('^\\[(?:\\d+|#{0}?|\\*)]{1}', REF_NAME, TAIL));
	        var rx_citation = new RegExp(format('^\\[{0}\\]{1}', REF_NAME, TAIL));
	        var rx_substitution_ref = new RegExp(format('^\\|{0}\\|', TEXT1));
	        var rx_footnote_ref = new RegExp(format('^\\[(?:\\d+|#{0}?|\\*)]_', REF_NAME));
	        var rx_citation_ref = new RegExp(format('^\\[{0}\\]_', REF_NAME));
	        var rx_link_ref1 = new RegExp(format('^{0}__?', REF_NAME));
	        var rx_link_ref2 = new RegExp(format('^`{0}`_', TEXT2));
	        var rx_role_pre = new RegExp(format('^:{0}:`{1}`{2}', NAME, TEXT2, TAIL));
	        var rx_role_suf = new RegExp(format('^`{1}`:{0}:{2}', NAME, TEXT2, TAIL));
	        var rx_role = new RegExp(format('^:{0}:{1}', NAME, TAIL));
	        var rx_directive_name = new RegExp(format('^{0}', REF_NAME));
	        var rx_directive_tail = new RegExp(format('^::{0}', TAIL));
	        var rx_substitution_text = new RegExp(format('^\\|{0}\\|', TEXT1));
	        var rx_substitution_sepa = new RegExp(format('^{0}', SEPA));
	        var rx_substitution_name = new RegExp(format('^{0}', REF_NAME));
	        var rx_substitution_tail = new RegExp(format('^::{0}', TAIL));
	        var rx_link_head = new RegExp("^_");
	        var rx_link_name = new RegExp(format('^{0}|_', REF_NAME));
	        var rx_link_tail = new RegExp(format('^:{0}', TAIL));
	        var rx_verbatim = new RegExp('^::\\s*$');
	        var rx_examples = new RegExp('^\\s+(?:>>>|In \\[\\d+\\]:)\\s');

	        ///////////////////////////////////////////////////////////////////////////
	        ///////////////////////////////////////////////////////////////////////////

	        function to_normal(stream, state) {
	          var token = null;
	          if (stream.sol() && stream.match(rx_examples, false)) {
	            change(state, to_mode, {
	              mode: mode_python,
	              local: CodeMirror.startState(mode_python)
	            });
	          } else if (stream.sol() && stream.match(rx_explicit)) {
	            change(state, to_explicit);
	            token = 'meta';
	          } else if (stream.sol() && stream.match(rx_section)) {
	            change(state, to_normal);
	            token = 'header';
	          } else if (phase(state) == rx_role_pre || stream.match(rx_role_pre, false)) {
	            switch (stage(state)) {
	              case 0:
	                change(state, to_normal, context(rx_role_pre, 1));
	                stream.match(/^:/);
	                token = 'meta';
	                break;
	              case 1:
	                change(state, to_normal, context(rx_role_pre, 2));
	                stream.match(rx_NAME);
	                token = 'keyword';
	                if (stream.current().match(/^(?:math|latex)/)) {
	                  state.tmp_stex = true;
	                }
	                break;
	              case 2:
	                change(state, to_normal, context(rx_role_pre, 3));
	                stream.match(/^:`/);
	                token = 'meta';
	                break;
	              case 3:
	                if (state.tmp_stex) {
	                  state.tmp_stex = undefined;
	                  state.tmp = {
	                    mode: mode_stex,
	                    local: CodeMirror.startState(mode_stex)
	                  };
	                }
	                if (state.tmp) {
	                  if (stream.peek() == '`') {
	                    change(state, to_normal, context(rx_role_pre, 4));
	                    state.tmp = undefined;
	                    break;
	                  }
	                  token = state.tmp.mode.token(stream, state.tmp.local);
	                  break;
	                }
	                change(state, to_normal, context(rx_role_pre, 4));
	                stream.match(rx_TEXT2);
	                token = 'string';
	                break;
	              case 4:
	                change(state, to_normal, context(rx_role_pre, 5));
	                stream.match(/^`/);
	                token = 'meta';
	                break;
	              case 5:
	                change(state, to_normal, context(rx_role_pre, 6));
	                stream.match(rx_TAIL);
	                break;
	              default:
	                change(state, to_normal);
	            }
	          } else if (phase(state) == rx_role_suf || stream.match(rx_role_suf, false)) {
	            switch (stage(state)) {
	              case 0:
	                change(state, to_normal, context(rx_role_suf, 1));
	                stream.match(/^`/);
	                token = 'meta';
	                break;
	              case 1:
	                change(state, to_normal, context(rx_role_suf, 2));
	                stream.match(rx_TEXT2);
	                token = 'string';
	                break;
	              case 2:
	                change(state, to_normal, context(rx_role_suf, 3));
	                stream.match(/^`:/);
	                token = 'meta';
	                break;
	              case 3:
	                change(state, to_normal, context(rx_role_suf, 4));
	                stream.match(rx_NAME);
	                token = 'keyword';
	                break;
	              case 4:
	                change(state, to_normal, context(rx_role_suf, 5));
	                stream.match(/^:/);
	                token = 'meta';
	                break;
	              case 5:
	                change(state, to_normal, context(rx_role_suf, 6));
	                stream.match(rx_TAIL);
	                break;
	              default:
	                change(state, to_normal);
	            }
	          } else if (phase(state) == rx_role || stream.match(rx_role, false)) {
	            switch (stage(state)) {
	              case 0:
	                change(state, to_normal, context(rx_role, 1));
	                stream.match(/^:/);
	                token = 'meta';
	                break;
	              case 1:
	                change(state, to_normal, context(rx_role, 2));
	                stream.match(rx_NAME);
	                token = 'keyword';
	                break;
	              case 2:
	                change(state, to_normal, context(rx_role, 3));
	                stream.match(/^:/);
	                token = 'meta';
	                break;
	              case 3:
	                change(state, to_normal, context(rx_role, 4));
	                stream.match(rx_TAIL);
	                break;
	              default:
	                change(state, to_normal);
	            }
	          } else if (phase(state) == rx_substitution_ref || stream.match(rx_substitution_ref, false)) {
	            switch (stage(state)) {
	              case 0:
	                change(state, to_normal, context(rx_substitution_ref, 1));
	                stream.match(rx_substitution_text);
	                token = 'variable-2';
	                break;
	              case 1:
	                change(state, to_normal, context(rx_substitution_ref, 2));
	                if (stream.match(/^_?_?/)) token = 'link';
	                break;
	              default:
	                change(state, to_normal);
	            }
	          } else if (stream.match(rx_footnote_ref)) {
	            change(state, to_normal);
	            token = 'quote';
	          } else if (stream.match(rx_citation_ref)) {
	            change(state, to_normal);
	            token = 'quote';
	          } else if (stream.match(rx_link_ref1)) {
	            change(state, to_normal);
	            if (!stream.peek() || stream.peek().match(/^\W$/)) {
	              token = 'link';
	            }
	          } else if (phase(state) == rx_link_ref2 || stream.match(rx_link_ref2, false)) {
	            switch (stage(state)) {
	              case 0:
	                if (!stream.peek() || stream.peek().match(/^\W$/)) {
	                  change(state, to_normal, context(rx_link_ref2, 1));
	                } else {
	                  stream.match(rx_link_ref2);
	                }
	                break;
	              case 1:
	                change(state, to_normal, context(rx_link_ref2, 2));
	                stream.match(/^`/);
	                token = 'link';
	                break;
	              case 2:
	                change(state, to_normal, context(rx_link_ref2, 3));
	                stream.match(rx_TEXT2);
	                break;
	              case 3:
	                change(state, to_normal, context(rx_link_ref2, 4));
	                stream.match(/^`_/);
	                token = 'link';
	                break;
	              default:
	                change(state, to_normal);
	            }
	          } else if (stream.match(rx_verbatim)) {
	            change(state, to_verbatim);
	          } else {
	            if (stream.next()) change(state, to_normal);
	          }
	          return token;
	        }

	        ///////////////////////////////////////////////////////////////////////////
	        ///////////////////////////////////////////////////////////////////////////

	        function to_explicit(stream, state) {
	          var token = null;
	          if (phase(state) == rx_substitution || stream.match(rx_substitution, false)) {
	            switch (stage(state)) {
	              case 0:
	                change(state, to_explicit, context(rx_substitution, 1));
	                stream.match(rx_substitution_text);
	                token = 'variable-2';
	                break;
	              case 1:
	                change(state, to_explicit, context(rx_substitution, 2));
	                stream.match(rx_substitution_sepa);
	                break;
	              case 2:
	                change(state, to_explicit, context(rx_substitution, 3));
	                stream.match(rx_substitution_name);
	                token = 'keyword';
	                break;
	              case 3:
	                change(state, to_explicit, context(rx_substitution, 4));
	                stream.match(rx_substitution_tail);
	                token = 'meta';
	                break;
	              default:
	                change(state, to_normal);
	            }
	          } else if (phase(state) == rx_directive || stream.match(rx_directive, false)) {
	            switch (stage(state)) {
	              case 0:
	                change(state, to_explicit, context(rx_directive, 1));
	                stream.match(rx_directive_name);
	                token = 'keyword';
	                if (stream.current().match(/^(?:math|latex)/)) state.tmp_stex = true;else if (stream.current().match(/^python/)) state.tmp_py = true;
	                break;
	              case 1:
	                change(state, to_explicit, context(rx_directive, 2));
	                stream.match(rx_directive_tail);
	                token = 'meta';
	                if (stream.match(/^latex\s*$/) || state.tmp_stex) {
	                  state.tmp_stex = undefined;
	                  change(state, to_mode, {
	                    mode: mode_stex,
	                    local: CodeMirror.startState(mode_stex)
	                  });
	                }
	                break;
	              case 2:
	                change(state, to_explicit, context(rx_directive, 3));
	                if (stream.match(/^python\s*$/) || state.tmp_py) {
	                  state.tmp_py = undefined;
	                  change(state, to_mode, {
	                    mode: mode_python,
	                    local: CodeMirror.startState(mode_python)
	                  });
	                }
	                break;
	              default:
	                change(state, to_normal);
	            }
	          } else if (phase(state) == rx_link || stream.match(rx_link, false)) {
	            switch (stage(state)) {
	              case 0:
	                change(state, to_explicit, context(rx_link, 1));
	                stream.match(rx_link_head);
	                stream.match(rx_link_name);
	                token = 'link';
	                break;
	              case 1:
	                change(state, to_explicit, context(rx_link, 2));
	                stream.match(rx_link_tail);
	                token = 'meta';
	                break;
	              default:
	                change(state, to_normal);
	            }
	          } else if (stream.match(rx_footnote)) {
	            change(state, to_normal);
	            token = 'quote';
	          } else if (stream.match(rx_citation)) {
	            change(state, to_normal);
	            token = 'quote';
	          } else {
	            stream.eatSpace();
	            if (stream.eol()) {
	              change(state, to_normal);
	            } else {
	              stream.skipToEnd();
	              change(state, to_comment);
	              token = 'comment';
	            }
	          }
	          return token;
	        }

	        ///////////////////////////////////////////////////////////////////////////
	        ///////////////////////////////////////////////////////////////////////////

	        function to_comment(stream, state) {
	          return as_block(stream, state, 'comment');
	        }
	        function to_verbatim(stream, state) {
	          return as_block(stream, state, 'meta');
	        }
	        function as_block(stream, state, token) {
	          if (stream.eol() || stream.eatSpace()) {
	            stream.skipToEnd();
	            return token;
	          } else {
	            change(state, to_normal);
	            return null;
	          }
	        }

	        ///////////////////////////////////////////////////////////////////////////
	        ///////////////////////////////////////////////////////////////////////////

	        function to_mode(stream, state) {
	          if (state.ctx.mode && state.ctx.local) {
	            if (stream.sol()) {
	              if (!stream.eatSpace()) change(state, to_normal);
	              return null;
	            }
	            return state.ctx.mode.token(stream, state.ctx.local);
	          }
	          change(state, to_normal);
	          return null;
	        }

	        ///////////////////////////////////////////////////////////////////////////
	        ///////////////////////////////////////////////////////////////////////////

	        function context(phase, stage, mode, local) {
	          return {
	            phase: phase,
	            stage: stage,
	            mode: mode,
	            local: local
	          };
	        }
	        function change(state, tok, ctx) {
	          state.tok = tok;
	          state.ctx = ctx || {};
	        }
	        function stage(state) {
	          return state.ctx.stage || 0;
	        }
	        function phase(state) {
	          return state.ctx.phase;
	        }

	        ///////////////////////////////////////////////////////////////////////////
	        ///////////////////////////////////////////////////////////////////////////

	        return {
	          startState: function () {
	            return {
	              tok: to_normal,
	              ctx: context(undefined, 0)
	            };
	          },
	          copyState: function (state) {
	            var ctx = state.ctx,
	              tmp = state.tmp;
	            if (ctx.local) ctx = {
	              mode: ctx.mode,
	              local: CodeMirror.copyState(ctx.mode, ctx.local)
	            };
	            if (tmp) tmp = {
	              mode: tmp.mode,
	              local: CodeMirror.copyState(tmp.mode, tmp.local)
	            };
	            return {
	              tok: state.tok,
	              ctx: ctx,
	              tmp: tmp
	            };
	          },
	          innerMode: function (state) {
	            return state.tmp ? {
	              state: state.tmp.local,
	              mode: state.tmp.mode
	            } : state.ctx.mode ? {
	              state: state.ctx.local,
	              mode: state.ctx.mode
	            } : null;
	          },
	          token: function (stream, state) {
	            return state.tok(stream, state);
	          }
	        };
	      }, 'python', 'stex');

	      ///////////////////////////////////////////////////////////////////////////////
	      ///////////////////////////////////////////////////////////////////////////////

	      CodeMirror.defineMIME('text/x-rst', 'rst');

	      ///////////////////////////////////////////////////////////////////////////////
	      ///////////////////////////////////////////////////////////////////////////////
	    });
	  })();
	  return rst.exports;
	}

	requireRst();

	var ruby = {exports: {}};

	var hasRequiredRuby;
	function requireRuby() {
	  if (hasRequiredRuby) return ruby.exports;
	  hasRequiredRuby = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      function wordObj(words) {
	        var o = {};
	        for (var i = 0, e = words.length; i < e; ++i) o[words[i]] = true;
	        return o;
	      }
	      var keywordList = ["alias", "and", "BEGIN", "begin", "break", "case", "class", "def", "defined?", "do", "else", "elsif", "END", "end", "ensure", "false", "for", "if", "in", "module", "next", "not", "or", "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless", "until", "when", "while", "yield", "nil", "raise", "throw", "catch", "fail", "loop", "callcc", "caller", "lambda", "proc", "public", "protected", "private", "require", "load", "require_relative", "extend", "autoload", "__END__", "__FILE__", "__LINE__", "__dir__"],
	        keywords = wordObj(keywordList);
	      var indentWords = wordObj(["def", "class", "case", "for", "while", "until", "module", "catch", "loop", "proc", "begin"]);
	      var dedentWords = wordObj(["end", "until"]);
	      var opening = {
	        "[": "]",
	        "{": "}",
	        "(": ")"
	      };
	      var closing = {
	        "]": "[",
	        "}": "{",
	        ")": "("
	      };
	      CodeMirror.defineMode("ruby", function (config) {
	        var curPunc;
	        function chain(newtok, stream, state) {
	          state.tokenize.push(newtok);
	          return newtok(stream, state);
	        }
	        function tokenBase(stream, state) {
	          if (stream.sol() && stream.match("=begin") && stream.eol()) {
	            state.tokenize.push(readBlockComment);
	            return "comment";
	          }
	          if (stream.eatSpace()) return null;
	          var ch = stream.next(),
	            m;
	          if (ch == "`" || ch == "'" || ch == '"') {
	            return chain(readQuoted(ch, "string", ch == '"' || ch == "`"), stream, state);
	          } else if (ch == "/") {
	            if (regexpAhead(stream)) return chain(readQuoted(ch, "string-2", true), stream, state);else return "operator";
	          } else if (ch == "%") {
	            var style = "string",
	              embed = true;
	            if (stream.eat("s")) style = "atom";else if (stream.eat(/[WQ]/)) style = "string";else if (stream.eat(/[r]/)) style = "string-2";else if (stream.eat(/[wxq]/)) {
	              style = "string";
	              embed = false;
	            }
	            var delim = stream.eat(/[^\w\s=]/);
	            if (!delim) return "operator";
	            if (opening.propertyIsEnumerable(delim)) delim = opening[delim];
	            return chain(readQuoted(delim, style, embed, true), stream, state);
	          } else if (ch == "#") {
	            stream.skipToEnd();
	            return "comment";
	          } else if (ch == "<" && (m = stream.match(/^<([-~])[\`\"\']?([a-zA-Z_?]\w*)[\`\"\']?(?:;|$)/))) {
	            return chain(readHereDoc(m[2], m[1]), stream, state);
	          } else if (ch == "0") {
	            if (stream.eat("x")) stream.eatWhile(/[\da-fA-F]/);else if (stream.eat("b")) stream.eatWhile(/[01]/);else stream.eatWhile(/[0-7]/);
	            return "number";
	          } else if (/\d/.test(ch)) {
	            stream.match(/^[\d_]*(?:\.[\d_]+)?(?:[eE][+\-]?[\d_]+)?/);
	            return "number";
	          } else if (ch == "?") {
	            while (stream.match(/^\\[CM]-/)) {}
	            if (stream.eat("\\")) stream.eatWhile(/\w/);else stream.next();
	            return "string";
	          } else if (ch == ":") {
	            if (stream.eat("'")) return chain(readQuoted("'", "atom", false), stream, state);
	            if (stream.eat('"')) return chain(readQuoted('"', "atom", true), stream, state);

	            // :> :>> :< :<< are valid symbols
	            if (stream.eat(/[\<\>]/)) {
	              stream.eat(/[\<\>]/);
	              return "atom";
	            }

	            // :+ :- :/ :* :| :& :! are valid symbols
	            if (stream.eat(/[\+\-\*\/\&\|\:\!]/)) {
	              return "atom";
	            }

	            // Symbols can't start by a digit
	            if (stream.eat(/[a-zA-Z$@_\xa1-\uffff]/)) {
	              stream.eatWhile(/[\w$\xa1-\uffff]/);
	              // Only one ? ! = is allowed and only as the last character
	              stream.eat(/[\?\!\=]/);
	              return "atom";
	            }
	            return "operator";
	          } else if (ch == "@" && stream.match(/^@?[a-zA-Z_\xa1-\uffff]/)) {
	            stream.eat("@");
	            stream.eatWhile(/[\w\xa1-\uffff]/);
	            return "variable-2";
	          } else if (ch == "$") {
	            if (stream.eat(/[a-zA-Z_]/)) {
	              stream.eatWhile(/[\w]/);
	            } else if (stream.eat(/\d/)) {
	              stream.eat(/\d/);
	            } else {
	              stream.next(); // Must be a special global like $: or $!
	            }
	            return "variable-3";
	          } else if (/[a-zA-Z_\xa1-\uffff]/.test(ch)) {
	            stream.eatWhile(/[\w\xa1-\uffff]/);
	            stream.eat(/[\?\!]/);
	            if (stream.eat(":")) return "atom";
	            return "ident";
	          } else if (ch == "|" && (state.varList || state.lastTok == "{" || state.lastTok == "do")) {
	            curPunc = "|";
	            return null;
	          } else if (/[\(\)\[\]{}\\;]/.test(ch)) {
	            curPunc = ch;
	            return null;
	          } else if (ch == "-" && stream.eat(">")) {
	            return "arrow";
	          } else if (/[=+\-\/*:\.^%<>~|]/.test(ch)) {
	            var more = stream.eatWhile(/[=+\-\/*:\.^%<>~|]/);
	            if (ch == "." && !more) curPunc = ".";
	            return "operator";
	          } else {
	            return null;
	          }
	        }
	        function regexpAhead(stream) {
	          var start = stream.pos,
	            depth = 0,
	            next,
	            found = false,
	            escaped = false;
	          while ((next = stream.next()) != null) {
	            if (!escaped) {
	              if ("[{(".indexOf(next) > -1) {
	                depth++;
	              } else if ("]})".indexOf(next) > -1) {
	                depth--;
	                if (depth < 0) break;
	              } else if (next == "/" && depth == 0) {
	                found = true;
	                break;
	              }
	              escaped = next == "\\";
	            } else {
	              escaped = false;
	            }
	          }
	          stream.backUp(stream.pos - start);
	          return found;
	        }
	        function tokenBaseUntilBrace(depth) {
	          if (!depth) depth = 1;
	          return function (stream, state) {
	            if (stream.peek() == "}") {
	              if (depth == 1) {
	                state.tokenize.pop();
	                return state.tokenize[state.tokenize.length - 1](stream, state);
	              } else {
	                state.tokenize[state.tokenize.length - 1] = tokenBaseUntilBrace(depth - 1);
	              }
	            } else if (stream.peek() == "{") {
	              state.tokenize[state.tokenize.length - 1] = tokenBaseUntilBrace(depth + 1);
	            }
	            return tokenBase(stream, state);
	          };
	        }
	        function tokenBaseOnce() {
	          var alreadyCalled = false;
	          return function (stream, state) {
	            if (alreadyCalled) {
	              state.tokenize.pop();
	              return state.tokenize[state.tokenize.length - 1](stream, state);
	            }
	            alreadyCalled = true;
	            return tokenBase(stream, state);
	          };
	        }
	        function readQuoted(quote, style, embed, unescaped) {
	          return function (stream, state) {
	            var escaped = false,
	              ch;
	            if (state.context.type === 'read-quoted-paused') {
	              state.context = state.context.prev;
	              stream.eat("}");
	            }
	            while ((ch = stream.next()) != null) {
	              if (ch == quote && (unescaped || !escaped)) {
	                state.tokenize.pop();
	                break;
	              }
	              if (embed && ch == "#" && !escaped) {
	                if (stream.eat("{")) {
	                  if (quote == "}") {
	                    state.context = {
	                      prev: state.context,
	                      type: 'read-quoted-paused'
	                    };
	                  }
	                  state.tokenize.push(tokenBaseUntilBrace());
	                  break;
	                } else if (/[@\$]/.test(stream.peek())) {
	                  state.tokenize.push(tokenBaseOnce());
	                  break;
	                }
	              }
	              escaped = !escaped && ch == "\\";
	            }
	            return style;
	          };
	        }
	        function readHereDoc(phrase, mayIndent) {
	          return function (stream, state) {
	            if (mayIndent) stream.eatSpace();
	            if (stream.match(phrase)) state.tokenize.pop();else stream.skipToEnd();
	            return "string";
	          };
	        }
	        function readBlockComment(stream, state) {
	          if (stream.sol() && stream.match("=end") && stream.eol()) state.tokenize.pop();
	          stream.skipToEnd();
	          return "comment";
	        }
	        return {
	          startState: function () {
	            return {
	              tokenize: [tokenBase],
	              indented: 0,
	              context: {
	                type: "top",
	                indented: -config.indentUnit
	              },
	              continuedLine: false,
	              lastTok: null,
	              varList: false
	            };
	          },
	          token: function (stream, state) {
	            curPunc = null;
	            if (stream.sol()) state.indented = stream.indentation();
	            var style = state.tokenize[state.tokenize.length - 1](stream, state),
	              kwtype;
	            var thisTok = curPunc;
	            if (style == "ident") {
	              var word = stream.current();
	              style = state.lastTok == "." ? "property" : keywords.propertyIsEnumerable(stream.current()) ? "keyword" : /^[A-Z]/.test(word) ? "tag" : state.lastTok == "def" || state.lastTok == "class" || state.varList ? "def" : "variable";
	              if (style == "keyword") {
	                thisTok = word;
	                if (indentWords.propertyIsEnumerable(word)) kwtype = "indent";else if (dedentWords.propertyIsEnumerable(word)) kwtype = "dedent";else if ((word == "if" || word == "unless") && stream.column() == stream.indentation()) kwtype = "indent";else if (word == "do" && state.context.indented < state.indented) kwtype = "indent";
	              }
	            }
	            if (curPunc || style && style != "comment") state.lastTok = thisTok;
	            if (curPunc == "|") state.varList = !state.varList;
	            if (kwtype == "indent" || /[\(\[\{]/.test(curPunc)) state.context = {
	              prev: state.context,
	              type: curPunc || style,
	              indented: state.indented
	            };else if ((kwtype == "dedent" || /[\)\]\}]/.test(curPunc)) && state.context.prev) state.context = state.context.prev;
	            if (stream.eol()) state.continuedLine = curPunc == "\\" || style == "operator";
	            return style;
	          },
	          indent: function (state, textAfter) {
	            if (state.tokenize[state.tokenize.length - 1] != tokenBase) return CodeMirror.Pass;
	            var firstChar = textAfter && textAfter.charAt(0);
	            var ct = state.context;
	            var closed = ct.type == closing[firstChar] || ct.type == "keyword" && /^(?:end|until|else|elsif|when|rescue)\b/.test(textAfter);
	            return ct.indented + (closed ? 0 : config.indentUnit) + (state.continuedLine ? config.indentUnit : 0);
	          },
	          electricInput: /^\s*(?:end|rescue|elsif|else|\})$/,
	          lineComment: "#",
	          fold: "indent"
	        };
	      });
	      CodeMirror.defineMIME("text/x-ruby", "ruby");
	      CodeMirror.registerHelper("hintWords", "ruby", keywordList);
	    });
	  })();
	  return ruby.exports;
	}

	requireRuby();

	var rust = {exports: {}};

	var hasRequiredRust;
	function requireRust() {
	  if (hasRequiredRust) return rust.exports;
	  hasRequiredRust = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror(), requireSimple());
	    })(function (CodeMirror) {

	      CodeMirror.defineSimpleMode("rust", {
	        start: [
	        // string and byte string
	        {
	          regex: /b?"/,
	          token: "string",
	          next: "string"
	        },
	        // raw string and raw byte string
	        {
	          regex: /b?r"/,
	          token: "string",
	          next: "string_raw"
	        }, {
	          regex: /b?r#+"/,
	          token: "string",
	          next: "string_raw_hash"
	        },
	        // character
	        {
	          regex: /'(?:[^'\\]|\\(?:[nrt0'"]|x[\da-fA-F]{2}|u\{[\da-fA-F]{6}\}))'/,
	          token: "string-2"
	        },
	        // byte
	        {
	          regex: /b'(?:[^']|\\(?:['\\nrt0]|x[\da-fA-F]{2}))'/,
	          token: "string-2"
	        }, {
	          regex: /(?:(?:[0-9][0-9_]*)(?:(?:[Ee][+-]?[0-9_]+)|\.[0-9_]+(?:[Ee][+-]?[0-9_]+)?)(?:f32|f64)?)|(?:0(?:b[01_]+|(?:o[0-7_]+)|(?:x[0-9a-fA-F_]+))|(?:[0-9][0-9_]*))(?:u8|u16|u32|u64|i8|i16|i32|i64|isize|usize)?/,
	          token: "number"
	        }, {
	          regex: /(let(?:\s+mut)?|fn|enum|mod|struct|type|union)(\s+)([a-zA-Z_][a-zA-Z0-9_]*)/,
	          token: ["keyword", null, "def"]
	        }, {
	          regex: /(?:abstract|alignof|as|async|await|box|break|continue|const|crate|do|dyn|else|enum|extern|fn|for|final|if|impl|in|loop|macro|match|mod|move|offsetof|override|priv|proc|pub|pure|ref|return|self|sizeof|static|struct|super|trait|type|typeof|union|unsafe|unsized|use|virtual|where|while|yield)\b/,
	          token: "keyword"
	        }, {
	          regex: /\b(?:Self|isize|usize|char|bool|u8|u16|u32|u64|f16|f32|f64|i8|i16|i32|i64|str|Option)\b/,
	          token: "atom"
	        }, {
	          regex: /\b(?:true|false|Some|None|Ok|Err)\b/,
	          token: "builtin"
	        }, {
	          regex: /\b(fn)(\s+)([a-zA-Z_][a-zA-Z0-9_]*)/,
	          token: ["keyword", null, "def"]
	        }, {
	          regex: /#!?\[.*\]/,
	          token: "meta"
	        }, {
	          regex: /\/\/.*/,
	          token: "comment"
	        }, {
	          regex: /\/\*/,
	          token: "comment",
	          next: "comment"
	        }, {
	          regex: /[-+\/*=<>!]+/,
	          token: "operator"
	        }, {
	          regex: /[a-zA-Z_]\w*!/,
	          token: "variable-3"
	        }, {
	          regex: /[a-zA-Z_]\w*/,
	          token: "variable"
	        }, {
	          regex: /[\{\[\(]/,
	          indent: true
	        }, {
	          regex: /[\}\]\)]/,
	          dedent: true
	        }],
	        string: [{
	          regex: /"/,
	          token: "string",
	          next: "start"
	        }, {
	          regex: /(?:[^\\"]|\\(?:.|$))*/,
	          token: "string"
	        }],
	        string_raw: [{
	          regex: /"/,
	          token: "string",
	          next: "start"
	        }, {
	          regex: /[^"]*/,
	          token: "string"
	        }],
	        string_raw_hash: [{
	          regex: /"#+/,
	          token: "string",
	          next: "start"
	        }, {
	          regex: /(?:[^"]|"(?!#))*/,
	          token: "string"
	        }],
	        comment: [{
	          regex: /.*?\*\//,
	          token: "comment",
	          next: "start"
	        }, {
	          regex: /.*/,
	          token: "comment"
	        }],
	        meta: {
	          dontIndentStates: ["comment"],
	          electricInput: /^\s*\}$/,
	          blockCommentStart: "/*",
	          blockCommentEnd: "*/",
	          lineComment: "//",
	          fold: "brace"
	        }
	      });
	      CodeMirror.defineMIME("text/x-rustsrc", "rust");
	      CodeMirror.defineMIME("text/rust", "rust");
	    });
	  })();
	  return rust.exports;
	}

	requireRust();

	var shell = {exports: {}};

	var hasRequiredShell;
	function requireShell() {
	  if (hasRequiredShell) return shell.exports;
	  hasRequiredShell = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      CodeMirror.defineMode('shell', function () {
	        var words = {};
	        function define(style, dict) {
	          for (var i = 0; i < dict.length; i++) {
	            words[dict[i]] = style;
	          }
	        }
	        var commonAtoms = ["true", "false"];
	        var commonKeywords = ["if", "then", "do", "else", "elif", "while", "until", "for", "in", "esac", "fi", "fin", "fil", "done", "exit", "set", "unset", "export", "function"];
	        var commonCommands = ["ab", "awk", "bash", "beep", "cat", "cc", "cd", "chown", "chmod", "chroot", "clear", "cp", "curl", "cut", "diff", "echo", "find", "gawk", "gcc", "get", "git", "grep", "hg", "kill", "killall", "ln", "ls", "make", "mkdir", "openssl", "mv", "nc", "nl", "node", "npm", "ping", "ps", "restart", "rm", "rmdir", "sed", "service", "sh", "shopt", "shred", "source", "sort", "sleep", "ssh", "start", "stop", "su", "sudo", "svn", "tee", "telnet", "top", "touch", "vi", "vim", "wall", "wc", "wget", "who", "write", "yes", "zsh"];
	        CodeMirror.registerHelper("hintWords", "shell", commonAtoms.concat(commonKeywords, commonCommands));
	        define('atom', commonAtoms);
	        define('keyword', commonKeywords);
	        define('builtin', commonCommands);
	        function tokenBase(stream, state) {
	          if (stream.eatSpace()) return null;
	          var sol = stream.sol();
	          var ch = stream.next();
	          if (ch === '\\') {
	            stream.next();
	            return null;
	          }
	          if (ch === '\'' || ch === '"' || ch === '`') {
	            state.tokens.unshift(tokenString(ch, ch === "`" ? "quote" : "string"));
	            return tokenize(stream, state);
	          }
	          if (ch === '#') {
	            if (sol && stream.eat('!')) {
	              stream.skipToEnd();
	              return 'meta'; // 'comment'?
	            }
	            stream.skipToEnd();
	            return 'comment';
	          }
	          if (ch === '$') {
	            state.tokens.unshift(tokenDollar);
	            return tokenize(stream, state);
	          }
	          if (ch === '+' || ch === '=') {
	            return 'operator';
	          }
	          if (ch === '-') {
	            stream.eat('-');
	            stream.eatWhile(/\w/);
	            return 'attribute';
	          }
	          if (ch == "<") {
	            if (stream.match("<<")) return "operator";
	            var heredoc = stream.match(/^<-?\s*['"]?([^'"]*)['"]?/);
	            if (heredoc) {
	              state.tokens.unshift(tokenHeredoc(heredoc[1]));
	              return 'string-2';
	            }
	          }
	          if (/\d/.test(ch)) {
	            stream.eatWhile(/\d/);
	            if (stream.eol() || !/\w/.test(stream.peek())) {
	              return 'number';
	            }
	          }
	          stream.eatWhile(/[\w-]/);
	          var cur = stream.current();
	          if (stream.peek() === '=' && /\w+/.test(cur)) return 'def';
	          return words.hasOwnProperty(cur) ? words[cur] : null;
	        }
	        function tokenString(quote, style) {
	          var close = quote == "(" ? ")" : quote == "{" ? "}" : quote;
	          return function (stream, state) {
	            var next,
	              escaped = false;
	            while ((next = stream.next()) != null) {
	              if (next === close && !escaped) {
	                state.tokens.shift();
	                break;
	              } else if (next === '$' && !escaped && quote !== "'" && stream.peek() != close) {
	                escaped = true;
	                stream.backUp(1);
	                state.tokens.unshift(tokenDollar);
	                break;
	              } else if (!escaped && quote !== close && next === quote) {
	                state.tokens.unshift(tokenString(quote, style));
	                return tokenize(stream, state);
	              } else if (!escaped && /['"]/.test(next) && !/['"]/.test(quote)) {
	                state.tokens.unshift(tokenStringStart(next, "string"));
	                stream.backUp(1);
	                break;
	              }
	              escaped = !escaped && next === '\\';
	            }
	            return style;
	          };
	        }
	        function tokenStringStart(quote, style) {
	          return function (stream, state) {
	            state.tokens[0] = tokenString(quote, style);
	            stream.next();
	            return tokenize(stream, state);
	          };
	        }
	        var tokenDollar = function (stream, state) {
	          if (state.tokens.length > 1) stream.eat('$');
	          var ch = stream.next();
	          if (/['"({]/.test(ch)) {
	            state.tokens[0] = tokenString(ch, ch == "(" ? "quote" : ch == "{" ? "def" : "string");
	            return tokenize(stream, state);
	          }
	          if (!/\d/.test(ch)) stream.eatWhile(/\w/);
	          state.tokens.shift();
	          return 'def';
	        };
	        function tokenHeredoc(delim) {
	          return function (stream, state) {
	            if (stream.sol() && stream.string == delim) state.tokens.shift();
	            stream.skipToEnd();
	            return "string-2";
	          };
	        }
	        function tokenize(stream, state) {
	          return (state.tokens[0] || tokenBase)(stream, state);
	        }
	        return {
	          startState: function () {
	            return {
	              tokens: []
	            };
	          },
	          token: function (stream, state) {
	            return tokenize(stream, state);
	          },
	          closeBrackets: "()[]{}''\"\"``",
	          lineComment: '#',
	          fold: "brace"
	        };
	      });
	      CodeMirror.defineMIME('text/x-sh', 'shell');
	      // Apache uses a slightly different Media Type for Shell scripts
	      // http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
	      CodeMirror.defineMIME('application/x-sh', 'shell');
	    });
	  })();
	  return shell.exports;
	}

	requireShell();

	var sql = {exports: {}};

	var hasRequiredSql;
	function requireSql() {
	  if (hasRequiredSql) return sql.exports;
	  hasRequiredSql = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      CodeMirror.defineMode("sql", function (config, parserConfig) {
	        var client = parserConfig.client || {},
	          atoms = parserConfig.atoms || {
	            "false": true,
	            "true": true,
	            "null": true
	          },
	          builtin = parserConfig.builtin || set(defaultBuiltin),
	          keywords = parserConfig.keywords || set(sqlKeywords),
	          operatorChars = parserConfig.operatorChars || /^[*+\-%<>!=&|~^\/]/,
	          support = parserConfig.support || {},
	          hooks = parserConfig.hooks || {},
	          dateSQL = parserConfig.dateSQL || {
	            "date": true,
	            "time": true,
	            "timestamp": true
	          },
	          backslashStringEscapes = parserConfig.backslashStringEscapes !== false,
	          brackets = parserConfig.brackets || /^[\{}\(\)\[\]]/,
	          punctuation = parserConfig.punctuation || /^[;.,:]/;
	        function tokenBase(stream, state) {
	          var ch = stream.next();

	          // call hooks from the mime type
	          if (hooks[ch]) {
	            var result = hooks[ch](stream, state);
	            if (result !== false) return result;
	          }
	          if (support.hexNumber && (ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/) || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]*'/))) {
	            // hex
	            // ref: https://dev.mysql.com/doc/refman/8.0/en/hexadecimal-literals.html
	            return "number";
	          } else if (support.binaryNumber && ((ch == "b" || ch == "B") && stream.match(/^'[01]*'/) || ch == "0" && stream.match(/^b[01]+/))) {
	            // bitstring
	            // ref: https://dev.mysql.com/doc/refman/8.0/en/bit-value-literals.html
	            return "number";
	          } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) {
	            // numbers
	            // ref: https://dev.mysql.com/doc/refman/8.0/en/number-literals.html
	            stream.match(/^[0-9]*(\.[0-9]+)?([eE][-+]?[0-9]+)?/);
	            support.decimallessFloat && stream.match(/^\.(?!\.)/);
	            return "number";
	          } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) {
	            // placeholders
	            return "variable-3";
	          } else if (ch == "'" || ch == '"' && support.doubleQuote) {
	            // strings
	            // ref: https://dev.mysql.com/doc/refman/8.0/en/string-literals.html
	            state.tokenize = tokenLiteral(ch);
	            return state.tokenize(stream, state);
	          } else if ((support.nCharCast && (ch == "n" || ch == "N") || support.charsetCast && ch == "_" && stream.match(/[a-z][a-z0-9]*/i)) && (stream.peek() == "'" || stream.peek() == '"')) {
	            // charset casting: _utf8'str', N'str', n'str'
	            // ref: https://dev.mysql.com/doc/refman/8.0/en/string-literals.html
	            return "keyword";
	          } else if (support.escapeConstant && (ch == "e" || ch == "E") && (stream.peek() == "'" || stream.peek() == '"' && support.doubleQuote)) {
	            // escape constant: E'str', e'str'
	            // ref: https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS-ESCAPE
	            state.tokenize = function (stream, state) {
	              return (state.tokenize = tokenLiteral(stream.next(), true))(stream, state);
	            };
	            return "keyword";
	          } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) {
	            // 1-line comment
	            stream.skipToEnd();
	            return "comment";
	          } else if (support.commentHash && ch == "#" || ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" "))) {
	            // 1-line comments
	            // ref: https://kb.askmonty.org/en/comment-syntax/
	            stream.skipToEnd();
	            return "comment";
	          } else if (ch == "/" && stream.eat("*")) {
	            // multi-line comments
	            // ref: https://kb.askmonty.org/en/comment-syntax/
	            state.tokenize = tokenComment(1);
	            return state.tokenize(stream, state);
	          } else if (ch == ".") {
	            // .1 for 0.1
	            if (support.zerolessFloat && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) return "number";
	            if (stream.match(/^\.+/)) return null;
	            if (stream.match(/^[\w\d_$#]+/)) return "variable-2";
	          } else if (operatorChars.test(ch)) {
	            // operators
	            stream.eatWhile(operatorChars);
	            return "operator";
	          } else if (brackets.test(ch)) {
	            // brackets
	            return "bracket";
	          } else if (punctuation.test(ch)) {
	            // punctuation
	            stream.eatWhile(punctuation);
	            return "punctuation";
	          } else if (ch == '{' && (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) {
	            // dates (weird ODBC syntax)
	            // ref: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-literals.html
	            return "number";
	          } else {
	            stream.eatWhile(/^[_\w\d]/);
	            var word = stream.current().toLowerCase();
	            // dates (standard SQL syntax)
	            // ref: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-literals.html
	            if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/))) return "number";
	            if (atoms.hasOwnProperty(word)) return "atom";
	            if (builtin.hasOwnProperty(word)) return "type";
	            if (keywords.hasOwnProperty(word)) return "keyword";
	            if (client.hasOwnProperty(word)) return "builtin";
	            return null;
	          }
	        }

	        // 'string', with char specified in quote escaped by '\'
	        function tokenLiteral(quote, backslashEscapes) {
	          return function (stream, state) {
	            var escaped = false,
	              ch;
	            while ((ch = stream.next()) != null) {
	              if (ch == quote && !escaped) {
	                state.tokenize = tokenBase;
	                break;
	              }
	              escaped = (backslashStringEscapes || backslashEscapes) && !escaped && ch == "\\";
	            }
	            return "string";
	          };
	        }
	        function tokenComment(depth) {
	          return function (stream, state) {
	            var m = stream.match(/^.*?(\/\*|\*\/)/);
	            if (!m) stream.skipToEnd();else if (m[1] == "/*") state.tokenize = tokenComment(depth + 1);else if (depth > 1) state.tokenize = tokenComment(depth - 1);else state.tokenize = tokenBase;
	            return "comment";
	          };
	        }
	        function pushContext(stream, state, type) {
	          state.context = {
	            prev: state.context,
	            indent: stream.indentation(),
	            col: stream.column(),
	            type: type
	          };
	        }
	        function popContext(state) {
	          state.indent = state.context.indent;
	          state.context = state.context.prev;
	        }
	        return {
	          startState: function () {
	            return {
	              tokenize: tokenBase,
	              context: null
	            };
	          },
	          token: function (stream, state) {
	            if (stream.sol()) {
	              if (state.context && state.context.align == null) state.context.align = false;
	            }
	            if (state.tokenize == tokenBase && stream.eatSpace()) return null;
	            var style = state.tokenize(stream, state);
	            if (style == "comment") return style;
	            if (state.context && state.context.align == null) state.context.align = true;
	            var tok = stream.current();
	            if (tok == "(") pushContext(stream, state, ")");else if (tok == "[") pushContext(stream, state, "]");else if (state.context && state.context.type == tok) popContext(state);
	            return style;
	          },
	          indent: function (state, textAfter) {
	            var cx = state.context;
	            if (!cx) return CodeMirror.Pass;
	            var closing = textAfter.charAt(0) == cx.type;
	            if (cx.align) return cx.col + (closing ? 0 : 1);else return cx.indent + (closing ? 0 : config.indentUnit);
	          },
	          blockCommentStart: "/*",
	          blockCommentEnd: "*/",
	          lineComment: support.commentSlashSlash ? "//" : support.commentHash ? "#" : "--",
	          closeBrackets: "()[]{}''\"\"``",
	          config: parserConfig
	        };
	      });

	      // `identifier`
	      function hookIdentifier(stream) {
	        // MySQL/MariaDB identifiers
	        // ref: https://dev.mysql.com/doc/refman/8.0/en/identifier-qualifiers.html
	        var ch;
	        while ((ch = stream.next()) != null) {
	          if (ch == "`" && !stream.eat("`")) return "variable-2";
	        }
	        stream.backUp(stream.current().length - 1);
	        return stream.eatWhile(/\w/) ? "variable-2" : null;
	      }

	      // "identifier"
	      function hookIdentifierDoublequote(stream) {
	        // Standard SQL /SQLite identifiers
	        // ref: http://web.archive.org/web/20160813185132/http://savage.net.au/SQL/sql-99.bnf.html#delimited%20identifier
	        // ref: http://sqlite.org/lang_keywords.html
	        var ch;
	        while ((ch = stream.next()) != null) {
	          if (ch == "\"" && !stream.eat("\"")) return "variable-2";
	        }
	        stream.backUp(stream.current().length - 1);
	        return stream.eatWhile(/\w/) ? "variable-2" : null;
	      }

	      // variable token
	      function hookVar(stream) {
	        // variables
	        // @@prefix.varName @varName
	        // varName can be quoted with ` or ' or "
	        // ref: https://dev.mysql.com/doc/refman/8.0/en/user-variables.html
	        if (stream.eat("@")) {
	          stream.match('session.');
	          stream.match('local.');
	          stream.match('global.');
	        }
	        if (stream.eat("'")) {
	          stream.match(/^.*'/);
	          return "variable-2";
	        } else if (stream.eat('"')) {
	          stream.match(/^.*"/);
	          return "variable-2";
	        } else if (stream.eat("`")) {
	          stream.match(/^.*`/);
	          return "variable-2";
	        } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) {
	          return "variable-2";
	        }
	        return null;
	      }

	      // short client keyword token
	      function hookClient(stream) {
	        // \N means NULL
	        // ref: https://dev.mysql.com/doc/refman/8.0/en/null-values.html
	        if (stream.eat("N")) {
	          return "atom";
	        }
	        // \g, etc
	        // ref: https://dev.mysql.com/doc/refman/8.0/en/mysql-commands.html
	        return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null;
	      }

	      // these keywords are used by all SQL dialects (however, a mode can still overwrite it)
	      var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit ";

	      // turn a space-separated list into an array
	      function set(str) {
	        var obj = {},
	          words = str.split(" ");
	        for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
	        return obj;
	      }
	      var defaultBuiltin = "bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision real date datetime year unsigned signed decimal numeric";

	      // A generic SQL Mode. It's not a standard, it just tries to support what is generally supported
	      CodeMirror.defineMIME("text/x-sql", {
	        name: "sql",
	        keywords: set(sqlKeywords + "begin"),
	        builtin: set(defaultBuiltin),
	        atoms: set("false true null unknown"),
	        dateSQL: set("date time timestamp"),
	        support: set("doubleQuote binaryNumber hexNumber")
	      });
	      CodeMirror.defineMIME("text/x-mssql", {
	        name: "sql",
	        client: set("$partition binary_checksum checksum connectionproperty context_info current_request_id error_line error_message error_number error_procedure error_severity error_state formatmessage get_filestream_transaction_context getansinull host_id host_name isnull isnumeric min_active_rowversion newid newsequentialid rowcount_big xact_state object_id"),
	        keywords: set(sqlKeywords + "begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare exec go if use index holdlock nolock nowait paglock readcommitted readcommittedlock readpast readuncommitted repeatableread rowlock serializable snapshot tablock tablockx updlock with"),
	        builtin: set("bigint numeric bit smallint decimal smallmoney int tinyint money float real char varchar text nchar nvarchar ntext binary varbinary image cursor timestamp hierarchyid uniqueidentifier sql_variant xml table "),
	        atoms: set("is not null like and or in left right between inner outer join all any some cross unpivot pivot exists"),
	        operatorChars: /^[*+\-%<>!=^\&|\/]/,
	        brackets: /^[\{}\(\)]/,
	        punctuation: /^[;.,:/]/,
	        backslashStringEscapes: false,
	        dateSQL: set("date datetimeoffset datetime2 smalldatetime datetime time"),
	        hooks: {
	          "@": hookVar
	        }
	      });
	      CodeMirror.defineMIME("text/x-mysql", {
	        name: "sql",
	        client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
	        keywords: set(sqlKeywords + "accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general get global grant grants group group_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),
	        builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),
	        atoms: set("false true null unknown"),
	        operatorChars: /^[*+\-%<>!=&|^]/,
	        dateSQL: set("date time timestamp"),
	        support: set("decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
	        hooks: {
	          "@": hookVar,
	          "`": hookIdentifier,
	          "\\": hookClient
	        }
	      });
	      CodeMirror.defineMIME("text/x-mariadb", {
	        name: "sql",
	        client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
	        keywords: set(sqlKeywords + "accessible action add after algorithm all always analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general generated get global grant grants group group_concat handler hard hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password persistent phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show shutdown signal slave slow smallint snapshot soft soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views virtual warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),
	        builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),
	        atoms: set("false true null unknown"),
	        operatorChars: /^[*+\-%<>!=&|^]/,
	        dateSQL: set("date time timestamp"),
	        support: set("decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
	        hooks: {
	          "@": hookVar,
	          "`": hookIdentifier,
	          "\\": hookClient
	        }
	      });

	      // provided by the phpLiteAdmin project - phpliteadmin.org
	      CodeMirror.defineMIME("text/x-sqlite", {
	        name: "sql",
	        // commands of the official SQLite client, ref: https://www.sqlite.org/cli.html#dotcmd
	        client: set("auth backup bail binary changes check clone databases dbinfo dump echo eqp exit explain fullschema headers help import imposter indexes iotrace limit lint load log mode nullvalue once open output print prompt quit read restore save scanstats schema separator session shell show stats system tables testcase timeout timer trace vfsinfo vfslist vfsname width"),
	        // ref: http://sqlite.org/lang_keywords.html
	        keywords: set(sqlKeywords + "abort action add after all analyze attach autoincrement before begin cascade case cast check collate column commit conflict constraint cross current_date current_time current_timestamp database default deferrable deferred detach each else end escape except exclusive exists explain fail for foreign full glob if ignore immediate index indexed initially inner instead intersect isnull key left limit match natural no notnull null of offset outer plan pragma primary query raise recursive references regexp reindex release rename replace restrict right rollback row savepoint temp temporary then to transaction trigger unique using vacuum view virtual when with without"),
	        // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types.
	        builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text clob bigint int int2 int8 integer float double char varchar date datetime year unsigned signed numeric real"),
	        // ref: http://sqlite.org/syntax/literal-value.html
	        atoms: set("null current_date current_time current_timestamp"),
	        // ref: http://sqlite.org/lang_expr.html#binaryops
	        operatorChars: /^[*+\-%<>!=&|/~]/,
	        // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types.
	        dateSQL: set("date time timestamp datetime"),
	        support: set("decimallessFloat zerolessFloat"),
	        identifierQuote: "\"",
	        //ref: http://sqlite.org/lang_keywords.html
	        hooks: {
	          // bind-parameters ref:http://sqlite.org/lang_expr.html#varparam
	          "@": hookVar,
	          ":": hookVar,
	          "?": hookVar,
	          "$": hookVar,
	          // The preferred way to escape Identifiers is using double quotes, ref: http://sqlite.org/lang_keywords.html
	          "\"": hookIdentifierDoublequote,
	          // there is also support for backticks, ref: http://sqlite.org/lang_keywords.html
	          "`": hookIdentifier
	        }
	      });

	      // the query language used by Apache Cassandra is called CQL, but this mime type
	      // is called Cassandra to avoid confusion with Contextual Query Language
	      CodeMirror.defineMIME("text/x-cassandra", {
	        name: "sql",
	        client: {},
	        keywords: set("add all allow alter and any apply as asc authorize batch begin by clustering columnfamily compact consistency count create custom delete desc distinct drop each_quorum exists filtering from grant if in index insert into key keyspace keyspaces level limit local_one local_quorum modify nan norecursive nosuperuser not of on one order password permission permissions primary quorum rename revoke schema select set storage superuser table three to token truncate ttl two type unlogged update use user users using values where with writetime"),
	        builtin: set("ascii bigint blob boolean counter decimal double float frozen inet int list map static text timestamp timeuuid tuple uuid varchar varint"),
	        atoms: set("false true infinity NaN"),
	        operatorChars: /^[<>=]/,
	        dateSQL: {},
	        support: set("commentSlashSlash decimallessFloat"),
	        hooks: {}
	      });

	      // this is based on Peter Raganitsch's 'plsql' mode
	      CodeMirror.defineMIME("text/x-plsql", {
	        name: "sql",
	        client: set("appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define describe echo editfile embedded escape exec execute feedback flagger flush heading headsep instance linesize lno loboffset logsource long longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar release repfooter repheader serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout time timing trimout trimspool ttitle underline verify version wrap"),
	        keywords: set("abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else elseif elsif enable end entry escape exception exception_init exchange exclusive exists exit external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging long loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base object of off offline on online only open option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw read rebuild record ref references refresh release rename replace resource restrict return returning returns reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate session set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work"),
	        builtin: set("abs acos add_months ascii asin atan atan2 average bfile bfilename bigserial bit blob ceil character chartorowid chr clob concat convert cos cosh count dec decode deref dual dump dup_val_on_index empty error exp false float floor found glb greatest hextoraw initcap instr instrb int integer isopen last_day least length lengthb ln lower lpad ltrim lub make_ref max min mlslabel mod months_between natural naturaln nchar nclob new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null number numeric nvarchar2 nvl others power rawtohex real reftohex round rowcount rowidtochar rowtype rpad rtrim serial sign signtype sin sinh smallint soundex sqlcode sqlerrm sqrt stddev string substr substrb sum sysdate tan tanh to_char text to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid unlogged upper user userenv varchar varchar2 variance varying vsize xml"),
	        operatorChars: /^[*\/+\-%<>!=~]/,
	        dateSQL: set("date time timestamp"),
	        support: set("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber")
	      });

	      // Created to support specific hive keywords
	      CodeMirror.defineMIME("text/x-hive", {
	        name: "sql",
	        keywords: set("select alter $elem$ $key$ $value$ add after all analyze and archive as asc before between binary both bucket buckets by cascade case cast change cluster clustered clusterstatus collection column columns comment compute concatenate continue create cross cursor data database databases dbproperties deferred delete delimited desc describe directory disable distinct distribute drop else enable end escaped exclusive exists explain export extended external fetch fields fileformat first format formatted from full function functions grant group having hold_ddltime idxproperties if import in index indexes inpath inputdriver inputformat insert intersect into is items join keys lateral left like limit lines load local location lock locks mapjoin materialized minus msck no_drop nocompress not of offline on option or order out outer outputdriver outputformat overwrite partition partitioned partitions percent plus preserve procedure purge range rcfile read readonly reads rebuild recordreader recordwriter recover reduce regexp rename repair replace restrict revoke right rlike row schema schemas semi sequencefile serde serdeproperties set shared show show_database sort sorted ssl statistics stored streamtable table tables tablesample tblproperties temporary terminated textfile then tmp to touch transform trigger unarchive undo union uniquejoin unlock update use using utc utc_tmestamp view when where while with admin authorization char compact compactions conf cube current current_date current_timestamp day decimal defined dependency directories elem_type exchange file following for grouping hour ignore inner interval jar less logical macro minute month more none noscan over owner partialscan preceding pretty principals protection reload rewrite role roles rollup rows second server sets skewed transactions truncate unbounded unset uri user values window year"),
	        builtin: set("bool boolean long timestamp tinyint smallint bigint int float double date datetime unsigned string array struct map uniontype key_type utctimestamp value_type varchar"),
	        atoms: set("false true null unknown"),
	        operatorChars: /^[*+\-%<>!=]/,
	        dateSQL: set("date timestamp"),
	        support: set("doubleQuote binaryNumber hexNumber")
	      });
	      CodeMirror.defineMIME("text/x-pgsql", {
	        name: "sql",
	        client: set("source"),
	        // For PostgreSQL - https://www.postgresql.org/docs/11/sql-keywords-appendix.html
	        // For pl/pgsql lang - https://github.com/postgres/postgres/blob/REL_11_2/src/pl/plpgsql/src/pl_scanner.c
	        keywords: set(sqlKeywords + "a abort abs absent absolute access according action ada add admin after aggregate alias all allocate also alter always analyse analyze and any are array array_agg array_max_cardinality as asc asensitive assert assertion assignment asymmetric at atomic attach attribute attributes authorization avg backward base64 before begin begin_frame begin_partition bernoulli between bigint binary bit bit_length blob blocked bom boolean both breadth by c cache call called cardinality cascade cascaded case cast catalog catalog_name ceil ceiling chain char char_length character character_length character_set_catalog character_set_name character_set_schema characteristics characters check checkpoint class class_origin clob close cluster coalesce cobol collate collation collation_catalog collation_name collation_schema collect column column_name columns command_function command_function_code comment comments commit committed concurrently condition condition_number configuration conflict connect connection connection_name constant constraint constraint_catalog constraint_name constraint_schema constraints constructor contains content continue control conversion convert copy corr corresponding cost count covar_pop covar_samp create cross csv cube cume_dist current current_catalog current_date current_default_transform_group current_path current_role current_row current_schema current_time current_timestamp current_transform_group_for_type current_user cursor cursor_name cycle data database datalink datatype date datetime_interval_code datetime_interval_precision day db deallocate debug dec decimal declare default defaults deferrable deferred defined definer degree delete delimiter delimiters dense_rank depends depth deref derived desc describe descriptor detach detail deterministic diagnostics dictionary disable discard disconnect dispatch distinct dlnewcopy dlpreviouscopy dlurlcomplete dlurlcompleteonly dlurlcompletewrite dlurlpath dlurlpathonly dlurlpathwrite dlurlscheme dlurlserver dlvalue do document domain double drop dump dynamic dynamic_function dynamic_function_code each element else elseif elsif empty enable encoding encrypted end end_frame end_partition endexec enforced enum equals errcode error escape event every except exception exclude excluding exclusive exec execute exists exit exp explain expression extension external extract false family fetch file filter final first first_value flag float floor following for force foreach foreign fortran forward found frame_row free freeze from fs full function functions fusion g general generated get global go goto grant granted greatest group grouping groups handler having header hex hierarchy hint hold hour id identity if ignore ilike immediate immediately immutable implementation implicit import in include including increment indent index indexes indicator info inherit inherits initially inline inner inout input insensitive insert instance instantiable instead int integer integrity intersect intersection interval into invoker is isnull isolation join k key key_member key_type label lag language large last last_value lateral lead leading leakproof least left length level library like like_regex limit link listen ln load local localtime localtimestamp location locator lock locked log logged loop lower m map mapping match matched materialized max max_cardinality maxvalue member merge message message_length message_octet_length message_text method min minute minvalue mod mode modifies module month more move multiset mumps name names namespace national natural nchar nclob nesting new next nfc nfd nfkc nfkd nil no none normalize normalized not nothing notice notify notnull nowait nth_value ntile null nullable nullif nulls number numeric object occurrences_regex octet_length octets of off offset oids old on only open operator option options or order ordering ordinality others out outer output over overlaps overlay overriding owned owner p pad parallel parameter parameter_mode parameter_name parameter_ordinal_position parameter_specific_catalog parameter_specific_name parameter_specific_schema parser partial partition pascal passing passthrough password path percent percent_rank percentile_cont percentile_disc perform period permission pg_context pg_datatype_name pg_exception_context pg_exception_detail pg_exception_hint placing plans pli policy portion position position_regex power precedes preceding precision prepare prepared preserve primary print_strict_params prior privileges procedural procedure procedures program public publication query quote raise range rank read reads real reassign recheck recovery recursive ref references referencing refresh regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy regr_syy reindex relative release rename repeatable replace replica requiring reset respect restart restore restrict result result_oid return returned_cardinality returned_length returned_octet_length returned_sqlstate returning returns reverse revoke right role rollback rollup routine routine_catalog routine_name routine_schema routines row row_count row_number rows rowtype rule savepoint scale schema schema_name schemas scope scope_catalog scope_name scope_schema scroll search second section security select selective self sensitive sequence sequences serializable server server_name session session_user set setof sets share show similar simple size skip slice smallint snapshot some source space specific specific_name specifictype sql sqlcode sqlerror sqlexception sqlstate sqlwarning sqrt stable stacked standalone start state statement static statistics stddev_pop stddev_samp stdin stdout storage strict strip structure style subclass_origin submultiset subscription substring substring_regex succeeds sum symmetric sysid system system_time system_user t table table_name tables tablesample tablespace temp template temporary text then ties time timestamp timezone_hour timezone_minute to token top_level_count trailing transaction transaction_active transactions_committed transactions_rolled_back transform transforms translate translate_regex translation treat trigger trigger_catalog trigger_name trigger_schema trim trim_array true truncate trusted type types uescape unbounded uncommitted under unencrypted union unique unknown unlink unlisten unlogged unnamed unnest until untyped update upper uri usage use_column use_variable user user_defined_type_catalog user_defined_type_code user_defined_type_name user_defined_type_schema using vacuum valid validate validator value value_of values var_pop var_samp varbinary varchar variable_conflict variadic varying verbose version versioning view views volatile warning when whenever where while whitespace width_bucket window with within without work wrapper write xml xmlagg xmlattributes xmlbinary xmlcast xmlcomment xmlconcat xmldeclaration xmldocument xmlelement xmlexists xmlforest xmliterate xmlnamespaces xmlparse xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltext xmlvalidate year yes zone"),
	        // https://www.postgresql.org/docs/11/datatype.html
	        builtin: set("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float8 inet integer int int4 interval json jsonb line lseg macaddr macaddr8 money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time zone timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml"),
	        atoms: set("false true null unknown"),
	        operatorChars: /^[*\/+\-%<>!=&|^\/#@?~]/,
	        backslashStringEscapes: false,
	        identifierQuote: "\"",
	        // https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
	        hooks: {
	          "\"": hookIdentifierDoublequote
	        },
	        dateSQL: set("date time timestamp"),
	        support: set("decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast escapeConstant")
	      });

	      // Google's SQL-like query language, GQL
	      CodeMirror.defineMIME("text/x-gql", {
	        name: "sql",
	        keywords: set("ancestor and asc by contains desc descendant distinct from group has in is limit offset on order select superset where"),
	        atoms: set("false true"),
	        builtin: set("blob datetime first key __key__ string integer double boolean null"),
	        operatorChars: /^[*+\-%<>!=]/
	      });

	      // Greenplum
	      CodeMirror.defineMIME("text/x-gpsql", {
	        name: "sql",
	        client: set("source"),
	        //https://github.com/greenplum-db/gpdb/blob/master/src/include/parser/kwlist.h
	        keywords: set("abort absolute access action active add admin after aggregate all also alter always analyse analyze and any array as asc assertion assignment asymmetric at authorization backward before begin between bigint binary bit boolean both by cache called cascade cascaded case cast chain char character characteristics check checkpoint class close cluster coalesce codegen collate column comment commit committed concurrency concurrently configuration connection constraint constraints contains content continue conversion copy cost cpu_rate_limit create createdb createexttable createrole createuser cross csv cube current current_catalog current_date current_role current_schema current_time current_timestamp current_user cursor cycle data database day deallocate dec decimal declare decode default defaults deferrable deferred definer delete delimiter delimiters deny desc dictionary disable discard distinct distributed do document domain double drop dxl each else enable encoding encrypted end enum errors escape every except exchange exclude excluding exclusive execute exists explain extension external extract false family fetch fields filespace fill filter first float following for force foreign format forward freeze from full function global grant granted greatest group group_id grouping handler hash having header hold host hour identity if ignore ilike immediate immutable implicit in including inclusive increment index indexes inherit inherits initially inline inner inout input insensitive insert instead int integer intersect interval into invoker is isnull isolation join key language large last leading least left level like limit list listen load local localtime localtimestamp location lock log login mapping master match maxvalue median merge minute minvalue missing mode modifies modify month move name names national natural nchar new newline next no nocreatedb nocreateexttable nocreaterole nocreateuser noinherit nologin none noovercommit nosuperuser not nothing notify notnull nowait null nullif nulls numeric object of off offset oids old on only operator option options or order ordered others out outer over overcommit overlaps overlay owned owner parser partial partition partitions passing password percent percentile_cont percentile_disc placing plans position preceding precision prepare prepared preserve primary prior privileges procedural procedure protocol queue quote randomly range read readable reads real reassign recheck recursive ref references reindex reject relative release rename repeatable replace replica reset resource restart restrict returning returns revoke right role rollback rollup rootpartition row rows rule savepoint scatter schema scroll search second security segment select sequence serializable session session_user set setof sets share show similar simple smallint some split sql stable standalone start statement statistics stdin stdout storage strict strip subpartition subpartitions substring superuser symmetric sysid system table tablespace temp template temporary text then threshold ties time timestamp to trailing transaction treat trigger trim true truncate trusted type unbounded uncommitted unencrypted union unique unknown unlisten until update user using vacuum valid validation validator value values varchar variadic varying verbose version view volatile web when where whitespace window with within without work writable write xml xmlattributes xmlconcat xmlelement xmlexists xmlforest xmlparse xmlpi xmlroot xmlserialize year yes zone"),
	        builtin: set("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float float8 inet integer int int4 interval json jsonb line lseg macaddr macaddr8 money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml"),
	        atoms: set("false true null unknown"),
	        operatorChars: /^[*+\-%<>!=&|^\/#@?~]/,
	        dateSQL: set("date time timestamp"),
	        support: set("decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast")
	      });

	      // Spark SQL
	      CodeMirror.defineMIME("text/x-sparksql", {
	        name: "sql",
	        keywords: set("add after all alter analyze and anti archive array as asc at between bucket buckets by cache cascade case cast change clear cluster clustered codegen collection column columns comment commit compact compactions compute concatenate cost create cross cube current current_date current_timestamp database databases data dbproperties defined delete delimited deny desc describe dfs directories distinct distribute drop else end escaped except exchange exists explain export extended external false fields fileformat first following for format formatted from full function functions global grant group grouping having if ignore import in index indexes inner inpath inputformat insert intersect interval into is items join keys last lateral lazy left like limit lines list load local location lock locks logical macro map minus msck natural no not null nulls of on optimize option options or order out outer outputformat over overwrite partition partitioned partitions percent preceding principals purge range recordreader recordwriter recover reduce refresh regexp rename repair replace reset restrict revoke right rlike role roles rollback rollup row rows schema schemas select semi separated serde serdeproperties set sets show skewed sort sorted start statistics stored stratify struct table tables tablesample tblproperties temp temporary terminated then to touch transaction transactions transform true truncate unarchive unbounded uncache union unlock unset use using values view when where window with"),
	        builtin: set("abs acos acosh add_months aggregate and any approx_count_distinct approx_percentile array array_contains array_distinct array_except array_intersect array_join array_max array_min array_position array_remove array_repeat array_sort array_union arrays_overlap arrays_zip ascii asin asinh assert_true atan atan2 atanh avg base64 between bigint bin binary bit_and bit_count bit_get bit_length bit_or bit_xor bool_and bool_or boolean bround btrim cardinality case cast cbrt ceil ceiling char char_length character_length chr coalesce collect_list collect_set concat concat_ws conv corr cos cosh cot count count_if count_min_sketch covar_pop covar_samp crc32 cume_dist current_catalog current_database current_date current_timestamp current_timezone current_user date date_add date_format date_from_unix_date date_part date_sub date_trunc datediff day dayofmonth dayofweek dayofyear decimal decode degrees delimited dense_rank div double e element_at elt encode every exists exp explode explode_outer expm1 extract factorial filter find_in_set first first_value flatten float floor forall format_number format_string from_csv from_json from_unixtime from_utc_timestamp get_json_object getbit greatest grouping grouping_id hash hex hour hypot if ifnull in initcap inline inline_outer input_file_block_length input_file_block_start input_file_name inputformat instr int isnan isnotnull isnull java_method json_array_length json_object_keys json_tuple kurtosis lag last last_day last_value lcase lead least left length levenshtein like ln locate log log10 log1p log2 lower lpad ltrim make_date make_dt_interval make_interval make_timestamp make_ym_interval map map_concat map_entries map_filter map_from_arrays map_from_entries map_keys map_values map_zip_with max max_by md5 mean min min_by minute mod monotonically_increasing_id month months_between named_struct nanvl negative next_day not now nth_value ntile nullif nvl nvl2 octet_length or outputformat overlay parse_url percent_rank percentile percentile_approx pi pmod posexplode posexplode_outer position positive pow power printf quarter radians raise_error rand randn random rank rcfile reflect regexp regexp_extract regexp_extract_all regexp_like regexp_replace repeat replace reverse right rint rlike round row_number rpad rtrim schema_of_csv schema_of_json second sentences sequence sequencefile serde session_window sha sha1 sha2 shiftleft shiftright shiftrightunsigned shuffle sign signum sin sinh size skewness slice smallint some sort_array soundex space spark_partition_id split sqrt stack std stddev stddev_pop stddev_samp str_to_map string struct substr substring substring_index sum tan tanh textfile timestamp timestamp_micros timestamp_millis timestamp_seconds tinyint to_csv to_date to_json to_timestamp to_unix_timestamp to_utc_timestamp transform transform_keys transform_values translate trim trunc try_add try_divide typeof ucase unbase64 unhex uniontype unix_date unix_micros unix_millis unix_seconds unix_timestamp upper uuid var_pop var_samp variance version weekday weekofyear when width_bucket window xpath xpath_boolean xpath_double xpath_float xpath_int xpath_long xpath_number xpath_short xpath_string xxhash64 year zip_with"),
	        atoms: set("false true null"),
	        operatorChars: /^[*\/+\-%<>!=~&|^]/,
	        dateSQL: set("date time timestamp"),
	        support: set("doubleQuote zerolessFloat")
	      });

	      // Esper
	      CodeMirror.defineMIME("text/x-esper", {
	        name: "sql",
	        client: set("source"),
	        // http://www.espertech.com/esper/release-5.5.0/esper-reference/html/appendix_keywords.html
	        keywords: set("alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit after all and as at asc avedev avg between by case cast coalesce count create current_timestamp day days delete define desc distinct else end escape events every exists false first from full group having hour hours in inner insert instanceof into irstream is istream join last lastweekday left limit like max match_recognize matches median measures metadatasql min minute minutes msec millisecond milliseconds not null offset on or order outer output partition pattern prev prior regexp retain-union retain-intersection right rstream sec second seconds select set some snapshot sql stddev sum then true unidirectional until update variable weekday when where window"),
	        builtin: {},
	        atoms: set("false true null"),
	        operatorChars: /^[*+\-%<>!=&|^\/#@?~]/,
	        dateSQL: set("time"),
	        support: set("decimallessFloat zerolessFloat binaryNumber hexNumber")
	      });

	      // Trino (formerly known as Presto)
	      CodeMirror.defineMIME("text/x-trino", {
	        name: "sql",
	        // https://github.com/trinodb/trino/blob/bc7a4eeedde28684c7ae6f74cefcaf7c6e782174/core/trino-parser/src/main/antlr4/io/trino/sql/parser/SqlBase.g4#L859-L1129
	        // https://github.com/trinodb/trino/blob/bc7a4eeedde28684c7ae6f74cefcaf7c6e782174/docs/src/main/sphinx/functions/list.rst
	        keywords: set("abs absent acos add admin after all all_match alter analyze and any any_match approx_distinct approx_most_frequent approx_percentile approx_set arbitrary array_agg array_distinct array_except array_intersect array_join array_max array_min array_position array_remove array_sort array_union arrays_overlap as asc asin at at_timezone atan atan2 authorization avg bar bernoulli beta_cdf between bing_tile bing_tile_at bing_tile_coordinates bing_tile_polygon bing_tile_quadkey bing_tile_zoom_level bing_tiles_around bit_count bitwise_and bitwise_and_agg bitwise_left_shift bitwise_not bitwise_or bitwise_or_agg bitwise_right_shift bitwise_right_shift_arithmetic bitwise_xor bool_and bool_or both by call cardinality cascade case cast catalogs cbrt ceil ceiling char2hexint checksum chr classify coalesce codepoint column columns combinations comment commit committed concat concat_ws conditional constraint contains contains_sequence convex_hull_agg copartition corr cos cosh cosine_similarity count count_if covar_pop covar_samp crc32 create cross cube cume_dist current current_catalog current_date current_groups current_path current_role current_schema current_time current_timestamp current_timezone current_user data date_add date_diff date_format date_parse date_trunc day day_of_month day_of_week day_of_year deallocate default define definer degrees delete dense_rank deny desc describe descriptor distinct distributed dow doy drop e element_at else empty empty_approx_set encoding end error escape evaluate_classifier_predictions every except excluding execute exists exp explain extract false features fetch filter final first first_value flatten floor following for format format_datetime format_number from from_base from_base32 from_base64 from_base64url from_big_endian_32 from_big_endian_64 from_encoded_polyline from_geojson_geometry from_hex from_ieee754_32 from_ieee754_64 from_iso8601_date from_iso8601_timestamp from_iso8601_timestamp_nanos from_unixtime from_unixtime_nanos from_utf8 full functions geometric_mean geometry_from_hadoop_shape geometry_invalid_reason geometry_nearest_points geometry_to_bing_tiles geometry_union geometry_union_agg grant granted grants graphviz great_circle_distance greatest group grouping groups hamming_distance hash_counts having histogram hmac_md5 hmac_sha1 hmac_sha256 hmac_sha512 hour human_readable_seconds if ignore in including index infinity initial inner input insert intersect intersection_cardinality into inverse_beta_cdf inverse_normal_cdf invoker io is is_finite is_infinite is_json_scalar is_nan isolation jaccard_index join json_array json_array_contains json_array_get json_array_length json_exists json_extract json_extract_scalar json_format json_object json_parse json_query json_size json_value keep key keys kurtosis lag last last_day_of_month last_value lateral lead leading learn_classifier learn_libsvm_classifier learn_libsvm_regressor learn_regressor least left length level levenshtein_distance like limit line_interpolate_point line_interpolate_points line_locate_point listagg ln local localtime localtimestamp log log10 log2 logical lower lpad ltrim luhn_check make_set_digest map_agg map_concat map_entries map_filter map_from_entries map_keys map_union map_values map_zip_with match match_recognize matched matches materialized max max_by md5 measures merge merge_set_digest millisecond min min_by minute mod month multimap_agg multimap_from_entries murmur3 nan natural next nfc nfd nfkc nfkd ngrams no none none_match normal_cdf normalize not now nth_value ntile null nullif nulls numeric_histogram object objectid_timestamp of offset omit on one only option or order ordinality outer output over overflow parse_data_size parse_datetime parse_duration partition partitions passing past path pattern per percent_rank permute pi position pow power preceding prepare privileges properties prune qdigest_agg quarter quotes radians rand random range rank read recursive reduce reduce_agg refresh regexp_count regexp_extract regexp_extract_all regexp_like regexp_position regexp_replace regexp_split regr_intercept regr_slope regress rename render repeat repeatable replace reset respect restrict returning reverse revoke rgb right role roles rollback rollup round row_number rows rpad rtrim running scalar schema schemas second security seek select sequence serializable session set sets sha1 sha256 sha512 show shuffle sign simplify_geometry sin skewness skip slice some soundex spatial_partitioning spatial_partitions split split_part split_to_map split_to_multimap spooky_hash_v2_32 spooky_hash_v2_64 sqrt st_area st_asbinary st_astext st_boundary st_buffer st_centroid st_contains st_convexhull st_coorddim st_crosses st_difference st_dimension st_disjoint st_distance st_endpoint st_envelope st_envelopeaspts st_equals st_exteriorring st_geometries st_geometryfromtext st_geometryn st_geometrytype st_geomfrombinary st_interiorringn st_interiorrings st_intersection st_intersects st_isclosed st_isempty st_isring st_issimple st_isvalid st_length st_linefromtext st_linestring st_multipoint st_numgeometries st_numinteriorring st_numpoints st_overlaps st_point st_pointn st_points st_polygon st_relate st_startpoint st_symdifference st_touches st_union st_within st_x st_xmax st_xmin st_y st_ymax st_ymin start starts_with stats stddev stddev_pop stddev_samp string strpos subset substr substring sum system table tables tablesample tan tanh tdigest_agg text then ties timestamp_objectid timezone_hour timezone_minute to to_base to_base32 to_base64 to_base64url to_big_endian_32 to_big_endian_64 to_char to_date to_encoded_polyline to_geojson_geometry to_geometry to_hex to_ieee754_32 to_ieee754_64 to_iso8601 to_milliseconds to_spherical_geography to_timestamp to_unixtime to_utf8 trailing transaction transform transform_keys transform_values translate trim trim_array true truncate try try_cast type typeof uescape unbounded uncommitted unconditional union unique unknown unmatched unnest update upper url_decode url_encode url_extract_fragment url_extract_host url_extract_parameter url_extract_path url_extract_port url_extract_protocol url_extract_query use user using utf16 utf32 utf8 validate value value_at_quantile values values_at_quantiles var_pop var_samp variance verbose version view week week_of_year when where width_bucket wilson_interval_lower wilson_interval_upper window with with_timezone within without word_stem work wrapper write xxhash64 year year_of_week yow zip zip_with"),
	        // https://github.com/trinodb/trino/blob/bc7a4eeedde28684c7ae6f74cefcaf7c6e782174/core/trino-main/src/main/java/io/trino/metadata/TypeRegistry.java#L131-L168
	        // https://github.com/trinodb/trino/blob/bc7a4eeedde28684c7ae6f74cefcaf7c6e782174/plugin/trino-ml/src/main/java/io/trino/plugin/ml/MLPlugin.java#L35
	        // https://github.com/trinodb/trino/blob/bc7a4eeedde28684c7ae6f74cefcaf7c6e782174/plugin/trino-mongodb/src/main/java/io/trino/plugin/mongodb/MongoPlugin.java#L32
	        // https://github.com/trinodb/trino/blob/bc7a4eeedde28684c7ae6f74cefcaf7c6e782174/plugin/trino-geospatial/src/main/java/io/trino/plugin/geospatial/GeoPlugin.java#L37
	        builtin: set("array bigint bingtile boolean char codepoints color date decimal double function geometry hyperloglog int integer interval ipaddress joniregexp json json2016 jsonpath kdbtree likepattern map model objectid p4hyperloglog precision qdigest re2jregexp real regressor row setdigest smallint sphericalgeography tdigest time timestamp tinyint uuid varbinary varchar zone"),
	        atoms: set("false true null unknown"),
	        // https://trino.io/docs/current/functions/list.html#id1
	        operatorChars: /^[[\]|<>=!\-+*/%]/,
	        dateSQL: set("date time timestamp zone"),
	        // hexNumber is necessary for VARBINARY literals, e.g. X'65683F'
	        // but it also enables 0xFF hex numbers, which Trino doesn't support.
	        support: set("decimallessFloat zerolessFloat hexNumber")
	      });
	    });

	    /*
	      How Properties of Mime Types are used by SQL Mode
	      =================================================
	    	  keywords:
	        A list of keywords you want to be highlighted.
	      builtin:
	        A list of builtin types you want to be highlighted (if you want types to be of class "builtin" instead of "keyword").
	      operatorChars:
	        All characters that must be handled as operators.
	      client:
	        Commands parsed and executed by the client (not the server).
	      support:
	        A list of supported syntaxes which are not common, but are supported by more than 1 DBMS.
	        * zerolessFloat: .1
	        * decimallessFloat: 1.
	        * hexNumber: X'01AF' X'01af' x'01AF' x'01af' 0x01AF 0x01af
	        * binaryNumber: b'01' B'01' 0b01
	        * doubleQuote: "string"
	        * escapeConstant: E''
	        * nCharCast: N'string'
	        * charsetCast: _utf8'string'
	        * commentHash: use # char for comments
	        * commentSlashSlash: use // for comments
	        * commentSpaceRequired: require a space after -- for comments
	      atoms:
	        Keywords that must be highlighted as atoms,. Some DBMS's support more atoms than others:
	        UNKNOWN, INFINITY, UNDERFLOW, NaN...
	      dateSQL:
	        Used for date/time SQL standard syntax, because not all DBMS's support same temporal types.
	    */
	  })();
	  return sql.exports;
	}

	requireSql();

	var swift = {exports: {}};

	var hasRequiredSwift;
	function requireSwift() {
	  if (hasRequiredSwift) return swift.exports;
	  hasRequiredSwift = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    // Swift mode created by Michael Kaminsky https://github.com/mkaminsky11

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      function wordSet(words) {
	        var set = {};
	        for (var i = 0; i < words.length; i++) set[words[i]] = true;
	        return set;
	      }
	      var keywords = wordSet(["_", "var", "let", "actor", "class", "enum", "extension", "import", "protocol", "struct", "func", "typealias", "associatedtype", "open", "public", "internal", "fileprivate", "private", "deinit", "init", "new", "override", "self", "subscript", "super", "convenience", "dynamic", "final", "indirect", "lazy", "required", "static", "unowned", "unowned(safe)", "unowned(unsafe)", "weak", "as", "is", "break", "case", "continue", "default", "else", "fallthrough", "for", "guard", "if", "in", "repeat", "switch", "where", "while", "defer", "return", "inout", "mutating", "nonmutating", "isolated", "nonisolated", "catch", "do", "rethrows", "throw", "throws", "async", "await", "try", "didSet", "get", "set", "willSet", "assignment", "associativity", "infix", "left", "none", "operator", "postfix", "precedence", "precedencegroup", "prefix", "right", "Any", "AnyObject", "Type", "dynamicType", "Self", "Protocol", "__COLUMN__", "__FILE__", "__FUNCTION__", "__LINE__"]);
	      var definingKeywords = wordSet(["var", "let", "actor", "class", "enum", "extension", "import", "protocol", "struct", "func", "typealias", "associatedtype", "for"]);
	      var atoms = wordSet(["true", "false", "nil", "self", "super", "_"]);
	      var types = wordSet(["Array", "Bool", "Character", "Dictionary", "Double", "Float", "Int", "Int8", "Int16", "Int32", "Int64", "Never", "Optional", "Set", "String", "UInt8", "UInt16", "UInt32", "UInt64", "Void"]);
	      var operators = "+-/*%=|&<>~^?!";
	      var punc = ":;,.(){}[]";
	      var binary = /^\-?0b[01][01_]*/;
	      var octal = /^\-?0o[0-7][0-7_]*/;
	      var hexadecimal = /^\-?0x[\dA-Fa-f][\dA-Fa-f_]*(?:(?:\.[\dA-Fa-f][\dA-Fa-f_]*)?[Pp]\-?\d[\d_]*)?/;
	      var decimal = /^\-?\d[\d_]*(?:\.\d[\d_]*)?(?:[Ee]\-?\d[\d_]*)?/;
	      var identifier = /^\$\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\1/;
	      var property = /^\.(?:\$\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\1)/;
	      var instruction = /^\#[A-Za-z]+/;
	      var attribute = /^@(?:\$\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\1)/;
	      //var regexp = /^\/(?!\s)(?:\/\/)?(?:\\.|[^\/])+\//

	      function tokenBase(stream, state, prev) {
	        if (stream.sol()) state.indented = stream.indentation();
	        if (stream.eatSpace()) return null;
	        var ch = stream.peek();
	        if (ch == "/") {
	          if (stream.match("//")) {
	            stream.skipToEnd();
	            return "comment";
	          }
	          if (stream.match("/*")) {
	            state.tokenize.push(tokenComment);
	            return tokenComment(stream, state);
	          }
	        }
	        if (stream.match(instruction)) return "builtin";
	        if (stream.match(attribute)) return "attribute";
	        if (stream.match(binary)) return "number";
	        if (stream.match(octal)) return "number";
	        if (stream.match(hexadecimal)) return "number";
	        if (stream.match(decimal)) return "number";
	        if (stream.match(property)) return "property";
	        if (operators.indexOf(ch) > -1) {
	          stream.next();
	          return "operator";
	        }
	        if (punc.indexOf(ch) > -1) {
	          stream.next();
	          stream.match("..");
	          return "punctuation";
	        }
	        var stringMatch;
	        if (stringMatch = stream.match(/("""|"|')/)) {
	          var tokenize = tokenString.bind(null, stringMatch[0]);
	          state.tokenize.push(tokenize);
	          return tokenize(stream, state);
	        }
	        if (stream.match(identifier)) {
	          var ident = stream.current();
	          if (types.hasOwnProperty(ident)) return "variable-2";
	          if (atoms.hasOwnProperty(ident)) return "atom";
	          if (keywords.hasOwnProperty(ident)) {
	            if (definingKeywords.hasOwnProperty(ident)) state.prev = "define";
	            return "keyword";
	          }
	          if (prev == "define") return "def";
	          return "variable";
	        }
	        stream.next();
	        return null;
	      }
	      function tokenUntilClosingParen() {
	        var depth = 0;
	        return function (stream, state, prev) {
	          var inner = tokenBase(stream, state, prev);
	          if (inner == "punctuation") {
	            if (stream.current() == "(") ++depth;else if (stream.current() == ")") {
	              if (depth == 0) {
	                stream.backUp(1);
	                state.tokenize.pop();
	                return state.tokenize[state.tokenize.length - 1](stream, state);
	              } else --depth;
	            }
	          }
	          return inner;
	        };
	      }
	      function tokenString(openQuote, stream, state) {
	        var singleLine = openQuote.length == 1;
	        var ch,
	          escaped = false;
	        while (ch = stream.peek()) {
	          if (escaped) {
	            stream.next();
	            if (ch == "(") {
	              state.tokenize.push(tokenUntilClosingParen());
	              return "string";
	            }
	            escaped = false;
	          } else if (stream.match(openQuote)) {
	            state.tokenize.pop();
	            return "string";
	          } else {
	            stream.next();
	            escaped = ch == "\\";
	          }
	        }
	        if (singleLine) {
	          state.tokenize.pop();
	        }
	        return "string";
	      }
	      function tokenComment(stream, state) {
	        var ch;
	        while (ch = stream.next()) {
	          if (ch === "/" && stream.eat("*")) {
	            state.tokenize.push(tokenComment);
	          } else if (ch === "*" && stream.eat("/")) {
	            state.tokenize.pop();
	            break;
	          }
	        }
	        return "comment";
	      }
	      function Context(prev, align, indented) {
	        this.prev = prev;
	        this.align = align;
	        this.indented = indented;
	      }
	      function pushContext(state, stream) {
	        var align = stream.match(/^\s*($|\/[\/\*])/, false) ? null : stream.column() + 1;
	        state.context = new Context(state.context, align, state.indented);
	      }
	      function popContext(state) {
	        if (state.context) {
	          state.indented = state.context.indented;
	          state.context = state.context.prev;
	        }
	      }
	      CodeMirror.defineMode("swift", function (config) {
	        return {
	          startState: function () {
	            return {
	              prev: null,
	              context: null,
	              indented: 0,
	              tokenize: []
	            };
	          },
	          token: function (stream, state) {
	            var prev = state.prev;
	            state.prev = null;
	            var tokenize = state.tokenize[state.tokenize.length - 1] || tokenBase;
	            var style = tokenize(stream, state, prev);
	            if (!style || style == "comment") state.prev = prev;else if (!state.prev) state.prev = style;
	            if (style == "punctuation") {
	              var bracket = /[\(\[\{]|([\]\)\}])/.exec(stream.current());
	              if (bracket) (bracket[1] ? popContext : pushContext)(state, stream);
	            }
	            return style;
	          },
	          indent: function (state, textAfter) {
	            var cx = state.context;
	            if (!cx) return 0;
	            var closing = /^[\]\}\)]/.test(textAfter);
	            if (cx.align != null) return cx.align - (closing ? 1 : 0);
	            return cx.indented + (closing ? 0 : config.indentUnit);
	          },
	          electricInput: /^\s*[\)\}\]]$/,
	          lineComment: "//",
	          blockCommentStart: "/*",
	          blockCommentEnd: "*/",
	          fold: "brace",
	          closeBrackets: "()[]{}''\"\"``"
	        };
	      });
	      CodeMirror.defineMIME("text/x-swift", "swift");
	    });
	  })();
	  return swift.exports;
	}

	requireSwift();

	requireXml();

	var yaml = {exports: {}};

	var hasRequiredYaml;
	function requireYaml() {
	  if (hasRequiredYaml) return yaml.exports;
	  hasRequiredYaml = 1;
	  (function (module, exports) {
	    // CodeMirror, copyright (c) by Marijn Haverbeke and others
	    // Distributed under an MIT license: https://codemirror.net/5/LICENSE

	    (function (mod) {
	      mod(requireCodemirror());
	    })(function (CodeMirror) {

	      CodeMirror.defineMode("yaml", function () {
	        var cons = ['true', 'false', 'on', 'off', 'yes', 'no'];
	        var keywordRegex = new RegExp("\\b((" + cons.join(")|(") + "))$", 'i');
	        return {
	          token: function (stream, state) {
	            var ch = stream.peek();
	            var esc = state.escaped;
	            state.escaped = false;
	            /* comments */
	            if (ch == "#" && (stream.pos == 0 || /\s/.test(stream.string.charAt(stream.pos - 1)))) {
	              stream.skipToEnd();
	              return "comment";
	            }
	            if (stream.match(/^('([^']|\\.)*'?|"([^"]|\\.)*"?)/)) return "string";
	            if (state.literal && stream.indentation() > state.keyCol) {
	              stream.skipToEnd();
	              return "string";
	            } else if (state.literal) {
	              state.literal = false;
	            }
	            if (stream.sol()) {
	              state.keyCol = 0;
	              state.pair = false;
	              state.pairStart = false;
	              /* document start */
	              if (stream.match('---')) {
	                return "def";
	              }
	              /* document end */
	              if (stream.match('...')) {
	                return "def";
	              }
	              /* array list item */
	              if (stream.match(/\s*-\s+/)) {
	                return 'meta';
	              }
	            }
	            /* inline pairs/lists */
	            if (stream.match(/^(\{|\}|\[|\])/)) {
	              if (ch == '{') state.inlinePairs++;else if (ch == '}') state.inlinePairs--;else if (ch == '[') state.inlineList++;else state.inlineList--;
	              return 'meta';
	            }

	            /* list separator */
	            if (state.inlineList > 0 && !esc && ch == ',') {
	              stream.next();
	              return 'meta';
	            }
	            /* pairs separator */
	            if (state.inlinePairs > 0 && !esc && ch == ',') {
	              state.keyCol = 0;
	              state.pair = false;
	              state.pairStart = false;
	              stream.next();
	              return 'meta';
	            }

	            /* start of value of a pair */
	            if (state.pairStart) {
	              /* block literals */
	              if (stream.match(/^\s*(\||\>)\s*/)) {
	                state.literal = true;
	                return 'meta';
	              }
	              /* references */
	              if (stream.match(/^\s*(\&|\*)[a-z0-9\._-]+\b/i)) {
	                return 'variable-2';
	              }
	              /* numbers */
	              if (state.inlinePairs == 0 && stream.match(/^\s*-?[0-9\.\,]+\s?$/)) {
	                return 'number';
	              }
	              if (state.inlinePairs > 0 && stream.match(/^\s*-?[0-9\.\,]+\s?(?=(,|}))/)) {
	                return 'number';
	              }
	              /* keywords */
	              if (stream.match(keywordRegex)) {
	                return 'keyword';
	              }
	            }

	            /* pairs (associative arrays) -> key */
	            if (!state.pair && stream.match(/^\s*(?:[,\[\]{}&*!|>'"%@`][^\s'":]|[^\s,\[\]{}#&*!|>'"%@`])[^#:]*(?=:($|\s))/)) {
	              state.pair = true;
	              state.keyCol = stream.indentation();
	              return "atom";
	            }
	            if (state.pair && stream.match(/^:\s*/)) {
	              state.pairStart = true;
	              return 'meta';
	            }

	            /* nothing found, continue */
	            state.pairStart = false;
	            state.escaped = ch == '\\';
	            stream.next();
	            return null;
	          },
	          startState: function () {
	            return {
	              pair: false,
	              pairStart: false,
	              keyCol: 0,
	              inlinePairs: 0,
	              inlineList: 0,
	              literal: false,
	              escaped: false
	            };
	          },
	          lineComment: "#",
	          fold: "indent"
	        };
	      });
	      CodeMirror.defineMIME("text/x-yaml", "yaml");
	      CodeMirror.defineMIME("text/yaml", "yaml");
	    });
	  })();
	  return yaml.exports;
	}

	requireYaml();

	// Current version.
	var VERSION = '1.13.8';

	// Establish the root object, `window` (`self`) in the browser, `global`
	// on the server, or `this` in some virtual machines. We use `self`
	// instead of `window` for `WebWorker` support.
	var root = typeof self == 'object' && self.self === self && self || typeof global == 'object' && global.global === global && global || Function('return this')() || {};

	// Save bytes in the minified (but not gzipped) version:
	var ArrayProto = Array.prototype,
	  ObjProto = Object.prototype;
	var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null;

	// Create quick reference variables for speed access to core prototypes.
	var push = ArrayProto.push,
	  slice = ArrayProto.slice,
	  toString = ObjProto.toString,
	  hasOwnProperty = ObjProto.hasOwnProperty;

	// Modern feature detection.
	var supportsArrayBuffer = typeof ArrayBuffer !== 'undefined',
	  supportsDataView = typeof DataView !== 'undefined';

	// All **ECMAScript 5+** native function implementations that we hope to use
	// are declared here.
	var nativeIsArray = Array.isArray,
	  nativeKeys = Object.keys,
	  nativeCreate = Object.create,
	  nativeIsView = supportsArrayBuffer && ArrayBuffer.isView;

	// Create references to these builtin functions because we override them.
	var _isNaN = isNaN,
	  _isFinite = isFinite;

	// 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'];

	// The largest integer that can be represented exactly.
	var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;

	// Some functions take a variable number of arguments, or a few expected
	// arguments at the beginning and then a variable number of values to operate
	// on. This helper accumulates all remaining arguments past the function’s
	// argument length (or an explicit `startIndex`), into an array that becomes
	// the last argument. Similar to ES6’s "rest parameter".
	function restArguments(func, startIndex) {
	  startIndex = startIndex == null ? func.length - 1 : +startIndex;
	  return function () {
	    var length = Math.max(arguments.length - startIndex, 0),
	      rest = Array(length),
	      index = 0;
	    for (; index < length; index++) {
	      rest[index] = arguments[index + startIndex];
	    }
	    switch (startIndex) {
	      case 0:
	        return func.call(this, rest);
	      case 1:
	        return func.call(this, arguments[0], rest);
	      case 2:
	        return func.call(this, arguments[0], arguments[1], rest);
	    }
	    var args = Array(startIndex + 1);
	    for (index = 0; index < startIndex; index++) {
	      args[index] = arguments[index];
	    }
	    args[startIndex] = rest;
	    return func.apply(this, args);
	  };
	}

	// Is a given variable an object?
	function isObject(obj) {
	  var type = typeof obj;
	  return type === 'function' || type === 'object' && !!obj;
	}

	// Is a given value equal to null?
	function isNull(obj) {
	  return obj === null;
	}

	// Is a given variable undefined?
	function isUndefined(obj) {
	  return obj === void 0;
	}

	// Is a given value a boolean?
	function isBoolean(obj) {
	  return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
	}

	// Is a given value a DOM element?
	function isElement(obj) {
	  return !!(obj && obj.nodeType === 1);
	}

	// Internal function for creating a `toString`-based type tester.
	function tagTester(name) {
	  var tag = '[object ' + name + ']';
	  return function (obj) {
	    return toString.call(obj) === tag;
	  };
	}

	const isString = tagTester('String');

	const isNumber = tagTester('Number');

	const isDate = tagTester('Date');

	const isRegExp = tagTester('RegExp');

	const isError = tagTester('Error');

	const isSymbol = tagTester('Symbol');

	const isArrayBuffer = tagTester('ArrayBuffer');

	var isFunction = tagTester('Function');

	// Optimize `isFunction` if appropriate. Work around some `typeof` bugs in old
	// v8, IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236).
	var nodelist = root.document && root.document.childNodes;
	if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') {
	  isFunction = function (obj) {
	    return typeof obj == 'function' || false;
	  };
	}
	const isFunction$1 = isFunction;

	const hasObjectTag = tagTester('Object');

	// In IE 10 - Edge 13, `DataView` has string tag `'[object Object]'`.
	// In IE 11, the most common among them, this problem also applies to
	// `Map`, `WeakMap` and `Set`.
	// Also, there are cases where an application can override the native
	// `DataView` object, in cases like that we can't use the constructor
	// safely and should just rely on alternate `DataView` checks
	var hasDataViewBug = supportsDataView && (!/\[native code\]/.test(String(DataView)) || hasObjectTag(new DataView(new ArrayBuffer(8)))),
	  isIE11 = typeof Map !== 'undefined' && hasObjectTag(new Map());

	var isDataView = tagTester('DataView');

	// In IE 10 - Edge 13, we need a different heuristic
	// to determine whether an object is a `DataView`.
	// Also, in cases where the native `DataView` is
	// overridden we can't rely on the tag itself.
	function alternateIsDataView(obj) {
	  return obj != null && isFunction$1(obj.getInt8) && isArrayBuffer(obj.buffer);
	}
	const isDataView$1 = hasDataViewBug ? alternateIsDataView : isDataView;

	// Is a given value an array?
	// Delegates to ECMA5's native `Array.isArray`.
	const isArray = nativeIsArray || tagTester('Array');

	// Internal function to check whether `key` is an own property name of `obj`.
	function has$1(obj, key) {
	  return obj != null && hasOwnProperty.call(obj, key);
	}

	var isArguments = tagTester('Arguments');

	// Define a fallback version of the method in browsers (ahem, IE < 9), where
	// there isn't any inspectable "Arguments" type.
	(function () {
	  if (!isArguments(arguments)) {
	    isArguments = function (obj) {
	      return has$1(obj, 'callee');
	    };
	  }
	})();
	const isArguments$1 = isArguments;

	// Is a given object a finite number?
	function isFinite$1(obj) {
	  return !isSymbol(obj) && _isFinite(obj) && !isNaN(parseFloat(obj));
	}

	// Is the given value `NaN`?
	function isNaN$1(obj) {
	  return isNumber(obj) && _isNaN(obj);
	}

	// Predicate-generating function. Often useful outside of Underscore.
	function constant(value) {
	  return function () {
	    return value;
	  };
	}

	// Common internal logic for `isArrayLike` and `isBufferLike`.
	function createSizePropertyCheck(getSizeProperty) {
	  return function (collection) {
	    var sizeProperty = getSizeProperty(collection);
	    return typeof sizeProperty == 'number' && sizeProperty >= 0 && sizeProperty <= MAX_ARRAY_INDEX;
	  };
	}

	// Internal helper to generate a function to obtain property `key` from `obj`.
	function shallowProperty(key) {
	  return function (obj) {
	    return obj == null ? void 0 : obj[key];
	  };
	}

	// Internal helper to obtain the `byteLength` property of an object.
	const getByteLength = shallowProperty('byteLength');

	// Internal helper to determine whether we should spend extensive checks against
	// `ArrayBuffer` et al.
	const isBufferLike = createSizePropertyCheck(getByteLength);

	// Is a given value a typed array?
	var typedArrayPattern = /\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;
	function isTypedArray(obj) {
	  // `ArrayBuffer.isView` is the most future-proof, so use it when available.
	  // Otherwise, fall back on the above regular expression.
	  return nativeIsView ? nativeIsView(obj) && !isDataView$1(obj) : isBufferLike(obj) && typedArrayPattern.test(toString.call(obj));
	}
	const isTypedArray$1 = supportsArrayBuffer ? isTypedArray : constant(false);

	// Internal helper to obtain the `length` property of an object.
	const getLength = shallowProperty('length');

	// Internal helper to create a simple lookup structure.
	// `collectNonEnumProps` used to depend on `_.contains`, but this led to
	// circular imports. `emulatedSet` is a one-off solution that only works for
	// arrays of strings.
	function emulatedSet(keys) {
	  var hash = {};
	  for (var l = keys.length, i = 0; i < l; ++i) hash[keys[i]] = true;
	  return {
	    contains: function (key) {
	      return hash[key] === true;
	    },
	    push: function (key) {
	      hash[key] = true;
	      return keys.push(key);
	    }
	  };
	}

	// Internal helper. Checks `keys` for the presence of keys in IE < 9 that won't
	// be iterated by `for key in ...` and thus missed. Extends `keys` in place if
	// needed.
	function collectNonEnumProps(obj, keys) {
	  keys = emulatedSet(keys);
	  var nonEnumIdx = nonEnumerableProps.length;
	  var constructor = obj.constructor;
	  var proto = isFunction$1(constructor) && constructor.prototype || ObjProto;

	  // Constructor is a special case.
	  var prop = 'constructor';
	  if (has$1(obj, prop) && !keys.contains(prop)) keys.push(prop);
	  while (nonEnumIdx--) {
	    prop = nonEnumerableProps[nonEnumIdx];
	    if (prop in obj && obj[prop] !== proto[prop] && !keys.contains(prop)) {
	      keys.push(prop);
	    }
	  }
	}

	// Retrieve the names of an object's own properties.
	// Delegates to **ECMAScript 5**'s native `Object.keys`.
	function keys(obj) {
	  if (!isObject(obj)) return [];
	  if (nativeKeys) return nativeKeys(obj);
	  var keys = [];
	  for (var key in obj) if (has$1(obj, key)) keys.push(key);
	  // Ahem, IE < 9.
	  if (hasEnumBug) collectNonEnumProps(obj, keys);
	  return keys;
	}

	// Is a given array, string, or object empty?
	// An "empty" object has no enumerable own-properties.
	function isEmpty(obj) {
	  if (obj == null) return true;
	  // Skip the more expensive `toString`-based type checks if `obj` has no
	  // `.length`.
	  var length = getLength(obj);
	  if (typeof length == 'number' && (isArray(obj) || isString(obj) || isArguments$1(obj))) return length === 0;
	  return getLength(keys(obj)) === 0;
	}

	// Returns whether an object has a given set of `key:value` pairs.
	function isMatch(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;
	}

	// 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 functions added
	// through `_.mixin`. Wrapped objects may be chained.
	function _$1(obj) {
	  if (obj instanceof _$1) return obj;
	  if (!(this instanceof _$1)) return new _$1(obj);
	  this._wrapped = obj;
	}
	_$1.VERSION = VERSION;

	// Extracts the result from a wrapped and chained object.
	_$1.prototype.value = function () {
	  return this._wrapped;
	};

	// Provide unwrapping proxies for some methods used in engine operations
	// such as arithmetic and JSON stringification.
	_$1.prototype.valueOf = _$1.prototype.toJSON = _$1.prototype.value;
	_$1.prototype.toString = function () {
	  return String(this._wrapped);
	};

	// Internal function to wrap or shallow-copy an ArrayBuffer,
	// typed array or DataView to a new view, reusing the buffer.
	function toBufferView(bufferSource) {
	  return new Uint8Array(bufferSource.buffer || bufferSource, bufferSource.byteOffset || 0, getByteLength(bufferSource));
	}

	// We use this string twice, so give it a name for minification.
	var tagDataView = '[object DataView]';

	// Perform a deep comparison to check if two objects are equal.
	function isEqual(a, b) {
	  var todo = [{
	    a: a,
	    b: b
	  }];
	  // Initializing stacks of traversed objects for cycle detection.
	  var aStack = [],
	    bStack = [];
	  while (todo.length) {
	    var frame = todo.pop();
	    if (frame === true) {
	      // Remove the first object from the stack of traversed objects.
	      aStack.pop();
	      bStack.pop();
	      continue;
	    }
	    a = frame.a;
	    b = frame.b;

	    // Identical objects are equal. `0 === -0`, but they aren't identical.
	    // See the [Harmony `egal` proposal](https://wiki.ecmascript.org/doku.php?id=harmony:egal).
	    if (a === b) {
	      if (a !== 0 || 1 / a === 1 / b) continue;
	      return false;
	    }
	    // `null` or `undefined` only equal to itself (strict comparison).
	    if (a == null || b == null) return false;
	    // `NaN`s are equivalent, but non-reflexive.
	    if (a !== a) {
	      if (b !== b) continue;
	      return false;
	    }
	    // Exhaust primitive checks
	    var type = typeof a;
	    if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;

	    // Internal recursive comparison function for `_.isEqual`.
	    // Unwrap any wrapped objects.
	    if (a instanceof _$1) a = a._wrapped;
	    if (b instanceof _$1) b = b._wrapped;
	    // Compare `[[Class]]` names.
	    var className = toString.call(a);
	    if (className !== toString.call(b)) return false;
	    // Work around a bug in IE 10 - Edge 13.
	    if (hasDataViewBug && className == '[object Object]' && isDataView$1(a)) {
	      if (!isDataView$1(b)) return false;
	      className = tagDataView;
	    }
	    switch (className) {
	      // These types 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")`.
	        if ('' + a === '' + b) continue;
	        return false;
	      case '[object Number]':
	        todo.push({
	          a: +a,
	          b: +b
	        });
	        continue;
	      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.
	        if (+a === +b) continue;
	        return false;
	      case '[object Symbol]':
	        if (SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b)) continue;
	        return false;
	      case '[object ArrayBuffer]':
	      case tagDataView:
	        // Coerce to typed array so we can fall through.
	        todo.push({
	          a: toBufferView(a),
	          b: toBufferView(b)
	        });
	        continue;
	    }
	    var areArrays = className === '[object Array]';
	    if (!areArrays && isTypedArray$1(a)) {
	      var byteLength = getByteLength(a);
	      if (byteLength !== getByteLength(b)) return false;
	      if (a.buffer === b.buffer && a.byteOffset === b.byteOffset) continue;
	      areArrays = true;
	    }
	    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$1(aCtor) && aCtor instanceof aCtor && isFunction$1(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`.

	    var length = aStack.length;
	    while (length--) {
	      // Linear search. Performance is inversely proportional to the number of
	      // unique nested structures.
	      if (aStack[length] === a) {
	        if (bStack[length] === b) break;
	        return false;
	      }
	    }
	    if (length >= 0) continue;

	    // Add the first object to the stack of traversed objects.
	    aStack.push(a);
	    bStack.push(b);
	    todo.push(true);

	    // 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--) {
	        todo.push({
	          a: a[length],
	          b: b[length]
	        });
	      }
	    } 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$1(b, key)) return false;
	        todo.push({
	          a: a[key],
	          b: b[key]
	        });
	      }
	    }
	  }
	  return true;
	}

	// Retrieve all the enumerable property names of an object.
	function allKeys(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;
	}

	// Since the regular `Object.prototype.toString` type tests don't work for
	// some types in IE 11, we use a fingerprinting heuristic instead, based
	// on the methods. It's not great, but it's the best we got.
	// The fingerprint method lists are defined below.
	function ie11fingerprint(methods) {
	  var length = getLength(methods);
	  return function (obj) {
	    if (obj == null) return false;
	    // `Map`, `WeakMap` and `Set` have no enumerable keys.
	    var keys = allKeys(obj);
	    if (getLength(keys)) return false;
	    for (var i = 0; i < length; i++) {
	      if (!isFunction$1(obj[methods[i]])) return false;
	    }
	    // If we are testing against `WeakMap`, we need to ensure that
	    // `obj` doesn't have a `forEach` method in order to distinguish
	    // it from a regular `Map`.
	    return methods !== weakMapMethods || !isFunction$1(obj[forEachName]);
	  };
	}

	// In the interest of compact minification, we write
	// each string in the fingerprints only once.
	var forEachName = 'forEach',
	  hasName = 'has',
	  commonInit = ['clear', 'delete'],
	  mapTail = ['get', hasName, 'set'];

	// `Map`, `WeakMap` and `Set` each have slightly different
	// combinations of the above sublists.
	var mapMethods = commonInit.concat(forEachName, mapTail),
	  weakMapMethods = commonInit.concat(mapTail),
	  setMethods = ['add'].concat(commonInit, forEachName, hasName);

	const isMap = isIE11 ? ie11fingerprint(mapMethods) : tagTester('Map');

	const isWeakMap = isIE11 ? ie11fingerprint(weakMapMethods) : tagTester('WeakMap');

	const isSet = isIE11 ? ie11fingerprint(setMethods) : tagTester('Set');

	const isWeakSet = tagTester('WeakSet');

	// Retrieve the values of an object's properties.
	function values(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;
	}

	// Convert an object into a list of `[key, value]` pairs.
	// The opposite of `_.object` with one argument.
	function pairs(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.
	function invert(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.
	function functions(obj) {
	  var names = [];
	  for (var key in obj) {
	    if (isFunction$1(obj[key])) names.push(key);
	  }
	  return names.sort();
	}

	// An internal function for creating assigner functions.
	function createAssigner(keysFunc, defaults) {
	  return function (obj) {
	    var length = arguments.length;
	    if (defaults) obj = Object(obj);
	    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 (!defaults || obj[key] === void 0) obj[key] = source[key];
	      }
	    }
	    return obj;
	  };
	}

	// Extend a given object with all the properties in passed-in object(s).
	const 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)
	const extendOwn = createAssigner(keys);

	// Fill in a given object with default properties.
	const defaults = createAssigner(allKeys, true);

	// Create a naked function reference for surrogate-prototype-swapping.
	function ctor() {
	  return function () {};
	}

	// An internal function for creating a new object that inherits from another.
	function baseCreate(prototype) {
	  if (!isObject(prototype)) return {};
	  if (nativeCreate) return nativeCreate(prototype);
	  var Ctor = ctor();
	  Ctor.prototype = prototype;
	  var result = new Ctor();
	  Ctor.prototype = null;
	  return result;
	}

	// Creates an object that inherits from the given prototype object.
	// If additional properties are provided then they will be added to the
	// created object.
	function create(prototype, props) {
	  var result = baseCreate(prototype);
	  if (props) extendOwn(result, props);
	  return result;
	}

	// Create a (shallow-cloned) duplicate of an object.
	function clone(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.
	function tap(obj, interceptor) {
	  interceptor(obj);
	  return obj;
	}

	// Normalize a (deep) property `path` to array.
	// Like `_.iteratee`, this function can be customized.
	function toPath$1(path) {
	  return isArray(path) ? path : [path];
	}
	_$1.toPath = toPath$1;

	// Internal wrapper for `_.toPath` to enable minification.
	// Similar to `cb` for `_.iteratee`.
	function toPath(path) {
	  return _$1.toPath(path);
	}

	// Internal function to obtain a nested property in `obj` along `path`.
	function deepGet(obj, path) {
	  var length = path.length;
	  for (var i = 0; i < length; i++) {
	    if (obj == null) return void 0;
	    obj = obj[path[i]];
	  }
	  return length ? obj : void 0;
	}

	// Get the value of the (deep) property on `path` from `object`.
	// If any property in `path` does not exist or if the value is
	// `undefined`, return `defaultValue` instead.
	// The `path` is normalized through `_.toPath`.
	function get(object, path, defaultValue) {
	  var value = deepGet(object, toPath(path));
	  return isUndefined(value) ? defaultValue : value;
	}

	// Shortcut function for checking if an object has a given property directly on
	// itself (in other words, not on a prototype). Unlike the internal `has`
	// function, this public version can also traverse nested properties.
	function has(obj, path) {
	  path = toPath(path);
	  var length = path.length;
	  for (var i = 0; i < length; i++) {
	    var key = path[i];
	    if (!has$1(obj, key)) return false;
	    obj = obj[key];
	  }
	  return !!length;
	}

	// Keep the identity function around for default iteratees.
	function identity(value) {
	  return value;
	}

	// Returns a predicate for checking whether an object has a given set of
	// `key:value` pairs.
	function matcher(attrs) {
	  attrs = extendOwn({}, attrs);
	  return function (obj) {
	    return isMatch(obj, attrs);
	  };
	}

	// Creates a function that, when passed an object, will traverse that object’s
	// properties down the given `path`, specified as an array of keys or indices.
	function property(path) {
	  path = toPath(path);
	  return function (obj) {
	    return deepGet(obj, path);
	  };
	}

	// Internal function that returns an efficient (for current engines) version
	// of the passed-in callback, to be repeatedly applied in other Underscore
	// functions.
	function optimizeCb(func, context, argCount) {
	  if (context === void 0) return func;
	  switch (argCount == null ? 3 : argCount) {
	    case 1:
	      return function (value) {
	        return func.call(context, value);
	      };
	    // The 2-argument case is omitted because we’re not using it.
	    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);
	  };
	}

	// An 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.
	function baseIteratee(value, context, argCount) {
	  if (value == null) return identity;
	  if (isFunction$1(value)) return optimizeCb(value, context, argCount);
	  if (isObject(value) && !isArray(value)) return matcher(value);
	  return property(value);
	}

	// External wrapper for our callback generator. Users may customize
	// `_.iteratee` if they want additional predicate/iteratee shorthand styles.
	// This abstraction hides the internal-only `argCount` argument.
	function iteratee(value, context) {
	  return baseIteratee(value, context, Infinity);
	}
	_$1.iteratee = iteratee;

	// The function we call internally to generate a callback. It invokes
	// `_.iteratee` if overridden, otherwise `baseIteratee`.
	function cb(value, context, argCount) {
	  if (_$1.iteratee !== iteratee) return _$1.iteratee(value, context);
	  return baseIteratee(value, context, argCount);
	}

	// Returns the results of applying the `iteratee` to each element of `obj`.
	// In contrast to `_.map` it returns an object.
	function mapObject(obj, iteratee, context) {
	  iteratee = cb(iteratee, context);
	  var _keys = keys(obj),
	    length = _keys.length,
	    results = {};
	  for (var index = 0; index < length; index++) {
	    var currentKey = _keys[index];
	    results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
	  }
	  return results;
	}

	// Predicate-generating function. Often useful outside of Underscore.
	function noop() {}

	// Generates a function for a given object that returns a given property.
	function propertyOf(obj) {
	  if (obj == null) return noop;
	  return function (path) {
	    return get(obj, path);
	  };
	}

	// Run a function **n** times.
	function times(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).
	function random(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.
	const now = Date.now || function () {
	  return new Date().getTime();
	};

	// Internal helper to generate functions for escaping and unescaping strings
	// to/from HTML interpolation.
	function createEscaper(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;
	  };
	}

	// Internal list of HTML entities for escaping.
	const escapeMap = {
	  '&': '&amp;',
	  '<': '&lt;',
	  '>': '&gt;',
	  '"': '&quot;',
	  "'": '&#x27;',
	  '`': '&#x60;'
	};

	// Function for escaping strings to HTML interpolation.
	const escape = createEscaper(escapeMap);

	// Internal list of HTML entities for unescaping.
	const unescapeMap = invert(escapeMap);

	// Function for unescaping strings from HTML interpolation.
	const unescape = createEscaper(unescapeMap);

	// By default, Underscore uses ERB-style template delimiters. Change the
	// following template settings to use alternative delimiters.
	const templateSettings = _$1.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 escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;
	function escapeChar(match) {
	  return '\\' + escapes[match];
	}

	// In order to prevent third-party code injection through
	// `_.templateSettings.variable`, we test it against the following regular
	// expression. It is intentionally a bit more liberal than just matching valid
	// identifiers, but still prevents possible loopholes through defaults or
	// destructuring assignment.
	var bareIdentifier = /^\s*(\w|\$)+\s*$/;

	// 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.
	function template(text, settings, oldSettings) {
	  if (!settings && oldSettings) settings = oldSettings;
	  settings = defaults({}, settings, _$1.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(escapeRegExp, 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 offset.
	    return match;
	  });
	  source += "';\n";
	  var argument = settings.variable;
	  if (argument) {
	    // Insure against third-party code injection. (CVE-2021-23358)
	    if (!bareIdentifier.test(argument)) throw new Error('variable is not a bare identifier: ' + argument);
	  } else {
	    // If a variable is not specified, place data values in local scope.
	    source = 'with(obj||{}){\n' + source + '}\n';
	    argument = 'obj';
	  }
	  source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n';
	  var render;
	  try {
	    render = new Function(argument, '_', source);
	  } catch (e) {
	    e.source = source;
	    throw e;
	  }
	  var template = function (data) {
	    return render.call(this, data, _$1);
	  };

	  // Provide the compiled source as a convenience for precompilation.
	  template.source = 'function(' + argument + '){\n' + source + '}';
	  return template;
	}

	// Traverses the children of `obj` along `path`. If a child is a function, it
	// is invoked with its parent as context. Returns the value of the final
	// child, or `fallback` if any child is undefined.
	function result(obj, path, fallback) {
	  path = toPath(path);
	  var length = path.length;
	  if (!length) {
	    return isFunction$1(fallback) ? fallback.call(obj) : fallback;
	  }
	  for (var i = 0; i < length; i++) {
	    var prop = obj == null ? void 0 : obj[path[i]];
	    if (prop === void 0) {
	      prop = fallback;
	      i = length; // Ensure we don't continue iterating.
	    }
	    obj = isFunction$1(prop) ? prop.call(obj) : prop;
	  }
	  return obj;
	}

	// Generate a unique integer id (unique within the entire client session).
	// Useful for temporary DOM ids.
	var idCounter = 0;
	function uniqueId(prefix) {
	  var id = ++idCounter + '';
	  return prefix ? prefix + id : id;
	}

	// Start chaining a wrapped Underscore object.
	function chain(obj) {
	  var instance = _$1(obj);
	  instance._chain = true;
	  return instance;
	}

	// Internal function to execute `sourceFunc` bound to `context` with optional
	// `args`. Determines whether to execute a function as a constructor or as a
	// normal function.
	function executeBound(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;
	}

	// 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 by default, allowing any combination of arguments to be
	// pre-filled. Set `_.partial.placeholder` for a custom placeholder argument.
	var partial = restArguments(function (func, boundArgs) {
	  var placeholder = partial.placeholder;
	  var bound = function () {
	    var position = 0,
	      length = boundArgs.length;
	    var args = Array(length);
	    for (var i = 0; i < length; i++) {
	      args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i];
	    }
	    while (position < arguments.length) args.push(arguments[position++]);
	    return executeBound(func, bound, this, this, args);
	  };
	  return bound;
	});
	partial.placeholder = _$1;

	// Create a function bound to a given object (assigning `this`, and arguments,
	// optionally).
	const bind = restArguments(function (func, context, args) {
	  if (!isFunction$1(func)) throw new TypeError('Bind must be called on a function');
	  var bound = restArguments(function (callArgs) {
	    return executeBound(func, bound, context, this, args.concat(callArgs));
	  });
	  return bound;
	});

	// Internal helper for collection methods to determine whether a collection
	// should be iterated as an array or as an object.
	// Related: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
	// Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
	const isArrayLike = createSizePropertyCheck(getLength);

	// Internal implementation of a recursive `flatten` function.
	function flatten$1(input, depth, strict) {
	  if (!depth && depth !== 0) depth = Infinity;
	  var output = [],
	    idx = 0,
	    i = 0,
	    length = getLength(input) || 0,
	    stack = [];
	  while (true) {
	    if (i >= length) {
	      if (!stack.length) break;
	      var frame = stack.pop();
	      i = frame.i;
	      input = frame.v;
	      length = getLength(input);
	      continue;
	    }
	    var value = input[i++];
	    if (stack.length >= depth) {
	      output[idx++] = value;
	    } else if (isArrayLike(value) && (isArray(value) || isArguments$1(value))) {
	      // Flatten current level of array or arguments object.
	      stack.push({
	        i: i,
	        v: input
	      });
	      i = 0;
	      input = value;
	      length = getLength(input);
	    } else if (!strict) {
	      output[idx++] = value;
	    }
	  }
	  return output;
	}

	// 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.
	const bindAll = restArguments(function (obj, keys) {
	  keys = flatten$1(keys, false, false);
	  var index = keys.length;
	  if (index < 1) throw new Error('bindAll must be passed function names');
	  while (index--) {
	    var key = keys[index];
	    obj[key] = bind(obj[key], obj);
	  }
	  return obj;
	});

	// Memoize an expensive function by storing its results.
	function memoize(func, hasher) {
	  var memoize = function (key) {
	    var cache = memoize.cache;
	    var address = '' + (hasher ? hasher.apply(this, arguments) : key);
	    if (!has$1(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.
	const delay = restArguments(function (func, wait, args) {
	  return setTimeout(function () {
	    return func.apply(null, args);
	  }, wait);
	});

	// Defers a function, scheduling it to run after the current call stack has
	// cleared.
	const defer = partial(delay, _$1, 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.
	function throttle(func, wait, options) {
	  var timeout, context, args, result;
	  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;
	  };
	  var throttled = 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;
	  };
	  throttled.cancel = function () {
	    clearTimeout(timeout);
	    previous = 0;
	    timeout = context = args = null;
	  };
	  return throttled;
	}

	// When a sequence of calls of the returned function ends, the argument
	// function is triggered. The end of a sequence is defined by the `wait`
	// parameter. If `immediate` is passed, the argument function will be
	// triggered at the beginning of the sequence instead of at the end.
	function debounce(func, wait, immediate) {
	  var timeout, previous, args, result, context;
	  var later = function () {
	    var passed = now() - previous;
	    if (wait > passed) {
	      timeout = setTimeout(later, wait - passed);
	    } else {
	      timeout = null;
	      if (!immediate) result = func.apply(context, args);
	      // This check is needed because `func` can recursively invoke `debounced`.
	      if (!timeout) args = context = null;
	    }
	  };
	  var debounced = restArguments(function (_args) {
	    context = this;
	    args = _args;
	    previous = now();
	    if (!timeout) {
	      timeout = setTimeout(later, wait);
	      if (immediate) result = func.apply(context, args);
	    }
	    return result;
	  });
	  debounced.cancel = function () {
	    clearTimeout(timeout);
	    timeout = args = context = null;
	  };
	  return debounced;
	}

	// 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.
	function wrap(func, wrapper) {
	  return partial(wrapper, func);
	}

	// Returns a negated version of the passed-in predicate.
	function negate(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.
	function compose() {
	  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.
	function after(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.
	function before(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.
	const once = partial(before, 2);

	// Returns the first key on an object that passes a truth test.
	function findKey(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;
	  }
	}

	// Internal function to generate `_.findIndex` and `_.findLastIndex`.
	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 truth test.
	const findIndex = createPredicateIndexFinder(1);

	// Returns the last index on an array-like that passes a truth test.
	const 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.
	function sortedIndex(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;
	}

	// Internal function to generate 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$1);
	      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.
	const indexOf = createIndexFinder(1, findIndex, sortedIndex);

	// Return the position of the last occurrence of an item in an array,
	// or -1 if the item is not included in the array.
	const lastIndexOf = createIndexFinder(-1, findLastIndex);

	// Return the first value which passes a truth test.
	function find(obj, predicate, context) {
	  var keyFinder = isArrayLike(obj) ? findIndex : findKey;
	  var key = keyFinder(obj, predicate, context);
	  if (key !== void 0 && key !== -1) return obj[key];
	}

	// Convenience version of a common use case of `_.find`: getting the first
	// object containing specific `key:value` pairs.
	function findWhere(obj, attrs) {
	  return find(obj, matcher(attrs));
	}

	// The cornerstone for collection functions, an `each`
	// implementation, aka `forEach`.
	// Handles raw objects in addition to array-likes. Treats all
	// sparse array-likes as if they were dense.
	function each(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.
	function map(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;
	}

	// Internal helper to create a reducing function, iterating left or right.
	function createReduce(dir) {
	  // Wrap code that reassigns argument variables in a separate function than
	  // the one that accesses `arguments.length` to avoid a perf hit. (#1991)
	  var reducer = function (obj, iteratee, memo, initial) {
	    var _keys = !isArrayLike(obj) && keys(obj),
	      length = (_keys || obj).length,
	      index = dir > 0 ? 0 : length - 1;
	    if (!initial) {
	      memo = obj[_keys ? _keys[index] : index];
	      index += dir;
	    }
	    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) {
	    var initial = arguments.length >= 3;
	    return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
	  };
	}

	// **Reduce** builds up a single result from a list of values, aka `inject`,
	// or `foldl`.
	const reduce = createReduce(1);

	// The right-associative version of reduce, also known as `foldr`.
	const reduceRight = createReduce(-1);

	// Return all the elements that pass a truth test.
	function filter(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.
	function reject(obj, predicate, context) {
	  return filter(obj, negate(cb(predicate)), context);
	}

	// Determine whether all of the elements pass a truth test.
	function every(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 passes a truth test.
	function some(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 `===`).
	function contains(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.
	const invoke = restArguments(function (obj, path, args) {
	  var contextPath, func;
	  if (isFunction$1(path)) {
	    func = path;
	  } else {
	    path = toPath(path);
	    contextPath = path.slice(0, -1);
	    path = path[path.length - 1];
	  }
	  return map(obj, function (context) {
	    var method = func;
	    if (!method) {
	      if (contextPath && contextPath.length) {
	        context = deepGet(context, contextPath);
	      }
	      if (context == null) return void 0;
	      method = context[path];
	    }
	    return method == null ? method : method.apply(context, args);
	  });
	});

	// Convenience version of a common use case of `_.map`: fetching a property.
	function pluck(obj, key) {
	  return map(obj, property(key));
	}

	// Convenience version of a common use case of `_.filter`: selecting only
	// objects containing specific `key:value` pairs.
	function where(obj, attrs) {
	  return filter(obj, matcher(attrs));
	}

	// Return the maximum element (or element-based computation).
	function max(obj, iteratee, context) {
	  var result = -Infinity,
	    lastComputed = -Infinity,
	    value,
	    computed;
	  if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
	    obj = isArrayLike(obj) ? obj : values(obj);
	    for (var i = 0, length = obj.length; i < length; i++) {
	      value = obj[i];
	      if (value != null && value > result) {
	        result = value;
	      }
	    }
	  } else {
	    iteratee = cb(iteratee, context);
	    each(obj, function (v, index, list) {
	      computed = iteratee(v, index, list);
	      if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
	        result = v;
	        lastComputed = computed;
	      }
	    });
	  }
	  return result;
	}

	// Return the minimum element (or element-based computation).
	function min(obj, iteratee, context) {
	  var result = Infinity,
	    lastComputed = Infinity,
	    value,
	    computed;
	  if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
	    obj = isArrayLike(obj) ? obj : values(obj);
	    for (var i = 0, length = obj.length; i < length; i++) {
	      value = obj[i];
	      if (value != null && value < result) {
	        result = value;
	      }
	    }
	  } else {
	    iteratee = cb(iteratee, context);
	    each(obj, function (v, index, list) {
	      computed = iteratee(v, index, list);
	      if (computed < lastComputed || computed === Infinity && result === Infinity) {
	        result = v;
	        lastComputed = computed;
	      }
	    });
	  }
	  return result;
	}

	// Safely create a real, live array from anything iterable.
	var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
	function toArray(obj) {
	  if (!obj) return [];
	  if (isArray(obj)) return slice.call(obj);
	  if (isString(obj)) {
	    // Keep surrogate pair characters together.
	    return obj.match(reStrSymbol);
	  }
	  if (isArrayLike(obj)) return map(obj, identity);
	  return values(obj);
	}

	// Sample **n** random values from a collection using the modern version of the
	// [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
	// If **n** is not specified, returns a single random element.
	// The internal `guard` argument allows it to work with `_.map`.
	function sample(obj, n, guard) {
	  if (n == null || guard) {
	    if (!isArrayLike(obj)) obj = values(obj);
	    return obj[random(obj.length - 1)];
	  }
	  var sample = toArray(obj);
	  var length = getLength(sample);
	  n = Math.max(Math.min(n, length), 0);
	  var last = length - 1;
	  for (var index = 0; index < n; index++) {
	    var rand = random(index, last);
	    var temp = sample[index];
	    sample[index] = sample[rand];
	    sample[rand] = temp;
	  }
	  return sample.slice(0, n);
	}

	// Shuffle a collection.
	function shuffle(obj) {
	  return sample(obj, Infinity);
	}

	// Sort the object's values by a criterion produced by an iteratee.
	function sortBy(obj, iteratee, context) {
	  var index = 0;
	  iteratee = cb(iteratee, context);
	  return pluck(map(obj, function (value, key, list) {
	    return {
	      value: value,
	      index: index++,
	      criteria: iteratee(value, key, 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.
	function group(behavior, partition) {
	  return function (obj, iteratee, context) {
	    var result = partition ? [[], []] : {};
	    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.
	const groupBy = group(function (result, value, key) {
	  if (has$1(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.
	const 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.
	const countBy = group(function (result, value, key) {
	  if (has$1(result, key)) result[key]++;else result[key] = 1;
	});

	// Split a collection into two arrays: one whose elements all pass the given
	// truth test, and one whose elements all do not pass the truth test.
	const partition = group(function (result, value, pass) {
	  result[pass ? 0 : 1].push(value);
	}, true);

	// Return the number of elements in a collection.
	function size(obj) {
	  if (obj == null) return 0;
	  return isArrayLike(obj) ? obj.length : keys(obj).length;
	}

	// Internal `_.pick` helper function to determine whether `key` is an enumerable
	// property name of `obj`.
	function keyInObj(value, key, obj) {
	  return key in obj;
	}

	// Return a copy of the object only containing the allowed properties.
	const pick = restArguments(function (obj, keys) {
	  var result = {},
	    iteratee = keys[0];
	  if (obj == null) return result;
	  if (isFunction$1(iteratee)) {
	    if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]);
	    keys = allKeys(obj);
	  } else {
	    iteratee = keyInObj;
	    keys = flatten$1(keys, false, false);
	    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 disallowed properties.
	const omit = restArguments(function (obj, keys) {
	  var iteratee = keys[0],
	    context;
	  if (isFunction$1(iteratee)) {
	    iteratee = negate(iteratee);
	    if (keys.length > 1) context = keys[1];
	  } else {
	    keys = map(flatten$1(keys, false, false), String);
	    iteratee = function (value, key) {
	      return !contains(keys, key);
	    };
	  }
	  return pick(obj, iteratee, context);
	});

	// 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.
	function initial(array, n, guard) {
	  return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
	}

	// Get the first element of an array. Passing **n** will return the first N
	// values in the array. The **guard** check allows it to work with `_.map`.
	function first(array, n, guard) {
	  if (array == null || array.length < 1) return n == null || guard ? void 0 : [];
	  if (n == null || guard) return array[0];
	  return initial(array, array.length - n);
	}

	// Returns everything but the first entry of the `array`. Especially useful on
	// the `arguments` object. Passing an **n** will return the rest N values in the
	// `array`.
	function rest(array, n, guard) {
	  return slice.call(array, n == null || guard ? 1 : n);
	}

	// Get the last element of an array. Passing **n** will return the last N
	// values in the array.
	function last(array, n, guard) {
	  if (array == null || array.length < 1) return n == null || guard ? void 0 : [];
	  if (n == null || guard) return array[array.length - 1];
	  return rest(array, Math.max(0, array.length - n));
	}

	// Trim out all falsy values from an array.
	function compact(array) {
	  return filter(array, Boolean);
	}

	// Flatten out an array, either recursively (by default), or up to `depth`.
	// Passing `true` or `false` as `depth` means `1` or `Infinity`, respectively.
	function flatten(array, depth) {
	  return flatten$1(array, depth, false);
	}

	// Take the difference between one array and a number of other arrays.
	// Only the elements present in just the first array will remain.
	const difference = restArguments(function (array, rest) {
	  rest = flatten$1(rest, true, true);
	  return filter(array, function (value) {
	    return !contains(rest, value);
	  });
	});

	// Return a version of the array that does not contain the specified value(s).
	const without = restArguments(function (array, otherArrays) {
	  return difference(array, otherArrays);
	});

	// Produce a duplicate-free version of the array. If the array has already
	// been sorted, you have the option of using a faster algorithm.
	// The faster algorithm will not work with an iteratee if the iteratee
	// is not a one-to-one function, so providing an iteratee will disable
	// the faster algorithm.
	function uniq(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 && !iteratee) {
	      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.
	const union = restArguments(function (arrays) {
	  return uniq(flatten$1(arrays, true, true));
	});

	// Produce an array that contains every item shared between all the
	// passed-in arrays.
	function intersection(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;
	    var j;
	    for (j = 1; j < argsLength; j++) {
	      if (!contains(arguments[j], item)) break;
	    }
	    if (j === argsLength) result.push(item);
	  }
	  return result;
	}

	// Complement of zip. Unzip accepts an array of arrays and groups
	// each array's elements on shared indices.
	function unzip(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;
	}

	// Zip together multiple lists into a single array -- elements that share
	// an index go together.
	const zip = restArguments(unzip);

	// 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. Passing by pairs is the reverse of `_.pairs`.
	function object(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;
	}

	// Generate an integer Array containing an arithmetic progression. A port of
	// the native Python `range()` function. See
	// [the Python documentation](https://docs.python.org/library/functions.html#range).
	function range(start, stop, step) {
	  if (stop == null) {
	    stop = start || 0;
	    start = 0;
	  }
	  if (!step) {
	    step = stop < start ? -1 : 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;
	}

	// Chunk a single array into multiple arrays, each containing `count` or fewer
	// items.
	function chunk(array, count) {
	  if (count == null || count < 1) return [];
	  var result = [];
	  var i = 0,
	    length = array.length;
	  while (i < length) {
	    result.push(slice.call(array, i, i += count));
	  }
	  return result;
	}

	// Helper function to continue chaining intermediate results.
	function chainResult(instance, obj) {
	  return instance._chain ? _$1(obj).chain() : obj;
	}

	// Add your own custom functions to the Underscore object.
	function mixin(obj) {
	  each(functions(obj), function (name) {
	    var func = _$1[name] = obj[name];
	    _$1.prototype[name] = function () {
	      var args = [this._wrapped];
	      push.apply(args, arguments);
	      return chainResult(this, func.apply(_$1, args));
	    };
	  });
	  return _$1;
	}

	// Add all mutator `Array` functions to the wrapper.
	each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function (name) {
	  var method = ArrayProto[name];
	  _$1.prototype[name] = function () {
	    var obj = this._wrapped;
	    if (obj != null) {
	      method.apply(obj, arguments);
	      if ((name === 'shift' || name === 'splice') && obj.length === 0) {
	        delete obj[0];
	      }
	    }
	    return chainResult(this, obj);
	  };
	});

	// Add all accessor `Array` functions to the wrapper.
	each(['concat', 'join', 'slice'], function (name) {
	  var method = ArrayProto[name];
	  _$1.prototype[name] = function () {
	    var obj = this._wrapped;
	    if (obj != null) obj = method.apply(obj, arguments);
	    return chainResult(this, obj);
	  };
	});

	// Named Exports
	// =============

	const allExports = /*#__PURE__*/Object.defineProperty({
		__proto__: null,
		VERSION,
		after,
		all: every,
		allKeys,
		any: some,
		assign: extendOwn,
		before,
		bind,
		bindAll,
		chain,
		chunk,
		clone,
		collect: map,
		compact,
		compose,
		constant,
		contains,
		countBy,
		create,
		debounce,
		default: _$1,
		defaults,
		defer,
		delay,
		detect: find,
		difference,
		drop: rest,
		each,
		escape,
		every,
		extend,
		extendOwn,
		filter,
		find,
		findIndex,
		findKey,
		findLastIndex,
		findWhere,
		first,
		flatten,
		foldl: reduce,
		foldr: reduceRight,
		forEach: each,
		functions,
		get,
		groupBy,
		has,
		head: first,
		identity,
		include: contains,
		includes: contains,
		indexBy,
		indexOf,
		initial,
		inject: reduce,
		intersection,
		invert,
		invoke,
		isArguments: isArguments$1,
		isArray,
		isArrayBuffer,
		isBoolean,
		isDataView: isDataView$1,
		isDate,
		isElement,
		isEmpty,
		isEqual,
		isError,
		isFinite: isFinite$1,
		isFunction: isFunction$1,
		isMap,
		isMatch,
		isNaN: isNaN$1,
		isNull,
		isNumber,
		isObject,
		isRegExp,
		isSet,
		isString,
		isSymbol,
		isTypedArray: isTypedArray$1,
		isUndefined,
		isWeakMap,
		isWeakSet,
		iteratee,
		keys,
		last,
		lastIndexOf,
		map,
		mapObject,
		matcher,
		matches: matcher,
		max,
		memoize,
		methods: functions,
		min,
		mixin,
		negate,
		noop,
		now,
		object,
		omit,
		once,
		pairs,
		partial,
		partition,
		pick,
		pluck,
		property,
		propertyOf,
		random,
		range,
		reduce,
		reduceRight,
		reject,
		rest,
		restArguments,
		result,
		sample,
		select: filter,
		shuffle,
		size,
		some,
		sortBy,
		sortedIndex,
		tail: rest,
		take: first,
		tap,
		template,
		templateSettings,
		throttle,
		times,
		toArray,
		toPath: toPath$1,
		transpose: unzip,
		unescape,
		union,
		uniq,
		unique: uniq,
		uniqueId,
		unzip,
		values,
		where,
		without,
		wrap,
		zip
	}, Symbol.toStringTag, { value: 'Module' });

	// Default Export
	// ==============
	// In this module, we mix our bundled exports into the `_` object and export
	// the result. This is analogous to setting `module.exports = _` in CommonJS.
	// Hence, this module is also the entry point of our UMD bundle and the package
	// entry point for CommonJS and AMD users. In other words, this is (the source
	// of) the module you are interfacing with when you do any of the following:
	//
	// ```js
	// // CommonJS
	// var _ = require('underscore');
	//
	// // AMD
	// define(['underscore'], function(_) {...});
	//
	// // UMD in the browser
	// // _ is available as a global variable
	// ```

	// Add all of the Underscore functions to the wrapper object.
	var _ = mixin(allExports);
	// Legacy Node.js API.
	_._ = _;

	// ESM Exports
	// ===========
	// This module is the package entry point for ES module users. In other words,
	// it is the module they are interfacing with when they import from the whole
	// package instead of from a submodule, like this:
	//
	// ```js
	// import { map } from 'underscore';
	// ```
	//
	// The difference with `./index-default`, which is the package entry point for
	// CommonJS, AMD and UMD users, is purely technical. In ES modules, named and
	// default exports are considered to be siblings, so when you have a default
	// export, its properties are not automatically available as named exports. For
	// this reason, we re-export the named exports in addition to providing the same
	// default export as in `./index-default`.

	const indexAll = /*#__PURE__*/Object.defineProperty({
		__proto__: null,
		VERSION,
		after,
		all: every,
		allKeys,
		any: some,
		assign: extendOwn,
		before,
		bind,
		bindAll,
		chain,
		chunk,
		clone,
		collect: map,
		compact,
		compose,
		constant,
		contains,
		countBy,
		create,
		debounce,
		default: _,
		defaults,
		defer,
		delay,
		detect: find,
		difference,
		drop: rest,
		each,
		escape,
		every,
		extend,
		extendOwn,
		filter,
		find,
		findIndex,
		findKey,
		findLastIndex,
		findWhere,
		first,
		flatten,
		foldl: reduce,
		foldr: reduceRight,
		forEach: each,
		functions,
		get,
		groupBy,
		has,
		head: first,
		identity,
		include: contains,
		includes: contains,
		indexBy,
		indexOf,
		initial,
		inject: reduce,
		intersection,
		invert,
		invoke,
		isArguments: isArguments$1,
		isArray,
		isArrayBuffer,
		isBoolean,
		isDataView: isDataView$1,
		isDate,
		isElement,
		isEmpty,
		isEqual,
		isError,
		isFinite: isFinite$1,
		isFunction: isFunction$1,
		isMap,
		isMatch,
		isNaN: isNaN$1,
		isNull,
		isNumber,
		isObject,
		isRegExp,
		isSet,
		isString,
		isSymbol,
		isTypedArray: isTypedArray$1,
		isUndefined,
		isWeakMap,
		isWeakSet,
		iteratee,
		keys,
		last,
		lastIndexOf,
		map,
		mapObject,
		matcher,
		matches: matcher,
		max,
		memoize,
		methods: functions,
		min,
		mixin,
		negate,
		noop,
		now,
		object,
		omit,
		once,
		pairs,
		partial,
		partition,
		pick,
		pluck,
		property,
		propertyOf,
		random,
		range,
		reduce,
		reduceRight,
		reject,
		rest,
		restArguments,
		result,
		sample,
		select: filter,
		shuffle,
		size,
		some,
		sortBy,
		sortedIndex,
		tail: rest,
		take: first,
		tap,
		template,
		templateSettings,
		throttle,
		times,
		toArray,
		toPath: toPath$1,
		transpose: unzip,
		unescape,
		union,
		uniq,
		unique: uniq,
		uniqueId,
		unzip,
		values,
		where,
		without,
		wrap,
		zip
	}, Symbol.toStringTag, { value: 'Module' });

	var backbone = {};

	const require$$0 = /*@__PURE__*/getAugmentedNamespace(indexAll);

	var hasRequiredBackbone;
	function requireBackbone() {
	  if (hasRequiredBackbone) return backbone;
	  hasRequiredBackbone = 1;
	  (function (exports) {
	    //     Backbone.js 1.6.1

	    //     (c) 2010-2024 Jeremy Ashkenas and DocumentCloud
	    //     Backbone may be freely distributed under the MIT license.
	    //     For all details and documentation:
	    //     http://backbonejs.org

	    (function (factory) {
	      // Establish the root object, `window` (`self`) in the browser, or `global` on the server.
	      // We use `self` instead of `window` for `WebWorker` support.
	      var root = typeof self == 'object' && self.self === self && self || typeof commonjsGlobal == 'object' && commonjsGlobal.global === commonjsGlobal && commonjsGlobal;

	      // Set up Backbone appropriately for the environment. Start with AMD.
	      {
	        var _ = require$$0,
	          $;
	        try {
	          $ = require$$0$1;
	        } catch (e) {}
	        factory(root, exports, _, $);

	        // Finally, as a browser global.
	      }
	    })(function (root, Backbone, _, $) {
	      // Initial Setup
	      // -------------

	      // Save the previous value of the `Backbone` variable, so that it can be
	      // restored later on, if `noConflict` is used.
	      var previousBackbone = root.Backbone;

	      // Create a local reference to a common array method we'll want to use later.
	      var slice = Array.prototype.slice;

	      // Current version of the library. Keep in sync with `package.json`.
	      Backbone.VERSION = '1.6.1';

	      // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
	      // the `$` variable.
	      Backbone.$ = $;

	      // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
	      // to its previous owner. Returns a reference to this Backbone object.
	      Backbone.noConflict = function () {
	        root.Backbone = previousBackbone;
	        return this;
	      };

	      // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
	      // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
	      // set a `X-Http-Method-Override` header.
	      Backbone.emulateHTTP = false;

	      // Turn on `emulateJSON` to support legacy servers that can't deal with direct
	      // `application/json` requests ... this will encode the body as
	      // `application/x-www-form-urlencoded` instead and will send the model in a
	      // form param named `model`.
	      Backbone.emulateJSON = false;

	      // Backbone.Events
	      // ---------------

	      // A module that can be mixed in to *any object* in order to provide it with
	      // a custom event channel. You may bind a callback to an event with `on` or
	      // remove with `off`; `trigger`-ing an event fires all callbacks in
	      // succession.
	      //
	      //     var object = {};
	      //     _.extend(object, Backbone.Events);
	      //     object.on('expand', function(){ alert('expanded'); });
	      //     object.trigger('expand');
	      //
	      var Events = Backbone.Events = {};

	      // Regular expression used to split event strings.
	      var eventSplitter = /\s+/;

	      // A private global variable to share between listeners and listenees.
	      var _listening;

	      // Iterates over the standard `event, callback` (as well as the fancy multiple
	      // space-separated events `"change blur", callback` and jQuery-style event
	      // maps `{event: callback}`).
	      var eventsApi = function (iteratee, events, name, callback, opts) {
	        var i = 0,
	          names;
	        if (name && typeof name === 'object') {
	          // Handle event maps.
	          if (callback !== void 0 && 'context' in opts && opts.context === void 0) opts.context = callback;
	          for (names = _.keys(name); i < names.length; i++) {
	            events = eventsApi(iteratee, events, names[i], name[names[i]], opts);
	          }
	        } else if (name && eventSplitter.test(name)) {
	          // Handle space-separated event names by delegating them individually.
	          for (names = name.split(eventSplitter); i < names.length; i++) {
	            events = iteratee(events, names[i], callback, opts);
	          }
	        } else {
	          // Finally, standard events.
	          events = iteratee(events, name, callback, opts);
	        }
	        return events;
	      };

	      // Bind an event to a `callback` function. Passing `"all"` will bind
	      // the callback to all events fired.
	      Events.on = function (name, callback, context) {
	        this._events = eventsApi(onApi, this._events || {}, name, callback, {
	          context: context,
	          ctx: this,
	          listening: _listening
	        });
	        if (_listening) {
	          var listeners = this._listeners || (this._listeners = {});
	          listeners[_listening.id] = _listening;
	          // Allow the listening to use a counter, instead of tracking
	          // callbacks for library interop
	          _listening.interop = false;
	        }
	        return this;
	      };

	      // Inversion-of-control versions of `on`. Tell *this* object to listen to
	      // an event in another object... keeping track of what it's listening to
	      // for easier unbinding later.
	      Events.listenTo = function (obj, name, callback) {
	        if (!obj) return this;
	        var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
	        var listeningTo = this._listeningTo || (this._listeningTo = {});
	        var listening = _listening = listeningTo[id];

	        // This object is not listening to any other events on `obj` yet.
	        // Setup the necessary references to track the listening callbacks.
	        if (!listening) {
	          this._listenId || (this._listenId = _.uniqueId('l'));
	          listening = _listening = listeningTo[id] = new Listening(this, obj);
	        }

	        // Bind callbacks on obj.
	        var error = tryCatchOn(obj, name, callback, this);
	        _listening = void 0;
	        if (error) throw error;
	        // If the target obj is not Backbone.Events, track events manually.
	        if (listening.interop) listening.on(name, callback);
	        return this;
	      };

	      // The reducing API that adds a callback to the `events` object.
	      var onApi = function (events, name, callback, options) {
	        if (callback) {
	          var handlers = events[name] || (events[name] = []);
	          var context = options.context,
	            ctx = options.ctx,
	            listening = options.listening;
	          if (listening) listening.count++;
	          handlers.push({
	            callback: callback,
	            context: context,
	            ctx: context || ctx,
	            listening: listening
	          });
	        }
	        return events;
	      };

	      // An try-catch guarded #on function, to prevent poisoning the global
	      // `_listening` variable.
	      var tryCatchOn = function (obj, name, callback, context) {
	        try {
	          obj.on(name, callback, context);
	        } catch (e) {
	          return e;
	        }
	      };

	      // Remove one or many callbacks. If `context` is null, removes all
	      // callbacks with that function. If `callback` is null, removes all
	      // callbacks for the event. If `name` is null, removes all bound
	      // callbacks for all events.
	      Events.off = function (name, callback, context) {
	        if (!this._events) return this;
	        this._events = eventsApi(offApi, this._events, name, callback, {
	          context: context,
	          listeners: this._listeners
	        });
	        return this;
	      };

	      // Tell this object to stop listening to either specific events ... or
	      // to every object it's currently listening to.
	      Events.stopListening = function (obj, name, callback) {
	        var listeningTo = this._listeningTo;
	        if (!listeningTo) return this;
	        var ids = obj ? [obj._listenId] : _.keys(listeningTo);
	        for (var i = 0; i < ids.length; i++) {
	          var listening = listeningTo[ids[i]];

	          // If listening doesn't exist, this object is not currently
	          // listening to obj. Break out early.
	          if (!listening) break;
	          listening.obj.off(name, callback, this);
	          if (listening.interop) listening.off(name, callback);
	        }
	        if (_.isEmpty(listeningTo)) this._listeningTo = void 0;
	        return this;
	      };

	      // The reducing API that removes a callback from the `events` object.
	      var offApi = function (events, name, callback, options) {
	        if (!events) return;
	        var context = options.context,
	          listeners = options.listeners;
	        var i = 0,
	          names;

	        // Delete all event listeners and "drop" events.
	        if (!name && !context && !callback) {
	          for (names = _.keys(listeners); i < names.length; i++) {
	            listeners[names[i]].cleanup();
	          }
	          return;
	        }
	        names = name ? [name] : _.keys(events);
	        for (; i < names.length; i++) {
	          name = names[i];
	          var handlers = events[name];

	          // Bail out if there are no events stored.
	          if (!handlers) break;

	          // Find any remaining events.
	          var remaining = [];
	          for (var j = 0; j < handlers.length; j++) {
	            var handler = handlers[j];
	            if (callback && callback !== handler.callback && callback !== handler.callback._callback || context && context !== handler.context) {
	              remaining.push(handler);
	            } else {
	              var listening = handler.listening;
	              if (listening) listening.off(name, callback);
	            }
	          }

	          // Replace events if there are any remaining.  Otherwise, clean up.
	          if (remaining.length) {
	            events[name] = remaining;
	          } else {
	            delete events[name];
	          }
	        }
	        return events;
	      };

	      // Bind an event to only be triggered a single time. After the first time
	      // the callback is invoked, its listener will be removed. If multiple events
	      // are passed in using the space-separated syntax, the handler will fire
	      // once for each event, not once for a combination of all events.
	      Events.once = function (name, callback, context) {
	        // Map the event into a `{event: once}` object.
	        var events = eventsApi(onceMap, {}, name, callback, this.off.bind(this));
	        if (typeof name === 'string' && context == null) callback = void 0;
	        return this.on(events, callback, context);
	      };

	      // Inversion-of-control versions of `once`.
	      Events.listenToOnce = function (obj, name, callback) {
	        // Map the event into a `{event: once}` object.
	        var events = eventsApi(onceMap, {}, name, callback, this.stopListening.bind(this, obj));
	        return this.listenTo(obj, events);
	      };

	      // Reduces the event callbacks into a map of `{event: onceWrapper}`.
	      // `offer` unbinds the `onceWrapper` after it has been called.
	      var onceMap = function (map, name, callback, offer) {
	        if (callback) {
	          var once = map[name] = _.once(function () {
	            offer(name, once);
	            callback.apply(this, arguments);
	          });
	          once._callback = callback;
	        }
	        return map;
	      };

	      // Trigger one or many events, firing all bound callbacks. Callbacks are
	      // passed the same arguments as `trigger` is, apart from the event name
	      // (unless you're listening on `"all"`, which will cause your callback to
	      // receive the true name of the event as the first argument).
	      Events.trigger = function (name) {
	        if (!this._events) return this;
	        var length = Math.max(0, arguments.length - 1);
	        var args = Array(length);
	        for (var i = 0; i < length; i++) args[i] = arguments[i + 1];
	        eventsApi(triggerApi, this._events, name, void 0, args);
	        return this;
	      };

	      // Handles triggering the appropriate event callbacks.
	      var triggerApi = function (objEvents, name, callback, args) {
	        if (objEvents) {
	          var events = objEvents[name];
	          var allEvents = objEvents.all;
	          if (events && allEvents) allEvents = allEvents.slice();
	          if (events) triggerEvents(events, args);
	          if (allEvents) triggerEvents(allEvents, [name].concat(args));
	        }
	        return objEvents;
	      };

	      // A difficult-to-believe, but optimized internal dispatch function for
	      // triggering events. Tries to keep the usual cases speedy (most internal
	      // Backbone events have 3 arguments).
	      var triggerEvents = function (events, args) {
	        var ev,
	          i = -1,
	          l = events.length,
	          a1 = args[0],
	          a2 = args[1],
	          a3 = args[2];
	        switch (args.length) {
	          case 0:
	            while (++i < l) (ev = events[i]).callback.call(ev.ctx);
	            return;
	          case 1:
	            while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1);
	            return;
	          case 2:
	            while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2);
	            return;
	          case 3:
	            while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3);
	            return;
	          default:
	            while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
	            return;
	        }
	      };

	      // A listening class that tracks and cleans up memory bindings
	      // when all callbacks have been offed.
	      var Listening = function (listener, obj) {
	        this.id = listener._listenId;
	        this.listener = listener;
	        this.obj = obj;
	        this.interop = true;
	        this.count = 0;
	        this._events = void 0;
	      };
	      Listening.prototype.on = Events.on;

	      // Offs a callback (or several).
	      // Uses an optimized counter if the listenee uses Backbone.Events.
	      // Otherwise, falls back to manual tracking to support events
	      // library interop.
	      Listening.prototype.off = function (name, callback) {
	        var cleanup;
	        if (this.interop) {
	          this._events = eventsApi(offApi, this._events, name, callback, {
	            context: void 0,
	            listeners: void 0
	          });
	          cleanup = !this._events;
	        } else {
	          this.count--;
	          cleanup = this.count === 0;
	        }
	        if (cleanup) this.cleanup();
	      };

	      // Cleans up memory bindings between the listener and the listenee.
	      Listening.prototype.cleanup = function () {
	        delete this.listener._listeningTo[this.obj._listenId];
	        if (!this.interop) delete this.obj._listeners[this.id];
	      };

	      // Aliases for backwards compatibility.
	      Events.bind = Events.on;
	      Events.unbind = Events.off;

	      // Allow the `Backbone` object to serve as a global event bus, for folks who
	      // want global "pubsub" in a convenient place.
	      _.extend(Backbone, Events);

	      // Backbone.Model
	      // --------------

	      // Backbone **Models** are the basic data object in the framework --
	      // frequently representing a row in a table in a database on your server.
	      // A discrete chunk of data and a bunch of useful, related methods for
	      // performing computations and transformations on that data.

	      // Create a new model with the specified attributes. A client id (`cid`)
	      // is automatically generated and assigned for you.
	      var Model = Backbone.Model = function (attributes, options) {
	        var attrs = attributes || {};
	        options || (options = {});
	        this.preinitialize.apply(this, arguments);
	        this.cid = _.uniqueId(this.cidPrefix);
	        this.attributes = {};
	        if (options.collection) this.collection = options.collection;
	        if (options.parse) attrs = this.parse(attrs, options) || {};
	        var defaults = _.result(this, 'defaults');

	        // Just _.defaults would work fine, but the additional _.extends
	        // is in there for historical reasons. See #3843.
	        attrs = _.defaults(_.extend({}, defaults, attrs), defaults);
	        this.set(attrs, options);
	        this.changed = {};
	        this.initialize.apply(this, arguments);
	      };

	      // Attach all inheritable methods to the Model prototype.
	      _.extend(Model.prototype, Events, {
	        // A hash of attributes whose current and previous value differ.
	        changed: null,
	        // The value returned during the last failed validation.
	        validationError: null,
	        // The default name for the JSON `id` attribute is `"id"`. MongoDB and
	        // CouchDB users may want to set this to `"_id"`.
	        idAttribute: 'id',
	        // The prefix is used to create the client id which is used to identify models locally.
	        // You may want to override this if you're experiencing name clashes with model ids.
	        cidPrefix: 'c',
	        // preinitialize is an empty function by default. You can override it with a function
	        // or object.  preinitialize will run before any instantiation logic is run in the Model.
	        preinitialize: function () {},
	        // Initialize is an empty function by default. Override it with your own
	        // initialization logic.
	        initialize: function () {},
	        // Return a copy of the model's `attributes` object.
	        toJSON: function (options) {
	          return _.clone(this.attributes);
	        },
	        // Proxy `Backbone.sync` by default -- but override this if you need
	        // custom syncing semantics for *this* particular model.
	        sync: function () {
	          return Backbone.sync.apply(this, arguments);
	        },
	        // Get the value of an attribute.
	        get: function (attr) {
	          return this.attributes[attr];
	        },
	        // Get the HTML-escaped value of an attribute.
	        escape: function (attr) {
	          return _.escape(this.get(attr));
	        },
	        // Returns `true` if the attribute contains a value that is not null
	        // or undefined.
	        has: function (attr) {
	          return this.get(attr) != null;
	        },
	        // Special-cased proxy to underscore's `_.matches` method.
	        matches: function (attrs) {
	          return !!_.iteratee(attrs, this)(this.attributes);
	        },
	        // Set a hash of model attributes on the object, firing `"change"`. This is
	        // the core primitive operation of a model, updating the data and notifying
	        // anyone who needs to know about the change in state. The heart of the beast.
	        set: function (key, val, options) {
	          if (key == null) return this;

	          // Handle both `"key", value` and `{key: value}` -style arguments.
	          var attrs;
	          if (typeof key === 'object') {
	            attrs = key;
	            options = val;
	          } else {
	            (attrs = {})[key] = val;
	          }
	          options || (options = {});

	          // Run validation.
	          if (!this._validate(attrs, options)) return false;

	          // Extract attributes and options.
	          var unset = options.unset;
	          var silent = options.silent;
	          var changes = [];
	          var changing = this._changing;
	          this._changing = true;
	          if (!changing) {
	            this._previousAttributes = _.clone(this.attributes);
	            this.changed = {};
	          }
	          var current = this.attributes;
	          var changed = this.changed;
	          var prev = this._previousAttributes;

	          // For each `set` attribute, update or delete the current value.
	          for (var attr in attrs) {
	            val = attrs[attr];
	            if (!_.isEqual(current[attr], val)) changes.push(attr);
	            if (!_.isEqual(prev[attr], val)) {
	              changed[attr] = val;
	            } else {
	              delete changed[attr];
	            }
	            unset ? delete current[attr] : current[attr] = val;
	          }

	          // Update the `id`.
	          if (this.idAttribute in attrs) {
	            var prevId = this.id;
	            this.id = this.get(this.idAttribute);
	            if (this.id !== prevId) {
	              this.trigger('changeId', this, prevId, options);
	            }
	          }

	          // Trigger all relevant attribute changes.
	          if (!silent) {
	            if (changes.length) this._pending = options;
	            for (var i = 0; i < changes.length; i++) {
	              this.trigger('change:' + changes[i], this, current[changes[i]], options);
	            }
	          }

	          // You might be wondering why there's a `while` loop here. Changes can
	          // be recursively nested within `"change"` events.
	          if (changing) return this;
	          if (!silent) {
	            while (this._pending) {
	              options = this._pending;
	              this._pending = false;
	              this.trigger('change', this, options);
	            }
	          }
	          this._pending = false;
	          this._changing = false;
	          return this;
	        },
	        // Remove an attribute from the model, firing `"change"`. `unset` is a noop
	        // if the attribute doesn't exist.
	        unset: function (attr, options) {
	          return this.set(attr, void 0, _.extend({}, options, {
	            unset: true
	          }));
	        },
	        // Clear all attributes on the model, firing `"change"`.
	        clear: function (options) {
	          var attrs = {};
	          for (var key in this.attributes) attrs[key] = void 0;
	          return this.set(attrs, _.extend({}, options, {
	            unset: true
	          }));
	        },
	        // Determine if the model has changed since the last `"change"` event.
	        // If you specify an attribute name, determine if that attribute has changed.
	        hasChanged: function (attr) {
	          if (attr == null) return !_.isEmpty(this.changed);
	          return _.has(this.changed, attr);
	        },
	        // Return an object containing all the attributes that have changed, or
	        // false if there are no changed attributes. Useful for determining what
	        // parts of a view need to be updated and/or what attributes need to be
	        // persisted to the server. Unset attributes will be set to undefined.
	        // You can also pass an attributes object to diff against the model,
	        // determining if there *would be* a change.
	        changedAttributes: function (diff) {
	          if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
	          var old = this._changing ? this._previousAttributes : this.attributes;
	          var changed = {};
	          var hasChanged;
	          for (var attr in diff) {
	            var val = diff[attr];
	            if (_.isEqual(old[attr], val)) continue;
	            changed[attr] = val;
	            hasChanged = true;
	          }
	          return hasChanged ? changed : false;
	        },
	        // Get the previous value of an attribute, recorded at the time the last
	        // `"change"` event was fired.
	        previous: function (attr) {
	          if (attr == null || !this._previousAttributes) return null;
	          return this._previousAttributes[attr];
	        },
	        // Get all of the attributes of the model at the time of the previous
	        // `"change"` event.
	        previousAttributes: function () {
	          return _.clone(this._previousAttributes);
	        },
	        // Fetch the model from the server, merging the response with the model's
	        // local attributes. Any changed attributes will trigger a "change" event.
	        fetch: function (options) {
	          options = _.extend({
	            parse: true
	          }, options);
	          var model = this;
	          var success = options.success;
	          options.success = function (resp) {
	            var serverAttrs = options.parse ? model.parse(resp, options) : resp;
	            if (!model.set(serverAttrs, options)) return false;
	            if (success) success.call(options.context, model, resp, options);
	            model.trigger('sync', model, resp, options);
	          };
	          wrapError(this, options);
	          return this.sync('read', this, options);
	        },
	        // Set a hash of model attributes, and sync the model to the server.
	        // If the server returns an attributes hash that differs, the model's
	        // state will be `set` again.
	        save: function (key, val, options) {
	          // Handle both `"key", value` and `{key: value}` -style arguments.
	          var attrs;
	          if (key == null || typeof key === 'object') {
	            attrs = key;
	            options = val;
	          } else {
	            (attrs = {})[key] = val;
	          }
	          options = _.extend({
	            validate: true,
	            parse: true
	          }, options);
	          var wait = options.wait;

	          // If we're not waiting and attributes exist, save acts as
	          // `set(attr).save(null, opts)` with validation. Otherwise, check if
	          // the model will be valid when the attributes, if any, are set.
	          if (attrs && !wait) {
	            if (!this.set(attrs, options)) return false;
	          } else if (!this._validate(attrs, options)) {
	            return false;
	          }

	          // After a successful server-side save, the client is (optionally)
	          // updated with the server-side state.
	          var model = this;
	          var success = options.success;
	          var attributes = this.attributes;
	          options.success = function (resp) {
	            // Ensure attributes are restored during synchronous saves.
	            model.attributes = attributes;
	            var serverAttrs = options.parse ? model.parse(resp, options) : resp;
	            if (wait) serverAttrs = _.extend({}, attrs, serverAttrs);
	            if (serverAttrs && !model.set(serverAttrs, options)) return false;
	            if (success) success.call(options.context, model, resp, options);
	            model.trigger('sync', model, resp, options);
	          };
	          wrapError(this, options);

	          // Set temporary attributes if `{wait: true}` to properly find new ids.
	          if (attrs && wait) this.attributes = _.extend({}, attributes, attrs);
	          var method = this.isNew() ? 'create' : options.patch ? 'patch' : 'update';
	          if (method === 'patch' && !options.attrs) options.attrs = attrs;
	          var xhr = this.sync(method, this, options);

	          // Restore attributes.
	          this.attributes = attributes;
	          return xhr;
	        },
	        // Destroy this model on the server if it was already persisted.
	        // Optimistically removes the model from its collection, if it has one.
	        // If `wait: true` is passed, waits for the server to respond before removal.
	        destroy: function (options) {
	          options = options ? _.clone(options) : {};
	          var model = this;
	          var success = options.success;
	          var wait = options.wait;
	          var destroy = function () {
	            model.stopListening();
	            model.trigger('destroy', model, model.collection, options);
	          };
	          options.success = function (resp) {
	            if (wait) destroy();
	            if (success) success.call(options.context, model, resp, options);
	            if (!model.isNew()) model.trigger('sync', model, resp, options);
	          };
	          var xhr = false;
	          if (this.isNew()) {
	            _.defer(options.success);
	          } else {
	            wrapError(this, options);
	            xhr = this.sync('delete', this, options);
	          }
	          if (!wait) destroy();
	          return xhr;
	        },
	        // Default URL for the model's representation on the server -- if you're
	        // using Backbone's restful methods, override this to change the endpoint
	        // that will be called.
	        url: function () {
	          var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
	          if (this.isNew()) return base;
	          var id = this.get(this.idAttribute);
	          return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id);
	        },
	        // **parse** converts a response into the hash of attributes to be `set` on
	        // the model. The default implementation is just to pass the response along.
	        parse: function (resp, options) {
	          return resp;
	        },
	        // Create a new model with identical attributes to this one.
	        clone: function () {
	          return new this.constructor(this.attributes);
	        },
	        // A model is new if it has never been saved to the server, and lacks an id.
	        isNew: function () {
	          return !this.has(this.idAttribute);
	        },
	        // Check if the model is currently in a valid state.
	        isValid: function (options) {
	          return this._validate({}, _.extend({}, options, {
	            validate: true
	          }));
	        },
	        // Run validation against the next complete set of model attributes,
	        // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
	        _validate: function (attrs, options) {
	          if (!options.validate || !this.validate) return true;
	          attrs = _.extend({}, this.attributes, attrs);
	          var error = this.validationError = this.validate(attrs, options) || null;
	          if (!error) return true;
	          this.trigger('invalid', this, error, _.extend(options, {
	            validationError: error
	          }));
	          return false;
	        }
	      });

	      // Backbone.Collection
	      // -------------------

	      // If models tend to represent a single row of data, a Backbone Collection is
	      // more analogous to a table full of data ... or a small slice or page of that
	      // table, or a collection of rows that belong together for a particular reason
	      // -- all of the messages in this particular folder, all of the documents
	      // belonging to this particular author, and so on. Collections maintain
	      // indexes of their models, both in order, and for lookup by `id`.

	      // Create a new **Collection**, perhaps to contain a specific type of `model`.
	      // If a `comparator` is specified, the Collection will maintain
	      // its models in sort order, as they're added and removed.
	      var Collection = Backbone.Collection = function (models, options) {
	        options || (options = {});
	        this.preinitialize.apply(this, arguments);
	        if (options.model) this.model = options.model;
	        if (options.comparator !== void 0) this.comparator = options.comparator;
	        this._reset();
	        this.initialize.apply(this, arguments);
	        if (models) this.reset(models, _.extend({
	          silent: true
	        }, options));
	      };

	      // Default options for `Collection#set`.
	      var setOptions = {
	        add: true,
	        remove: true,
	        merge: true
	      };
	      var addOptions = {
	        add: true,
	        remove: false
	      };

	      // Splices `insert` into `array` at index `at`.
	      var splice = function (array, insert, at) {
	        at = Math.min(Math.max(at, 0), array.length);
	        var tail = Array(array.length - at);
	        var length = insert.length;
	        var i;
	        for (i = 0; i < tail.length; i++) tail[i] = array[i + at];
	        for (i = 0; i < length; i++) array[i + at] = insert[i];
	        for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i];
	      };

	      // Define the Collection's inheritable methods.
	      _.extend(Collection.prototype, Events, {
	        // The default model for a collection is just a **Backbone.Model**.
	        // This should be overridden in most cases.
	        model: Model,
	        // preinitialize is an empty function by default. You can override it with a function
	        // or object.  preinitialize will run before any instantiation logic is run in the Collection.
	        preinitialize: function () {},
	        // Initialize is an empty function by default. Override it with your own
	        // initialization logic.
	        initialize: function () {},
	        // The JSON representation of a Collection is an array of the
	        // models' attributes.
	        toJSON: function (options) {
	          return this.map(function (model) {
	            return model.toJSON(options);
	          });
	        },
	        // Proxy `Backbone.sync` by default.
	        sync: function () {
	          return Backbone.sync.apply(this, arguments);
	        },
	        // Add a model, or list of models to the set. `models` may be Backbone
	        // Models or raw JavaScript objects to be converted to Models, or any
	        // combination of the two.
	        add: function (models, options) {
	          return this.set(models, _.extend({
	            merge: false
	          }, options, addOptions));
	        },
	        // Remove a model, or a list of models from the set.
	        remove: function (models, options) {
	          options = _.extend({}, options);
	          var singular = !_.isArray(models);
	          models = singular ? [models] : models.slice();
	          var removed = this._removeModels(models, options);
	          if (!options.silent && removed.length) {
	            options.changes = {
	              added: [],
	              merged: [],
	              removed: removed
	            };
	            this.trigger('update', this, options);
	          }
	          return singular ? removed[0] : removed;
	        },
	        // Update a collection by `set`-ing a new list of models, adding new ones,
	        // removing models that are no longer present, and merging models that
	        // already exist in the collection, as necessary. Similar to **Model#set**,
	        // the core operation for updating the data contained by the collection.
	        set: function (models, options) {
	          if (models == null) return;
	          options = _.extend({}, setOptions, options);
	          if (options.parse && !this._isModel(models)) {
	            models = this.parse(models, options) || [];
	          }
	          var singular = !_.isArray(models);
	          models = singular ? [models] : models.slice();
	          var at = options.at;
	          if (at != null) at = +at;
	          if (at > this.length) at = this.length;
	          if (at < 0) at += this.length + 1;
	          var set = [];
	          var toAdd = [];
	          var toMerge = [];
	          var toRemove = [];
	          var modelMap = {};
	          var add = options.add;
	          var merge = options.merge;
	          var remove = options.remove;
	          var sort = false;
	          var sortable = this.comparator && at == null && options.sort !== false;
	          var sortAttr = _.isString(this.comparator) ? this.comparator : null;

	          // Turn bare objects into model references, and prevent invalid models
	          // from being added.
	          var model, i;
	          for (i = 0; i < models.length; i++) {
	            model = models[i];

	            // If a duplicate is found, prevent it from being added and
	            // optionally merge it into the existing model.
	            var existing = this.get(model);
	            if (existing) {
	              if (merge && model !== existing) {
	                var attrs = this._isModel(model) ? model.attributes : model;
	                if (options.parse) attrs = existing.parse(attrs, options);
	                existing.set(attrs, options);
	                toMerge.push(existing);
	                if (sortable && !sort) sort = existing.hasChanged(sortAttr);
	              }
	              if (!modelMap[existing.cid]) {
	                modelMap[existing.cid] = true;
	                set.push(existing);
	              }
	              models[i] = existing;

	              // If this is a new, valid model, push it to the `toAdd` list.
	            } else if (add) {
	              model = models[i] = this._prepareModel(model, options);
	              if (model) {
	                toAdd.push(model);
	                this._addReference(model, options);
	                modelMap[model.cid] = true;
	                set.push(model);
	              }
	            }
	          }

	          // Remove stale models.
	          if (remove) {
	            for (i = 0; i < this.length; i++) {
	              model = this.models[i];
	              if (!modelMap[model.cid]) toRemove.push(model);
	            }
	            if (toRemove.length) this._removeModels(toRemove, options);
	          }

	          // See if sorting is needed, update `length` and splice in new models.
	          var orderChanged = false;
	          var replace = !sortable && add && remove;
	          if (set.length && replace) {
	            orderChanged = this.length !== set.length || _.some(this.models, function (m, index) {
	              return m !== set[index];
	            });
	            this.models.length = 0;
	            splice(this.models, set, 0);
	            this.length = this.models.length;
	          } else if (toAdd.length) {
	            if (sortable) sort = true;
	            splice(this.models, toAdd, at == null ? this.length : at);
	            this.length = this.models.length;
	          }

	          // Silently sort the collection if appropriate.
	          if (sort) this.sort({
	            silent: true
	          });

	          // Unless silenced, it's time to fire all appropriate add/sort/update events.
	          if (!options.silent) {
	            for (i = 0; i < toAdd.length; i++) {
	              if (at != null) options.index = at + i;
	              model = toAdd[i];
	              model.trigger('add', model, this, options);
	            }
	            if (sort || orderChanged) this.trigger('sort', this, options);
	            if (toAdd.length || toRemove.length || toMerge.length) {
	              options.changes = {
	                added: toAdd,
	                removed: toRemove,
	                merged: toMerge
	              };
	              this.trigger('update', this, options);
	            }
	          }

	          // Return the added (or merged) model (or models).
	          return singular ? models[0] : models;
	        },
	        // When you have more items than you want to add or remove individually,
	        // you can reset the entire set with a new list of models, without firing
	        // any granular `add` or `remove` events. Fires `reset` when finished.
	        // Useful for bulk operations and optimizations.
	        reset: function (models, options) {
	          options = options ? _.clone(options) : {};
	          for (var i = 0; i < this.models.length; i++) {
	            this._removeReference(this.models[i], options);
	          }
	          options.previousModels = this.models;
	          this._reset();
	          models = this.add(models, _.extend({
	            silent: true
	          }, options));
	          if (!options.silent) this.trigger('reset', this, options);
	          return models;
	        },
	        // Add a model to the end of the collection.
	        push: function (model, options) {
	          return this.add(model, _.extend({
	            at: this.length
	          }, options));
	        },
	        // Remove a model from the end of the collection.
	        pop: function (options) {
	          var model = this.at(this.length - 1);
	          return this.remove(model, options);
	        },
	        // Add a model to the beginning of the collection.
	        unshift: function (model, options) {
	          return this.add(model, _.extend({
	            at: 0
	          }, options));
	        },
	        // Remove a model from the beginning of the collection.
	        shift: function (options) {
	          var model = this.at(0);
	          return this.remove(model, options);
	        },
	        // Slice out a sub-array of models from the collection.
	        slice: function () {
	          return slice.apply(this.models, arguments);
	        },
	        // Get a model from the set by id, cid, model object with id or cid
	        // properties, or an attributes object that is transformed through modelId.
	        get: function (obj) {
	          if (obj == null) return void 0;
	          return this._byId[obj] || this._byId[this.modelId(this._isModel(obj) ? obj.attributes : obj, obj.idAttribute)] || obj.cid && this._byId[obj.cid];
	        },
	        // Returns `true` if the model is in the collection.
	        has: function (obj) {
	          return this.get(obj) != null;
	        },
	        // Get the model at the given index.
	        at: function (index) {
	          if (index < 0) index += this.length;
	          return this.models[index];
	        },
	        // Return models with matching attributes. Useful for simple cases of
	        // `filter`.
	        where: function (attrs, first) {
	          return this[first ? 'find' : 'filter'](attrs);
	        },
	        // Return the first model with matching attributes. Useful for simple cases
	        // of `find`.
	        findWhere: function (attrs) {
	          return this.where(attrs, true);
	        },
	        // Force the collection to re-sort itself. You don't need to call this under
	        // normal circumstances, as the set will maintain sort order as each item
	        // is added.
	        sort: function (options) {
	          var comparator = this.comparator;
	          if (!comparator) throw new Error('Cannot sort a set without a comparator');
	          options || (options = {});
	          var length = comparator.length;
	          if (_.isFunction(comparator)) comparator = comparator.bind(this);

	          // Run sort based on type of `comparator`.
	          if (length === 1 || _.isString(comparator)) {
	            this.models = this.sortBy(comparator);
	          } else {
	            this.models.sort(comparator);
	          }
	          if (!options.silent) this.trigger('sort', this, options);
	          return this;
	        },
	        // Pluck an attribute from each model in the collection.
	        pluck: function (attr) {
	          return this.map(attr + '');
	        },
	        // Fetch the default set of models for this collection, resetting the
	        // collection when they arrive. If `reset: true` is passed, the response
	        // data will be passed through the `reset` method instead of `set`.
	        fetch: function (options) {
	          options = _.extend({
	            parse: true
	          }, options);
	          var success = options.success;
	          var collection = this;
	          options.success = function (resp) {
	            var method = options.reset ? 'reset' : 'set';
	            collection[method](resp, options);
	            if (success) success.call(options.context, collection, resp, options);
	            collection.trigger('sync', collection, resp, options);
	          };
	          wrapError(this, options);
	          return this.sync('read', this, options);
	        },
	        // Create a new instance of a model in this collection. Add the model to the
	        // collection immediately, unless `wait: true` is passed, in which case we
	        // wait for the server to agree.
	        create: function (model, options) {
	          options = options ? _.clone(options) : {};
	          var wait = options.wait;
	          model = this._prepareModel(model, options);
	          if (!model) return false;
	          if (!wait) this.add(model, options);
	          var collection = this;
	          var success = options.success;
	          options.success = function (m, resp, callbackOpts) {
	            if (wait) {
	              m.off('error', collection._forwardPristineError, collection);
	              collection.add(m, callbackOpts);
	            }
	            if (success) success.call(callbackOpts.context, m, resp, callbackOpts);
	          };
	          // In case of wait:true, our collection is not listening to any
	          // of the model's events yet, so it will not forward the error
	          // event. In this special case, we need to listen for it
	          // separately and handle the event just once.
	          // (The reason we don't need to do this for the sync event is
	          // in the success handler above: we add the model first, which
	          // causes the collection to listen, and then invoke the callback
	          // that triggers the event.)
	          if (wait) {
	            model.once('error', this._forwardPristineError, this);
	          }
	          model.save(null, options);
	          return model;
	        },
	        // **parse** converts a response into a list of models to be added to the
	        // collection. The default implementation is just to pass it through.
	        parse: function (resp, options) {
	          return resp;
	        },
	        // Create a new collection with an identical list of models as this one.
	        clone: function () {
	          return new this.constructor(this.models, {
	            model: this.model,
	            comparator: this.comparator
	          });
	        },
	        // Define how to uniquely identify models in the collection.
	        modelId: function (attrs, idAttribute) {
	          return attrs[idAttribute || this.model.prototype.idAttribute || 'id'];
	        },
	        // Get an iterator of all models in this collection.
	        values: function () {
	          return new CollectionIterator(this, ITERATOR_VALUES);
	        },
	        // Get an iterator of all model IDs in this collection.
	        keys: function () {
	          return new CollectionIterator(this, ITERATOR_KEYS);
	        },
	        // Get an iterator of all [ID, model] tuples in this collection.
	        entries: function () {
	          return new CollectionIterator(this, ITERATOR_KEYSVALUES);
	        },
	        // Private method to reset all internal state. Called when the collection
	        // is first initialized or reset.
	        _reset: function () {
	          this.length = 0;
	          this.models = [];
	          this._byId = {};
	        },
	        // Prepare a hash of attributes (or other model) to be added to this
	        // collection.
	        _prepareModel: function (attrs, options) {
	          if (this._isModel(attrs)) {
	            if (!attrs.collection) attrs.collection = this;
	            return attrs;
	          }
	          options = options ? _.clone(options) : {};
	          options.collection = this;
	          var model;
	          if (this.model.prototype) {
	            model = new this.model(attrs, options);
	          } else {
	            // ES class methods didn't have prototype
	            model = this.model(attrs, options);
	          }
	          if (!model.validationError) return model;
	          this.trigger('invalid', this, model.validationError, options);
	          return false;
	        },
	        // Internal method called by both remove and set.
	        _removeModels: function (models, options) {
	          var removed = [];
	          for (var i = 0; i < models.length; i++) {
	            var model = this.get(models[i]);
	            if (!model) continue;
	            var index = this.indexOf(model);
	            this.models.splice(index, 1);
	            this.length--;

	            // Remove references before triggering 'remove' event to prevent an
	            // infinite loop. #3693
	            delete this._byId[model.cid];
	            var id = this.modelId(model.attributes, model.idAttribute);
	            if (id != null) delete this._byId[id];
	            if (!options.silent) {
	              options.index = index;
	              model.trigger('remove', model, this, options);
	            }
	            removed.push(model);
	            this._removeReference(model, options);
	          }
	          if (models.length > 0 && !options.silent) delete options.index;
	          return removed;
	        },
	        // Method for checking whether an object should be considered a model for
	        // the purposes of adding to the collection.
	        _isModel: function (model) {
	          return model instanceof Model;
	        },
	        // Internal method to create a model's ties to a collection.
	        _addReference: function (model, options) {
	          this._byId[model.cid] = model;
	          var id = this.modelId(model.attributes, model.idAttribute);
	          if (id != null) this._byId[id] = model;
	          model.on('all', this._onModelEvent, this);
	        },
	        // Internal method to sever a model's ties to a collection.
	        _removeReference: function (model, options) {
	          delete this._byId[model.cid];
	          var id = this.modelId(model.attributes, model.idAttribute);
	          if (id != null) delete this._byId[id];
	          if (this === model.collection) delete model.collection;
	          model.off('all', this._onModelEvent, this);
	        },
	        // Internal method called every time a model in the set fires an event.
	        // Sets need to update their indexes when models change ids. All other
	        // events simply proxy through. "add" and "remove" events that originate
	        // in other collections are ignored.
	        _onModelEvent: function (event, model, collection, options) {
	          if (model) {
	            if ((event === 'add' || event === 'remove') && collection !== this) return;
	            if (event === 'destroy') this.remove(model, options);
	            if (event === 'changeId') {
	              var prevId = this.modelId(model.previousAttributes(), model.idAttribute);
	              var id = this.modelId(model.attributes, model.idAttribute);
	              if (prevId != null) delete this._byId[prevId];
	              if (id != null) this._byId[id] = model;
	            }
	          }
	          this.trigger.apply(this, arguments);
	        },
	        // Internal callback method used in `create`. It serves as a
	        // stand-in for the `_onModelEvent` method, which is not yet bound
	        // during the `wait` period of the `create` call. We still want to
	        // forward any `'error'` event at the end of the `wait` period,
	        // hence a customized callback.
	        _forwardPristineError: function (model, collection, options) {
	          // Prevent double forward if the model was already in the
	          // collection before the call to `create`.
	          if (this.has(model)) return;
	          this._onModelEvent('error', model, collection, options);
	        }
	      });

	      // Defining an @@iterator method implements JavaScript's Iterable protocol.
	      // In modern ES2015 browsers, this value is found at Symbol.iterator.
	      /* global Symbol */
	      var $$iterator = typeof Symbol === 'function' && Symbol.iterator;
	      if ($$iterator) {
	        Collection.prototype[$$iterator] = Collection.prototype.values;
	      }

	      // CollectionIterator
	      // ------------------

	      // A CollectionIterator implements JavaScript's Iterator protocol, allowing the
	      // use of `for of` loops in modern browsers and interoperation between
	      // Backbone.Collection and other JavaScript functions and third-party libraries
	      // which can operate on Iterables.
	      var CollectionIterator = function (collection, kind) {
	        this._collection = collection;
	        this._kind = kind;
	        this._index = 0;
	      };

	      // This "enum" defines the three possible kinds of values which can be emitted
	      // by a CollectionIterator that correspond to the values(), keys() and entries()
	      // methods on Collection, respectively.
	      var ITERATOR_VALUES = 1;
	      var ITERATOR_KEYS = 2;
	      var ITERATOR_KEYSVALUES = 3;

	      // All Iterators should themselves be Iterable.
	      if ($$iterator) {
	        CollectionIterator.prototype[$$iterator] = function () {
	          return this;
	        };
	      }
	      CollectionIterator.prototype.next = function () {
	        if (this._collection) {
	          // Only continue iterating if the iterated collection is long enough.
	          if (this._index < this._collection.length) {
	            var model = this._collection.at(this._index);
	            this._index++;

	            // Construct a value depending on what kind of values should be iterated.
	            var value;
	            if (this._kind === ITERATOR_VALUES) {
	              value = model;
	            } else {
	              var id = this._collection.modelId(model.attributes, model.idAttribute);
	              if (this._kind === ITERATOR_KEYS) {
	                value = id;
	              } else {
	                // ITERATOR_KEYSVALUES
	                value = [id, model];
	              }
	            }
	            return {
	              value: value,
	              done: false
	            };
	          }

	          // Once exhausted, remove the reference to the collection so future
	          // calls to the next method always return done.
	          this._collection = void 0;
	        }
	        return {
	          value: void 0,
	          done: true
	        };
	      };

	      // Backbone.View
	      // -------------

	      // Backbone Views are almost more convention than they are actual code. A View
	      // is simply a JavaScript object that represents a logical chunk of UI in the
	      // DOM. This might be a single item, an entire list, a sidebar or panel, or
	      // even the surrounding frame which wraps your whole app. Defining a chunk of
	      // UI as a **View** allows you to define your DOM events declaratively, without
	      // having to worry about render order ... and makes it easy for the view to
	      // react to specific changes in the state of your models.

	      // Creating a Backbone.View creates its initial element outside of the DOM,
	      // if an existing element is not provided...
	      var View = Backbone.View = function (options) {
	        this.cid = _.uniqueId('view');
	        this.preinitialize.apply(this, arguments);
	        _.extend(this, _.pick(options, viewOptions));
	        this._ensureElement();
	        this.initialize.apply(this, arguments);
	      };

	      // Cached regex to split keys for `delegate`.
	      var delegateEventSplitter = /^(\S+)\s*(.*)$/;

	      // List of view options to be set as properties.
	      var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];

	      // Set up all inheritable **Backbone.View** properties and methods.
	      _.extend(View.prototype, Events, {
	        // The default `tagName` of a View's element is `"div"`.
	        tagName: 'div',
	        // jQuery delegate for element lookup, scoped to DOM elements within the
	        // current view. This should be preferred to global lookups where possible.
	        $: function (selector) {
	          return this.$el.find(selector);
	        },
	        // preinitialize is an empty function by default. You can override it with a function
	        // or object.  preinitialize will run before any instantiation logic is run in the View
	        preinitialize: function () {},
	        // Initialize is an empty function by default. Override it with your own
	        // initialization logic.
	        initialize: function () {},
	        // **render** is the core function that your view should override, in order
	        // to populate its element (`this.el`), with the appropriate HTML. The
	        // convention is for **render** to always return `this`.
	        render: function () {
	          return this;
	        },
	        // Remove this view by taking the element out of the DOM, and removing any
	        // applicable Backbone.Events listeners.
	        remove: function () {
	          this._removeElement();
	          this.stopListening();
	          return this;
	        },
	        // Remove this view's element from the document and all event listeners
	        // attached to it. Exposed for subclasses using an alternative DOM
	        // manipulation API.
	        _removeElement: function () {
	          this.$el.remove();
	        },
	        // Change the view's element (`this.el` property) and re-delegate the
	        // view's events on the new element.
	        setElement: function (element) {
	          this.undelegateEvents();
	          this._setElement(element);
	          this.delegateEvents();
	          return this;
	        },
	        // Creates the `this.el` and `this.$el` references for this view using the
	        // given `el`. `el` can be a CSS selector or an HTML string, a jQuery
	        // context or an element. Subclasses can override this to utilize an
	        // alternative DOM manipulation API and are only required to set the
	        // `this.el` property.
	        _setElement: function (el) {
	          this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
	          this.el = this.$el[0];
	        },
	        // Set callbacks, where `this.events` is a hash of
	        //
	        // *{"event selector": "callback"}*
	        //
	        //     {
	        //       'mousedown .title':  'edit',
	        //       'click .button':     'save',
	        //       'click .open':       function(e) { ... }
	        //     }
	        //
	        // pairs. Callbacks will be bound to the view, with `this` set properly.
	        // Uses event delegation for efficiency.
	        // Omitting the selector binds the event to `this.el`.
	        delegateEvents: function (events) {
	          events || (events = _.result(this, 'events'));
	          if (!events) return this;
	          this.undelegateEvents();
	          for (var key in events) {
	            var method = events[key];
	            if (!_.isFunction(method)) method = this[method];
	            if (!method) continue;
	            var match = key.match(delegateEventSplitter);
	            this.delegate(match[1], match[2], method.bind(this));
	          }
	          return this;
	        },
	        // Add a single event listener to the view's element (or a child element
	        // using `selector`). This only works for delegate-able events: not `focus`,
	        // `blur`, and not `change`, `submit`, and `reset` in Internet Explorer.
	        delegate: function (eventName, selector, listener) {
	          this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener);
	          return this;
	        },
	        // Clears all callbacks previously bound to the view by `delegateEvents`.
	        // You usually don't need to use this, but may wish to if you have multiple
	        // Backbone views attached to the same DOM element.
	        undelegateEvents: function () {
	          if (this.$el) this.$el.off('.delegateEvents' + this.cid);
	          return this;
	        },
	        // A finer-grained `undelegateEvents` for removing a single delegated event.
	        // `selector` and `listener` are both optional.
	        undelegate: function (eventName, selector, listener) {
	          this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener);
	          return this;
	        },
	        // Produces a DOM element to be assigned to your view. Exposed for
	        // subclasses using an alternative DOM manipulation API.
	        _createElement: function (tagName) {
	          return document.createElement(tagName);
	        },
	        // Ensure that the View has a DOM element to render into.
	        // If `this.el` is a string, pass it through `$()`, take the first
	        // matching element, and re-assign it to `el`. Otherwise, create
	        // an element from the `id`, `className` and `tagName` properties.
	        _ensureElement: function () {
	          if (!this.el) {
	            var attrs = _.extend({}, _.result(this, 'attributes'));
	            if (this.id) attrs.id = _.result(this, 'id');
	            if (this.className) attrs['class'] = _.result(this, 'className');
	            this.setElement(this._createElement(_.result(this, 'tagName')));
	            this._setAttributes(attrs);
	          } else {
	            this.setElement(_.result(this, 'el'));
	          }
	        },
	        // Set attributes from a hash on this view's element.  Exposed for
	        // subclasses using an alternative DOM manipulation API.
	        _setAttributes: function (attributes) {
	          this.$el.attr(attributes);
	        }
	      });

	      // Proxy Backbone class methods to Underscore functions, wrapping the model's
	      // `attributes` object or collection's `models` array behind the scenes.
	      //
	      // collection.filter(function(model) { return model.get('age') > 10 });
	      // collection.each(this.addView);
	      //
	      // `Function#apply` can be slow so we use the method's arg count, if we know it.
	      var addMethod = function (base, length, method, attribute) {
	        switch (length) {
	          case 1:
	            return function () {
	              return base[method](this[attribute]);
	            };
	          case 2:
	            return function (value) {
	              return base[method](this[attribute], value);
	            };
	          case 3:
	            return function (iteratee, context) {
	              return base[method](this[attribute], cb(iteratee, this), context);
	            };
	          case 4:
	            return function (iteratee, defaultVal, context) {
	              return base[method](this[attribute], cb(iteratee, this), defaultVal, context);
	            };
	          default:
	            return function () {
	              var args = slice.call(arguments);
	              args.unshift(this[attribute]);
	              return base[method].apply(base, args);
	            };
	        }
	      };
	      var addUnderscoreMethods = function (Class, base, methods, attribute) {
	        _.each(methods, function (length, method) {
	          if (base[method]) Class.prototype[method] = addMethod(base, length, method, attribute);
	        });
	      };

	      // Support `collection.sortBy('attr')` and `collection.findWhere({id: 1})`.
	      var cb = function (iteratee, instance) {
	        if (_.isFunction(iteratee)) return iteratee;
	        if (_.isObject(iteratee) && !instance._isModel(iteratee)) return modelMatcher(iteratee);
	        if (_.isString(iteratee)) return function (model) {
	          return model.get(iteratee);
	        };
	        return iteratee;
	      };
	      var modelMatcher = function (attrs) {
	        var matcher = _.matches(attrs);
	        return function (model) {
	          return matcher(model.attributes);
	        };
	      };

	      // Underscore methods that we want to implement on the Collection.
	      // 90% of the core usefulness of Backbone Collections is actually implemented
	      // right here:
	      var collectionMethods = {
	        forEach: 3,
	        each: 3,
	        map: 3,
	        collect: 3,
	        reduce: 0,
	        foldl: 0,
	        inject: 0,
	        reduceRight: 0,
	        foldr: 0,
	        find: 3,
	        detect: 3,
	        filter: 3,
	        select: 3,
	        reject: 3,
	        every: 3,
	        all: 3,
	        some: 3,
	        any: 3,
	        include: 3,
	        includes: 3,
	        contains: 3,
	        invoke: 0,
	        max: 3,
	        min: 3,
	        toArray: 1,
	        size: 1,
	        first: 3,
	        head: 3,
	        take: 3,
	        initial: 3,
	        rest: 3,
	        tail: 3,
	        drop: 3,
	        last: 3,
	        without: 0,
	        difference: 0,
	        indexOf: 3,
	        shuffle: 1,
	        lastIndexOf: 3,
	        isEmpty: 1,
	        chain: 1,
	        sample: 3,
	        partition: 3,
	        groupBy: 3,
	        countBy: 3,
	        sortBy: 3,
	        indexBy: 3,
	        findIndex: 3,
	        findLastIndex: 3
	      };

	      // Underscore methods that we want to implement on the Model, mapped to the
	      // number of arguments they take.
	      var modelMethods = {
	        keys: 1,
	        values: 1,
	        pairs: 1,
	        invert: 1,
	        pick: 0,
	        omit: 0,
	        chain: 1,
	        isEmpty: 1
	      };

	      // Mix in each Underscore method as a proxy to `Collection#models`.

	      _.each([[Collection, collectionMethods, 'models'], [Model, modelMethods, 'attributes']], function (config) {
	        var Base = config[0],
	          methods = config[1],
	          attribute = config[2];
	        Base.mixin = function (obj) {
	          var mappings = _.reduce(_.functions(obj), function (memo, name) {
	            memo[name] = 0;
	            return memo;
	          }, {});
	          addUnderscoreMethods(Base, obj, mappings, attribute);
	        };
	        addUnderscoreMethods(Base, _, methods, attribute);
	      });

	      // Backbone.sync
	      // -------------

	      // Override this function to change the manner in which Backbone persists
	      // models to the server. You will be passed the type of request, and the
	      // model in question. By default, makes a RESTful Ajax request
	      // to the model's `url()`. Some possible customizations could be:
	      //
	      // * Use `setTimeout` to batch rapid-fire updates into a single request.
	      // * Send up the models as XML instead of JSON.
	      // * Persist models via WebSockets instead of Ajax.
	      //
	      // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
	      // as `POST`, with a `_method` parameter containing the true HTTP method,
	      // as well as all requests with the body as `application/x-www-form-urlencoded`
	      // instead of `application/json` with the model in a param named `model`.
	      // Useful when interfacing with server-side languages like **PHP** that make
	      // it difficult to read the body of `PUT` requests.
	      Backbone.sync = function (method, model, options) {
	        var type = methodMap[method];

	        // Default options, unless specified.
	        _.defaults(options || (options = {}), {
	          emulateHTTP: Backbone.emulateHTTP,
	          emulateJSON: Backbone.emulateJSON
	        });

	        // Default JSON-request options.
	        var params = {
	          type: type,
	          dataType: 'json'
	        };

	        // Ensure that we have a URL.
	        if (!options.url) {
	          params.url = _.result(model, 'url') || urlError();
	        }

	        // Ensure that we have the appropriate request data.
	        if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
	          params.contentType = 'application/json';
	          params.data = JSON.stringify(options.attrs || model.toJSON(options));
	        }

	        // For older servers, emulate JSON by encoding the request into an HTML-form.
	        if (options.emulateJSON) {
	          params.contentType = 'application/x-www-form-urlencoded';
	          params.data = params.data ? {
	            model: params.data
	          } : {};
	        }

	        // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
	        // And an `X-HTTP-Method-Override` header.
	        if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
	          params.type = 'POST';
	          if (options.emulateJSON) params.data._method = type;
	          var beforeSend = options.beforeSend;
	          options.beforeSend = function (xhr) {
	            xhr.setRequestHeader('X-HTTP-Method-Override', type);
	            if (beforeSend) return beforeSend.apply(this, arguments);
	          };
	        }

	        // Don't process data on a non-GET request.
	        if (params.type !== 'GET' && !options.emulateJSON) {
	          params.processData = false;
	        }

	        // Pass along `textStatus` and `errorThrown` from jQuery.
	        var error = options.error;
	        options.error = function (xhr, textStatus, errorThrown) {
	          options.textStatus = textStatus;
	          options.errorThrown = errorThrown;
	          if (error) error.call(options.context, xhr, textStatus, errorThrown);
	        };

	        // Make the request, allowing the user to override any Ajax options.
	        var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
	        model.trigger('request', model, xhr, options);
	        return xhr;
	      };

	      // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
	      var methodMap = {
	        'create': 'POST',
	        'update': 'PUT',
	        'patch': 'PATCH',
	        'delete': 'DELETE',
	        'read': 'GET'
	      };

	      // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
	      // Override this if you'd like to use a different library.
	      Backbone.ajax = function () {
	        return Backbone.$.ajax.apply(Backbone.$, arguments);
	      };

	      // Backbone.Router
	      // ---------------

	      // Routers map faux-URLs to actions, and fire events when routes are
	      // matched. Creating a new one sets its `routes` hash, if not set statically.
	      var Router = Backbone.Router = function (options) {
	        options || (options = {});
	        this.preinitialize.apply(this, arguments);
	        if (options.routes) this.routes = options.routes;
	        this._bindRoutes();
	        this.initialize.apply(this, arguments);
	      };

	      // Cached regular expressions for matching named param parts and splatted
	      // parts of route strings.
	      var optionalParam = /\((.*?)\)/g;
	      var namedParam = /(\(\?)?:\w+/g;
	      var splatParam = /\*\w+/g;
	      var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;

	      // Set up all inheritable **Backbone.Router** properties and methods.
	      _.extend(Router.prototype, Events, {
	        // preinitialize is an empty function by default. You can override it with a function
	        // or object.  preinitialize will run before any instantiation logic is run in the Router.
	        preinitialize: function () {},
	        // Initialize is an empty function by default. Override it with your own
	        // initialization logic.
	        initialize: function () {},
	        // Manually bind a single named route to a callback. For example:
	        //
	        //     this.route('search/:query/p:num', 'search', function(query, num) {
	        //       ...
	        //     });
	        //
	        route: function (route, name, callback) {
	          if (!_.isRegExp(route)) route = this._routeToRegExp(route);
	          if (_.isFunction(name)) {
	            callback = name;
	            name = '';
	          }
	          if (!callback) callback = this[name];
	          var router = this;
	          Backbone.history.route(route, function (fragment) {
	            var args = router._extractParameters(route, fragment);
	            if (router.execute(callback, args, name) !== false) {
	              router.trigger.apply(router, ['route:' + name].concat(args));
	              router.trigger('route', name, args);
	              Backbone.history.trigger('route', router, name, args);
	            }
	          });
	          return this;
	        },
	        // Execute a route handler with the provided parameters.  This is an
	        // excellent place to do pre-route setup or post-route cleanup.
	        execute: function (callback, args, name) {
	          if (callback) callback.apply(this, args);
	        },
	        // Simple proxy to `Backbone.history` to save a fragment into the history.
	        navigate: function (fragment, options) {
	          Backbone.history.navigate(fragment, options);
	          return this;
	        },
	        // Bind all defined routes to `Backbone.history`. We have to reverse the
	        // order of the routes here to support behavior where the most general
	        // routes can be defined at the bottom of the route map.
	        _bindRoutes: function () {
	          if (!this.routes) return;
	          this.routes = _.result(this, 'routes');
	          var route,
	            routes = _.keys(this.routes);
	          while ((route = routes.pop()) != null) {
	            this.route(route, this.routes[route]);
	          }
	        },
	        // Convert a route string into a regular expression, suitable for matching
	        // against the current location hash.
	        _routeToRegExp: function (route) {
	          route = route.replace(escapeRegExp, '\\$&').replace(optionalParam, '(?:$1)?').replace(namedParam, function (match, optional) {
	            return optional ? match : '([^/?]+)';
	          }).replace(splatParam, '([^?]*?)');
	          return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
	        },
	        // Given a route, and a URL fragment that it matches, return the array of
	        // extracted decoded parameters. Empty or unmatched parameters will be
	        // treated as `null` to normalize cross-browser behavior.
	        _extractParameters: function (route, fragment) {
	          var params = route.exec(fragment).slice(1);
	          return _.map(params, function (param, i) {
	            // Don't decode the search params.
	            if (i === params.length - 1) return param || null;
	            return param ? decodeURIComponent(param) : null;
	          });
	        }
	      });

	      // Backbone.History
	      // ----------------

	      // Handles cross-browser history management, based on either
	      // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
	      // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
	      // and URL fragments. If the browser supports neither (old IE, natch),
	      // falls back to polling.
	      var History = Backbone.History = function () {
	        this.handlers = [];
	        this.checkUrl = this.checkUrl.bind(this);

	        // Ensure that `History` can be used outside of the browser.
	        if (typeof window !== 'undefined') {
	          this.location = window.location;
	          this.history = window.history;
	        }
	      };

	      // Cached regex for stripping a leading hash/slash and trailing space.
	      var routeStripper = /^[#\/]|\s+$/g;

	      // Cached regex for stripping leading and trailing slashes.
	      var rootStripper = /^\/+|\/+$/g;

	      // Cached regex for stripping urls of hash.
	      var pathStripper = /#.*$/;

	      // Has the history handling already been started?
	      History.started = false;

	      // Set up all inheritable **Backbone.History** properties and methods.
	      _.extend(History.prototype, Events, {
	        // The default interval to poll for hash changes, if necessary, is
	        // twenty times a second.
	        interval: 50,
	        // Are we at the app root?
	        atRoot: function () {
	          var path = this.location.pathname.replace(/[^\/]$/, '$&/');
	          return path === this.root && !this.getSearch();
	        },
	        // Does the pathname match the root?
	        matchRoot: function () {
	          var path = this.decodeFragment(this.location.pathname);
	          var rootPath = path.slice(0, this.root.length - 1) + '/';
	          return rootPath === this.root;
	        },
	        // Unicode characters in `location.pathname` are percent encoded so they're
	        // decoded for comparison. `%25` should not be decoded since it may be part
	        // of an encoded parameter.
	        decodeFragment: function (fragment) {
	          return decodeURI(fragment.replace(/%25/g, '%2525'));
	        },
	        // In IE6, the hash fragment and search params are incorrect if the
	        // fragment contains `?`.
	        getSearch: function () {
	          var match = this.location.href.replace(/#.*/, '').match(/\?.+/);
	          return match ? match[0] : '';
	        },
	        // Gets the true hash value. Cannot use location.hash directly due to bug
	        // in Firefox where location.hash will always be decoded.
	        getHash: function (window) {
	          var match = (window || this).location.href.match(/#(.*)$/);
	          return match ? match[1] : '';
	        },
	        // Get the pathname and search params, without the root.
	        getPath: function () {
	          var path = this.decodeFragment(this.location.pathname + this.getSearch()).slice(this.root.length - 1);
	          return path.charAt(0) === '/' ? path.slice(1) : path;
	        },
	        // Get the cross-browser normalized URL fragment from the path or hash.
	        getFragment: function (fragment) {
	          if (fragment == null) {
	            if (this._usePushState || !this._wantsHashChange) {
	              fragment = this.getPath();
	            } else {
	              fragment = this.getHash();
	            }
	          }
	          return fragment.replace(routeStripper, '');
	        },
	        // Start the hash change handling, returning `true` if the current URL matches
	        // an existing route, and `false` otherwise.
	        start: function (options) {
	          if (History.started) throw new Error('Backbone.history has already been started');
	          History.started = true;

	          // Figure out the initial configuration. Do we need an iframe?
	          // Is pushState desired ... is it available?
	          this.options = _.extend({
	            root: '/'
	          }, this.options, options);
	          this.root = this.options.root;
	          this._trailingSlash = this.options.trailingSlash;
	          this._wantsHashChange = this.options.hashChange !== false;
	          this._hasHashChange = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7);
	          this._useHashChange = this._wantsHashChange && this._hasHashChange;
	          this._wantsPushState = !!this.options.pushState;
	          this._hasPushState = !!(this.history && this.history.pushState);
	          this._usePushState = this._wantsPushState && this._hasPushState;
	          this.fragment = this.getFragment();

	          // Normalize root to always include a leading and trailing slash.
	          this.root = ('/' + this.root + '/').replace(rootStripper, '/');

	          // Transition from hashChange to pushState or vice versa if both are
	          // requested.
	          if (this._wantsHashChange && this._wantsPushState) {
	            // If we've started off with a route from a `pushState`-enabled
	            // browser, but we're currently in a browser that doesn't support it...
	            if (!this._hasPushState && !this.atRoot()) {
	              var rootPath = this.root.slice(0, -1) || '/';
	              this.location.replace(rootPath + '#' + this.getPath());
	              // Return immediately as browser will do redirect to new url
	              return true;

	              // Or if we've started out with a hash-based route, but we're currently
	              // in a browser where it could be `pushState`-based instead...
	            } else if (this._hasPushState && this.atRoot()) {
	              this.navigate(this.getHash(), {
	                replace: true
	              });
	            }
	          }

	          // Proxy an iframe to handle location events if the browser doesn't
	          // support the `hashchange` event, HTML5 history, or the user wants
	          // `hashChange` but not `pushState`.
	          if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) {
	            this.iframe = document.createElement('iframe');
	            this.iframe.src = 'javascript:0';
	            this.iframe.style.display = 'none';
	            this.iframe.tabIndex = -1;
	            var body = document.body;
	            // Using `appendChild` will throw on IE < 9 if the document is not ready.
	            var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow;
	            iWindow.document.open();
	            iWindow.document.close();
	            iWindow.location.hash = '#' + this.fragment;
	          }

	          // Add a cross-platform `addEventListener` shim for older browsers.
	          var addEventListener = window.addEventListener || function (eventName, listener) {
	            return attachEvent('on' + eventName, listener);
	          };

	          // Depending on whether we're using pushState or hashes, and whether
	          // 'onhashchange' is supported, determine how we check the URL state.
	          if (this._usePushState) {
	            addEventListener('popstate', this.checkUrl, false);
	          } else if (this._useHashChange && !this.iframe) {
	            addEventListener('hashchange', this.checkUrl, false);
	          } else if (this._wantsHashChange) {
	            this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
	          }
	          if (!this.options.silent) return this.loadUrl();
	        },
	        // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
	        // but possibly useful for unit testing Routers.
	        stop: function () {
	          // Add a cross-platform `removeEventListener` shim for older browsers.
	          var removeEventListener = window.removeEventListener || function (eventName, listener) {
	            return detachEvent('on' + eventName, listener);
	          };

	          // Remove window listeners.
	          if (this._usePushState) {
	            removeEventListener('popstate', this.checkUrl, false);
	          } else if (this._useHashChange && !this.iframe) {
	            removeEventListener('hashchange', this.checkUrl, false);
	          }

	          // Clean up the iframe if necessary.
	          if (this.iframe) {
	            document.body.removeChild(this.iframe);
	            this.iframe = null;
	          }

	          // Some environments will throw when clearing an undefined interval.
	          if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);
	          History.started = false;
	        },
	        // Add a route to be tested when the fragment changes. Routes added later
	        // may override previous routes.
	        route: function (route, callback) {
	          this.handlers.unshift({
	            route: route,
	            callback: callback
	          });
	        },
	        // Checks the current URL to see if it has changed, and if it has,
	        // calls `loadUrl`, normalizing across the hidden iframe.
	        checkUrl: function (e) {
	          var current = this.getFragment();

	          // If the user pressed the back button, the iframe's hash will have
	          // changed and we should use that for comparison.
	          if (current === this.fragment && this.iframe) {
	            current = this.getHash(this.iframe.contentWindow);
	          }
	          if (current === this.fragment) {
	            if (!this.matchRoot()) return this.notfound();
	            return false;
	          }
	          if (this.iframe) this.navigate(current);
	          this.loadUrl();
	        },
	        // Attempt to load the current URL fragment. If a route succeeds with a
	        // match, returns `true`. If no defined routes matches the fragment,
	        // returns `false`.
	        loadUrl: function (fragment) {
	          // If the root doesn't match, no routes can match either.
	          if (!this.matchRoot()) return this.notfound();
	          fragment = this.fragment = this.getFragment(fragment);
	          return _.some(this.handlers, function (handler) {
	            if (handler.route.test(fragment)) {
	              handler.callback(fragment);
	              return true;
	            }
	          }) || this.notfound();
	        },
	        // When no route could be matched, this method is called internally to
	        // trigger the `'notfound'` event. It returns `false` so that it can be used
	        // in tail position.
	        notfound: function () {
	          this.trigger('notfound');
	          return false;
	        },
	        // Save a fragment into the hash history, or replace the URL state if the
	        // 'replace' option is passed. You are responsible for properly URL-encoding
	        // the fragment in advance.
	        //
	        // The options object can contain `trigger: true` if you wish to have the
	        // route callback be fired (not usually desirable), or `replace: true`, if
	        // you wish to modify the current URL without adding an entry to the history.
	        navigate: function (fragment, options) {
	          if (!History.started) return false;
	          if (!options || options === true) options = {
	            trigger: !!options
	          };

	          // Normalize the fragment.
	          fragment = this.getFragment(fragment || '');

	          // Strip trailing slash on the root unless _trailingSlash is true
	          var rootPath = this.root;
	          if (!this._trailingSlash && (fragment === '' || fragment.charAt(0) === '?')) {
	            rootPath = rootPath.slice(0, -1) || '/';
	          }
	          var url = rootPath + fragment;

	          // Strip the fragment of the query and hash for matching.
	          fragment = fragment.replace(pathStripper, '');

	          // Decode for matching.
	          var decodedFragment = this.decodeFragment(fragment);
	          if (this.fragment === decodedFragment) return;
	          this.fragment = decodedFragment;

	          // If pushState is available, we use it to set the fragment as a real URL.
	          if (this._usePushState) {
	            this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);

	            // If hash changes haven't been explicitly disabled, update the hash
	            // fragment to store history.
	          } else if (this._wantsHashChange) {
	            this._updateHash(this.location, fragment, options.replace);
	            if (this.iframe && fragment !== this.getHash(this.iframe.contentWindow)) {
	              var iWindow = this.iframe.contentWindow;

	              // Opening and closing the iframe tricks IE7 and earlier to push a
	              // history entry on hash-tag change.  When replace is true, we don't
	              // want this.
	              if (!options.replace) {
	                iWindow.document.open();
	                iWindow.document.close();
	              }
	              this._updateHash(iWindow.location, fragment, options.replace);
	            }

	            // If you've told us that you explicitly don't want fallback hashchange-
	            // based history, then `navigate` becomes a page refresh.
	          } else {
	            return this.location.assign(url);
	          }
	          if (options.trigger) return this.loadUrl(fragment);
	        },
	        // Update the hash location, either replacing the current entry, or adding
	        // a new one to the browser history.
	        _updateHash: function (location, fragment, replace) {
	          if (replace) {
	            var href = location.href.replace(/(javascript:|#).*$/, '');
	            location.replace(href + '#' + fragment);
	          } else {
	            // Some browsers require that `hash` contains a leading #.
	            location.hash = '#' + fragment;
	          }
	        }
	      });

	      // Create the default Backbone.history.
	      Backbone.history = new History();

	      // Helpers
	      // -------

	      // Helper function to correctly set up the prototype chain for subclasses.
	      // Similar to `goog.inherits`, but uses a hash of prototype properties and
	      // class properties to be extended.
	      var extend = function (protoProps, staticProps) {
	        var parent = this;
	        var child;

	        // The constructor function for the new subclass is either defined by you
	        // (the "constructor" property in your `extend` definition), or defaulted
	        // by us to simply call the parent constructor.
	        if (protoProps && _.has(protoProps, 'constructor')) {
	          child = protoProps.constructor;
	        } else {
	          child = function () {
	            return parent.apply(this, arguments);
	          };
	        }

	        // Add static properties to the constructor function, if supplied.
	        _.extend(child, parent, staticProps);

	        // Set the prototype chain to inherit from `parent`, without calling
	        // `parent`'s constructor function and add the prototype properties.
	        child.prototype = _.create(parent.prototype, protoProps);
	        child.prototype.constructor = child;

	        // Set a convenience property in case the parent's prototype is needed
	        // later.
	        child.__super__ = parent.prototype;
	        return child;
	      };

	      // Set up inheritance for the model, collection, router, view and history.
	      Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;

	      // Throw an error when a URL is needed, and none is supplied.
	      var urlError = function () {
	        throw new Error('A "url" property or function must be specified');
	      };

	      // Wrap an optional error callback with a fallback error event.
	      var wrapError = function (model, options) {
	        var error = options.error;
	        options.error = function (resp) {
	          if (error) error.call(options.context, model, resp, options);
	          model.trigger('error', model, resp, options);
	        };
	      };

	      // Provide useful information when things go wrong. This method is not meant
	      // to be used directly; it merely provides the necessary introspection for the
	      // external `debugInfo` function.
	      Backbone._debug = function () {
	        return {
	          root: root,
	          _: _
	        };
	      };
	      return Backbone;
	    });
	  })(backbone);
	  return backbone;
	}

	var backboneExports = requireBackbone();
	const Backbone = /*@__PURE__*/getDefaultExportFromCjs(backboneExports);

	function htm (n) {
	  for (var l, e, s = arguments, t = 1, r = "", u = "", a = [0], c = function (n) {
	      1 === t && (n || (r = r.replace(/^\s*\n\s*|\s*\n\s*$/g, ""))) ? a.push(n ? s[n] : r) : 3 === t && (n || r) ? (a[1] = n ? s[n] : r, t = 2) : 2 === t && "..." === r && n ? a[2] = Object.assign(a[2] || {}, s[n]) : 2 === t && r && !n ? (a[2] = a[2] || {})[r] = true : t >= 5 && (5 === t ? ((a[2] = a[2] || {})[e] = n ? r ? r + s[n] : s[n] : r, t = 6) : (n || r) && (a[2][e] += n ? r + s[n] : r)), r = "";
	    }, h = 0; h < n.length; h++) {
	    h && (1 === t && c(), c(h));
	    for (var i = 0; i < n[h].length; i++) l = n[h][i], 1 === t ? "<" === l ? (c(), a = [a, "", null], t = 3) : r += l : 4 === t ? "--" === r && ">" === l ? (t = 1, r = "") : r = l + r[0] : u ? l === u ? u = "" : r += l : '"' === l || "'" === l ? u = l : ">" === l ? (c(), t = 1) : t && ("=" === l ? (t = 5, e = r, r = "") : "/" === l && (t < 5 || ">" === n[h][i + 1]) ? (c(), 3 === t && (a = a[0]), t = a, (a = a[0]).push(this.apply(null, t.slice(1))), t = 0) : " " === l || "\t" === l || "\n" === l || "\r" === l ? (c(), t = 2) : r += l), 3 === t && "!--" === r && (t = 4, a = a[0]);
	  }
	  return c(), a.length > 2 ? a.slice(1) : a[1];
	}

	/* Internal symbol used to flag a deferred construction path. */
	const _constructing = Symbol();

	/*
	 * Internal state to keep track of the number of classes.
	 *
	 * These work as IDs, helping to efficiently perform checks during object
	 * construction.
	 */
	let _spinaClassCount = 0;

	/**
	 * A Spina base class or subclass.
	 *
	 * This is used to help identify classes for use in :js:func:`spinaBaseClass`
	 * and :js:func`spinaSubclass`.
	 *
	 * Version Changed:
	 *     3.0:
	 *     * This is now generic, capable of wrapping and merging with a class
	 *       type.
	 *     * ``__super__` is now typed to ``any``, avoiding errors accessing
	 *       attributes or methods.
	 *
	 * Version Changed:
	 *     2.0:
	 *     * Added ``__super__``, ``__spinaOptions``, and ``_extend``.
	 *     * Instances of any SpinaClasses now type these properties.
	 */

	/**
	 * Options available when subclassing another Spina class.
	 *
	 * Version Added:
	 *     2.0
	 */

	/**
	 * Options available when defining an extended base class.
	 *
	 * This includes all attributes in :js:class:`SubclassOptions`, as well as
	 * explicit base class options.
	 *
	 * Version Added:
	 *     2.0
	 */

	/**
	 * Results from a subclass preparation operation.
	 *
	 * Version Added:
	 *     2.0
	 */

	/**
	 * An alias for a partial (in-progress) SpinaClass.
	 *
	 * Version Added:
	 *     2.0
	 */

	/**
	 * A mutable version of SpinaClass, used for class preparation.
	 *
	 * This temporarily disables all read-only properties, and makes them all
	 * optional.
	 *
	 * Version Added:
	 *     2.0
	 */

	/**
	 * Type for a function used to initialize a Spina object.
	 */

	/**
	 * Type for a constructor for a class.
	 *
	 * Version Changed:
	 *     2.0:
	 *     Made the class optionally generic.
	 */

	/**
	 * Type for a valid mixin.
	 *
	 * Version Added:
	 *     2.0
	 */

	/**
	 * Type for an attribute that can store a value or a callable returning a
	 * value.
	 *
	 * This is expected to be used with :js:func:`_.result`.
	 *
	 * To override this type of attribute in a subclass with a method instead of
	 * a callable attribute, use :js:func:`DynamicAttrs`.
	 *
	 * Version Added:
	 *     3.0
	 */

	/**
	 * Auto-merge an attribute between a parent class and subclass.
	 *
	 * If the attribute in both cases exists and is an object, the contents will
	 * be merged together and set on the subclass.
	 *
	 * Version Added:
	 *     3.0:
	 *     Function-based values can now be merged with other functions or with
	 *     objects, originating on both the class constructor and the prototype.
	 *
	 * Version Added:
	 *     2.0
	 *
	 * Args:
	 *     cls (function):
	 *         The subclass constructor.
	 *
	 *     clsProto (object):
	 *         The subclass prototype.
	 *
	 *     parentProto (object):
	 *         The parent class prototype.
	 *
	 *     attr (string):
	 *         The attribute name to auto-merge.
	 *
	 * Returns:
	 *     boolean:
	 *     ``true`` if an attribute was auto-merged. ``false`` if it was not.
	 */
	function _automergeAttr(cls, clsProto, parentProto, attr) {
	  /*
	   * We carefully want to grab this only from the prototype or the class,
	   * if defined on those.
	   *
	   * If *not* defined on those, grab from the class or prototype with
	   * inheritance factored in, in case of mixins and to ease comparison
	   * below.
	   */
	  let onProto = false;
	  let clsValue;
	  if (clsProto.hasOwnProperty(attr)) {
	    clsValue = clsProto[attr];
	    onProto = true;
	  } else if (cls.hasOwnProperty(attr) || cls[attr] !== undefined) {
	    clsValue = cls[attr];
	  } else if (clsProto[attr] !== undefined) {
	    clsValue = clsProto[attr];
	    onProto = true;
	  } else {
	    /* Fall back to accessing via the class. */
	    clsValue = cls[attr];
	  }

	  /* We don't need to go to that trouble for the parent prototype. */
	  const parentValue = parentProto[attr];

	  /*
	   * First, check if we need to perform a merge at all.
	   *
	   * If there's nothing to merge, or if we can simply assign, then we can
	   * short-cut a lot of this.
	   */
	  if (clsValue === parentValue) {
	    return false;
	  }
	  const isClsValueFunction = isFunction$1(clsValue);
	  const isParentValueFunction = isFunction$1(parentValue);
	  const clsValueIsEmpty = !isClsValueFunction && isEmpty(clsValue);
	  const parentValueIsEmpty = !isParentValueFunction && isEmpty(parentValue);
	  let newValue;
	  let merged = true;
	  if (parentValueIsEmpty) {
	    /* There's nothing to merge. Keep the class value as-is. We're done. */
	    newValue = clsValue;
	    merged = false;
	  } else if (clsValueIsEmpty) {
	    /* Only the class value is empty. Use the parent as-is. */
	    newValue = parentValue;
	  } else if (!isClsValueFunction && !isParentValueFunction) {
	    /*
	     * Assume these objects are in fact plain objects, and not something
	     * else object-like, such as an array. This is the caller's
	     * responsibility.
	     */
	    newValue = defaults(clsValue, parentValue);
	  } else if (isClsValueFunction && isParentValueFunction) {
	    /*
	     * Merge two functions together.
	     *
	     * We'll create a new function that merges the results of both
	     * functions.
	     */
	    newValue = function (...args) {
	      return defaults(clsValue.call(this, ...args), parentValue.call(this, ...args));
	    };
	  } else if (isClsValueFunction) {
	    /*
	     * Merge a class function with a parent object.
	     *
	     * We'll create this as a new function that does the merge at
	     * call-time.
	     */
	    newValue = function (...args) {
	      return defaults(clsValue.call(this, ...args), parentValue);
	    };
	  } else if (isParentValueFunction) {
	    /*
	     * Merge a class object with a parent function.
	     *
	     * We'll create this as a new function that does the merge at
	     * call-time.
	     */
	    newValue = function (...args) {
	      return defaults(clsValue, parentValue.call(this, ...args));
	    };
	  } else {
	    return false;
	  }

	  /*
	   * Always place this on the class body. This is in part for
	   * backwards-compatibility reasons, where we'd always merge onto the class
	   * body.
	   */
	  cls[attr] = newValue;

	  /* If this came from the prototype, set it there as well. */
	  if (onProto) {
	    clsProto[attr] = newValue;
	  }
	  return merged;
	}

	/**
	 * Copy a static attribute to a class's prototype.
	 *
	 * Version Added:
	 *     2.0
	 *
	 * Args:
	 *     cls (function):
	 *         The subclass constructor.
	 *
	 *     clsProto (object):
	 *         The subclass prototype.
	 *
	 *     attr (string):
	 *         The static attribute name to copy.
	 *
	 * Returns:
	 *     boolean:
	 *     ``true`` if an attribute was copied. ``false`` if it was not.
	 */
	function _copyPrototypeAttr(cls, clsProto, attr) {
	  if (!clsProto.hasOwnProperty(attr) && cls.hasOwnProperty(attr)) {
	    clsProto[attr] = cls[attr];
	    return true;
	  }
	  return false;
	}

	/**
	 * Prepare a subclass's options and state.
	 *
	 * This is used when defining base classes or subclasses. It takes in any
	 * options provided when applying a decorator and updated the state on the
	 * resulting class accordingly.
	 *
	 * Version Added:
	 *     2.0
	 *
	 * Args:
	 *     cls (function):
	 *         The constructor for the subclass being prepared.
	 *
	 *     options (object):
	 *         The options for the preparation. See :js:class:`SubclassOptions`.
	 *
	 * Returns:
	 *     object:
	 *     Information available to the caller. See :js:class:`SubclassPrepInfo`.
	 */
	function _prepareSubclass(cls, options) {
	  const parentProto = Object.getPrototypeOf(cls);
	  const parentOptions = parentProto.__spinaOptions || {};
	  const clsProto = cls.prototype;
	  const mergeOptions = {};
	  if (options.mixins) {
	    /* Apply any mixins to the subclass. */
	    applyMixins(cls, options.mixins);
	  }
	  if (options.prototypeAttrs || parentOptions.prototypeAttrs) {
	    /*
	     * Copy any static attributes requested to be added to the prototype
	     * on either the parent class or subclass.
	     *
	     * If there are attributes on both, we need to ensure we only copy
	     * them once. The final list of attributes will be set on the
	     * subclass's stored list of options, for use by any subclasses of
	     * the subclass.
	     */
	    const seenParentAttrs = [];
	    const seenClassAttrs = [];
	    const seen = {};
	    if (parentOptions.prototypeAttrs) {
	      for (const attr of parentOptions.prototypeAttrs) {
	        if (_copyPrototypeAttr(cls, clsProto, attr)) {
	          /* The attribute has been copied. */
	          seen[attr] = true;
	        }
	        seenParentAttrs.push(attr);
	      }
	    }
	    if (options.prototypeAttrs) {
	      for (const attr of options.prototypeAttrs) {
	        if (!seen[attr]) {
	          _copyPrototypeAttr(cls, clsProto, attr);
	          seenClassAttrs.push(attr);
	        }
	      }
	      if (seenParentAttrs.length > 0 && seenClassAttrs.length > 0) {
	        /*
	         * We combined the attributes on both. Store the new list for
	         * subclasses.
	         *
	         * Note that we're only here if both the parent and subclass
	         * both define options.
	         */
	        mergeOptions.prototypeAttrs = seenParentAttrs.concat(seenClassAttrs);
	      }
	    }
	  }

	  /*
	   * For any auto-extended static attributes set on both the parent class
	   * and the decorated class, apply a `_.defaults(...)` to the attributes.
	   */
	  if (options.automergeAttrs || parentOptions.automergeAttrs) {
	    /*
	     * Go through all auto-extended object attributes of a parent class.
	     * Unless skipped by the subclass, merge the parent and subclass's
	     * values into the subclass.
	     *
	     * This is used to make it easy to merge attributes like
	     * `BaseView.events` or `BaseModel.defaults`.
	     */
	    const seenParentAttrs = [];
	    const seenClassAttrs = [];
	    const seen = {};
	    const skipped = {};
	    let skipAll = false;
	    if (options.skipParentAutomergeAttrs === true) {
	      skipAll = true;
	    } else if (isArray(options.skipParentAutomergeAttrs)) {
	      for (const attr of options.skipParentAutomergeAttrs) {
	        skipped[attr] = true;
	      }
	    }

	    /*
	     * We're duplicating some work here between both loops, but since this
	     * is all about initialization of the app (we have to invoke this for
	     * each subclass), we should avoid unwanted loops.
	     *
	     * So it's intentional that we're not just building up a list of
	     * attributes up-front and doing this in one go.
	     *
	     * In practice, in most cases, we'll never be working with both
	     * sets of options, so we will only need to loop once.
	     */
	    if (!skipAll && parentOptions.automergeAttrs) {
	      for (const attr of parentOptions.automergeAttrs) {
	        if (!skipped[attr]) {
	          if (_automergeAttr(cls, clsProto, parentProto, attr)) {
	            /* The attribute has been merged. */
	            seen[attr] = true;
	          }
	          seenParentAttrs.push(attr);
	        }
	      }
	    }
	    if (options.automergeAttrs) {
	      for (const attr of options.automergeAttrs) {
	        if (!seen[attr]) {
	          _automergeAttr(cls, clsProto, parentProto, attr);
	          seenClassAttrs.push(attr);
	        }
	      }
	    }
	    if (skipped || seenParentAttrs.length > 0 && seenClassAttrs.length > 0) {
	      /*
	       * We combined the attributes on both. Store the new list for
	       * subclasses.
	       *
	       * Note that we're only here if both the parent and subclass
	       * both define options.
	       */
	      mergeOptions.automergeAttrs = seenParentAttrs.concat(seenClassAttrs);
	    }
	  }
	  const hasOptions = !isEmpty(options);
	  const hasParentOptions = !isEmpty(parentOptions);
	  let spinaOptions;
	  if (hasOptions && hasParentOptions) {
	    /*
	     * Merge in any parent options, so they'll apply to subclasses.
	     */
	    spinaOptions = defaults(mergeOptions, options, parentOptions);
	    if (spinaOptions.hasOwnProperty('automergeAttrs') && spinaOptions.automergeAttrs.length === 0) {
	      /* We've probably emptied out the list above. Remove this. */
	      delete spinaOptions.automergeAttrs;
	    }
	  } else if (hasParentOptions) {
	    /*
	     * Just reference the parent options, saving memory. This is likely
	     * to be the common case.
	     */
	    spinaOptions = parentOptions;
	  } else {
	    /*
	     * Just reference the options (even if empty), saving memory. We
	     * won't have mergeOptions, since we had nothing above to merge
	     * together.
	     */
	    spinaOptions = options;
	  }
	  cls.__spinaOptions = spinaOptions;
	  return {
	    parentProto: parentProto
	  };
	}

	/*
	 * Define an intermediary base class that a Spina base class can extend from.
	 *
	 * This base class will sit in-between a defined class and a parent base class
	 * (such as :js:class:`Backbone.Model`). It will contain special constructor
	 * logic for managing Spina deferred object initialization, and contain any
	 * mixins needed.
	 *
	 * This is used like:
	 *
	 * .. code-block:: javascript
	 *
	 *    class MyBaseClass extends spinaBaseClassExtends(Object) {
	 *        ...
	 *    }
	 *
	 *    // or
	 *
	 *    class MyBaseClass extends spinaBaseClassExtends(SomeLibrary.BaseClass) {
	 *        ...
	 *    }
	 *
	 * Resulting in a hierarchy like ``MyBaseClass -> <intermediary> -> Object``.
	 *
	 * The intermediary base class provides an ``initObject()`` method that
	 * handles the object initialization, which will be invoked by a subclass
	 * (in cooperation with :js:func:`spinaSubclass`) to perform any
	 * initialization required.
	 *
	 * If making a base class off of a prototype-based class, ``initObject()``
	 * will default to invoking the constructor.
	 *
	 * If making a base class off a ES6 class, then either an explicit
	 * ``options.initObject`` is required or the class being defined must provide
	 * an explicit :js:func`initObject` method. These are required since ES6
	 * class constructors can't be invoked manually.
	 *
	 * The base class being defined can't be instantiated directly, and will
	 * raise a :js:class:`TypeError` if attempted. It must be subclassed, and the
	 * subclass must be decorated by :js:func:`spinaSubclass`.
	 *
	 * Version Changed:
	 *     2.0:
	 *     * Added a whole new set of options for controlling class and subclass
	 *       construction. See :js:class:`BaseClassExtendsOptions`.
	 *
	 *     * Added a built-in ``extend()`` method for base classes, which can be
	 *       used to allow prototype-based classes to inherit from Spina classes.
	 *
	 * Args:
	 *     BaseClass (function):
	 *         The constructor for the base class.
	 *
	 *     options (object, optional):
	 *         Options used to control the setup of the base class.
	 *
	 *         See :js:class:`BaseClassExtendsOptions`.
	 *
	 * Returns:
	 *     function:
	 *     A constructor for a new Spina base class inheriting from the provided
	 *     base class.
	 */
	function spinaBaseClassExtends(BaseClass, options = {}) {
	  /* Use a heuristic to guess if this is a ES6 class or a prototype. */
	  const props = Object.getOwnPropertyDescriptor(BaseClass, 'prototype');
	  const isClass = !props.writable;
	  const classID = ++_spinaClassCount;

	  /* NOTE: We use ['name'] syntax to help satisfy TypeScript and ESLint. */
	  const name = options.name || BaseClass['name'] || `_SpinaBaseClass${classID}`;
	  const initObject = options.initObject || BaseClass.prototype.initObject || (isClass ? function () {} : BaseClass);

	  /* Construct the new intermediary base class. */
	  const cls = {
	    [name]: class extends BaseClass {
	      /*
	       * We set both of these because sometimes we need to check an
	       * instance, and sometimes we need to check a prototype. We don't
	       * always have access to both, and we can't have a TypeScript
	       * interface governing static attributes.
	       */
	      static __spinaObjectID = classID;
	      __spinaObjectID = classID;

	      /**
	       * Create a prototype-based subclass of a base class.
	       *
	       * This can be used to allow existing prototype-based code to inherit
	       * from a Spina class (either a base class or a subclass).
	       *
	       * It acts as a replacement for Backbone's ``.extend()`` methods, and
	       * allows codebases to transition base classes to ES6 classes without
	       * having to break compatibility with prototype-based subclsases.
	       *
	       * Version Added:
	       *     3.0:
	       *     * Added ``spinaOptions``, for controlling inheritance.
	       *     * All arguments are now optional.
	       *
	       * Version Added:
	       *     2.0
	       *
	       * Args:
	       *     protoProps (object):
	       *         Properties to apply to the prototype.
	       *
	       *     staticProps (object):
	       *         Static properties to apply to the constructor function
	       *         itself.
	       *
	       * Returns:
	       *     function:
	       *     The constructor for the resulting prototype-based subclass.
	       */
	      static extend(protoProps = undefined, staticProps = undefined, spinaOptions = undefined) {
	        const parentClass = this;
	        const cls = class extends parentClass {};
	        if (protoProps) {
	          Object.assign(cls.prototype, protoProps);
	        }
	        if (staticProps) {
	          Object.assign(cls, staticProps);
	        }
	        if (spinaOptions) {
	          return spinaSubclass(spinaOptions)(cls);
	        } else {
	          return spinaSubclass(cls);
	        }
	      }

	      /**
	       * Construct the object.
	       *
	       * For the base class, if in constructing mode, this will return a
	       * new prototype for the instantiated object, bypassing any further
	       * constructors.
	       *
	       * If not in constructing mode (the base class was constructed
	       * manually or through a non-Spina subclass), this will raise an
	       * exception.
	       *
	       * Args:
	       *     ...args (Array):
	       *         Any arguments passed to the constructor.
	       *
	       *         This will be used to check if we're in Spina constructing
	       *         mode.
	       *
	       * Returns:
	       *     object:
	       *     The prototype for the instantiated object.
	       *
	       * Raises:
	       *     TypeError:
	       *         This base class is being constructed manually, or the
	       *         subclass being constructed is not set up as a Spina object
	       *         subclass.
	       */
	      constructor(...args) {
	        if (args[0] === _constructing) {
	          /*
	           * Skip calling super() and instead create the target object
	           * being instantiated.
	           *
	           * We want to do this at this point, all the way down the
	           * constructor stack so that all constructors can properly
	           * set things up.
	           */
	          if (new.target.prototype.__spinaObjectID === classID) {
	            throw TypeError(`Failed to instantiate ${name} subclass ` + `(${new.target.name}). It was not set up with ` + 'spinaSubclass() or @spina.');
	          }
	          return Object.create(new.target.prototype);
	        } else {
	          throw TypeError(`${name} is abstract and cannot be instantiated directly.`);
	        }
	      }

	      /**
	       * Initialize the object.
	       *
	       * This will be called on the object once the constructor chain has
	       * finished. All provided arguments will be passed.
	       *
	       * Args:
	       *     ...args (Array):
	       *         Any arguments passed to the constructor.
	       */
	      initObject(...args) {
	        initObject.apply(this, args);
	      }
	    }
	  }[name];
	  _prepareSubclass(cls, options);
	  return cls;
	}

	/*
	 * Internal function to set up a subclass of a Spina class.
	 *
	 * This must be used for any classes derived from a base class that uses
	 * :js:func:`spinaBaseClassExtends`. It will ensure that object
	 * initialization only happens once the entire constructor chain has finished.
	 *
	 * The result is an intermediary class that has custom constructor logic,
	 * but otherwise behaves like the wrapped argument.
	 *
	 * Version Added:
	 *     2.0:
	 *     Separated out the main logic from :js:func:`spinaSubclass`, and made
	 *     the following improvements:
	 *
	 *     * Added options for controlling subclass construction.
	 *       See :js:class:`SubclassOptions`.
	 *
	 *     * Added a built-in ``extend()`` method for subclasses, which can be
	 *       used to allow prototype-based classes to inherit from Spina classes.
	 *
	 *     * Instances of the subclass are now the wrapper class, rather than
	 *       the wrapped class.
	 *
	 * Args:
	 *     BaseClass (function):
	 *         The constructor for the base class.
	 *
	 *     options (object, optional):
	 *         Options used to control the setup of the subclass.
	 *
	 *         See :js:class:`SubclassOptions`.
	 *
	 * Returns:
	 *     function:
	 *     A constructor for a new Spina subclass inheriting from a provided
	 *     Spina class.
	 */
	function _makeSpinaSubclass(BaseClass, options = {}) {
	  console.assert(BaseClass.__spinaObjectID !== undefined);
	  const classID = ++_spinaClassCount;
	  let name = options.name;
	  if (!name) {
	    const clsName = (BaseClass.hasOwnProperty('name') ? BaseClass['name'] : '') || `SpinaSubclass${classID}`;
	    name = `_${clsName}_`;
	  }
	  const prepInfo = _prepareSubclass(BaseClass, options);
	  const parentProto = prepInfo.parentProto;
	  const cls = {
	    [name]: class extends BaseClass {
	      /*
	       * We set both of these because sometimes we need to check an
	       * instance, and sometimes we need to check a prototype. We don't
	       * always have access to both, and we can't have a TypeScript
	       * interface governing static attributes.
	       */
	      static __spinaObjectID = classID;
	      __spinaObjectID = classID;

	      /* This provides compatibility with Backbone's __super__. */
	      __super__ = parentProto;

	      /**
	       * Construct the object.
	       *
	       * This is used for every Spina wrapper class up the constructor
	       * chain. When run on the Spina wrapper for the class being
	       * constructed, this will create a new instance of that object
	       * (omitting the wrapper class) and then initialize it with the
	       * ``initObject()`` method on the class.
	       *
	       * If this is run for a constructor further up the chain (between the
	       * constructed class and the base class), it will do a sanity check
	       * to make sure the object being constructed is in fact set up as a
	       * Spina subclass, and then continue up the chain.
	       *
	       * Args:
	       *     ...args (Array):
	       *         Any arguments passed to the constructor.
	       *
	       *         This will be used to check if we're in Spina constructing
	       *         mode. They'll also be passed to ``initObject()`` when
	       *         returning a new instance.
	       *
	       * Returns:
	       *     object:
	       *     The instance of the class, if this is the constructor for the
	       *     class being constructed.
	       *
	       * Raises:
	       *     TypeError:
	       *         A subclass of this was being constructed but wasn't set up
	       *         as a Spina object.
	       */
	      constructor(...args) {
	        if (args && args[0] === _constructing) {
	          super(...args);
	        } else {
	          const target = new.target;
	          if (target !== cls && target.__spinaObjectID === classID) {
	            throw TypeError(`Failed to instantiate ${name} subclass ` + `(${new.target.name}). It was not set up with ` + 'spinaSubclass() or @spina.');
	          }
	          super(_constructing, ...args);

	          /*
	           * NOTE: We need to reference initObject this way for typing,
	           *       since TypeScript doesn't know yet what this is.
	           */
	          if (target === cls && this['initObject']) {
	            /*
	             * This is the object being created, and we're at the tail
	             * end of the constructor chain. We can now initialize the
	             * object state.
	             */
	            this['initObject'](...args);
	          }
	        }
	      }
	    }
	  }[name];
	  return cls;
	}

	/* Declared stubs for the different decorator invocations. */

	/*
	 * Decorator used to set up a subclass of a Spina class.
	 *
	 * This must be used for any classes derived from a base class that uses
	 * :js:func:`spinaBaseClassExtends`. It will ensure that object
	 * initialization only happens once the entire constructor chain has finished.
	 *
	 * The result is an intermediary class that has custom constructor logic,
	 * but otherwise behaves like the wrapped argument.
	 *
	 * Version Changed:
	 *     3.0:
	 *     Added initial support for Stage 3 decorators in TypeScript/JavaScript.
	 *
	 * Version Changed:
	 *     2.0:
	 *     * Added options for controlling subclass construction.
	 *       See :js:class:`SubclassOptions`.
	 *
	 *     * Added a built-in ``extend()`` method for subclasses, which can be
	 *       used to allow prototype-based classes to inherit from Spina classes.
	 *
	 *     * Instances of the subclass are now the wrapper class, rather than
	 *       the wrapped class.
	 *
	 * Args:
	 *     baseClassOrOptions (function or object):
	 *         The class being subclassed, or options for subclassing, depending
	 *         on the way this is called.
	 *
	 *         See :js:class:`SubclassOptions` for options.
	 *
	 *     context (object, optional):
	 *         Decorator context, used for Stage 3 Decorator support.
	 *
	 *         This is ignored, but is necessary to declare for modern TypeScript
	 *         and JavaScript decorators.
	 *
	 * Returns:
	 *     function:
	 *     A constructor for a new Spina subclass inheriting from a provided
	 *     Spina class.
	 */
	function spinaSubclass(baseClassOrOptions, context) {
	  if (typeof baseClassOrOptions === 'function') {
	    /* This is a class. */
	    return _makeSpinaSubclass(baseClassOrOptions);
	  } else {
	    /* These are options. */
	    return function (BaseClass, context) {
	      return _makeSpinaSubclass(BaseClass, baseClassOrOptions);
	    };
	  }
	}

	/**
	 * Applies a mixin to a class/prototype.
	 *
	 * This will register everything in the provided mixins into the
	 * target class/prototype.
	 *
	 * Version Changed:
	 *     2.0:
	 *     * Added support for passing in plain objects to merge in.
	 *     * Static members of ES6 classes are now mixed in to the class body.
	 *
	 * Args:
	 *     target (function):
	 *         The target class to mix the mixins into.
	 *
	 *     mixins (Array of function or Array of object):
	 *         The array of mixins to mix into the target.
	 */
	function applyMixins(target, mixins) {
	  const targetProto = target.prototype;
	  for (const mixin of mixins) {
	    const mixinBody = mixin['prototype'] || mixin;
	    for (const name of Object.getOwnPropertyNames(mixinBody)) {
	      if (name !== 'prototype') {
	        Object.defineProperty(targetProto, name, Object.getOwnPropertyDescriptor(mixinBody, name) || {});
	      }
	    }
	    if (mixinBody !== mixin) {
	      for (const name of Object.getOwnPropertyNames(mixin)) {
	        if (name !== 'prototype') {
	          Object.defineProperty(target, name, Object.getOwnPropertyDescriptor(mixin, name) || {});
	        }
	      }
	    }
	  }
	}

	/** Simple alias for defining subclasses. */
	const spina = spinaSubclass;
	var _class$1$1;

	/**
	 * Base class for collections.
	 *
	 * This extends :js:class:`Backbone.Collection`, with types, and making it
	 * available as a Spina object that can be subclassed using ES6 classes.
	 */
	class BaseCollection extends spinaBaseClassExtends(backboneExports.Collection, {
	  prototypeAttrs: ['model', 'url']
	}) {
	  /**
	   * The type of model stored in the collection.
	   *
	   * If provided, this must be defined as static.
	   *
	   * Version Added:
	   *     2.0:
	   *     Starting in Spina 2, this must be defined as static.
	   */
	  static model;

	  /**
	   * The URL for server-side communication.
	   *
	   * If provided, this must be static. It can be a string with a URL, or a
	   * function that returns a string. The function can access ``this``.
	   *
	   * Version Added:
	   *     2.0:
	   *     Starting in Spina 2, this must be defined as static.
	   */
	  static url;

	  /**
	   * Return the URL for the model.
	   *
	   * Consumers should use this instead of accessing :js:attr:`url`
	   * directly. It takes care of accessing either a static or dynamic
	   * value for :js:attr:`url`.
	   *
	   * Version Added:
	   *     3.0
	   *
	   * Returns:
	   *     string:
	   *     The URL to the model, or ``null`` if there isn't a URL.
	   */
	  getURL() {
	    return result(this, 'url');
	  }
	}

	/**
	 * Generic class for standalone collections.
	 *
	 * Unlike :js:class:`BaseCollection`, this does not need to be subclassed,
	 * and can be used to create a standalone instance.
	 */
	let Collection = spina(_class$1$1 = class Collection extends BaseCollection {
	  /*
	   * Default value for the model. This will be overridden if provided
	   * in options.
	   */
	  static model = backboneExports.Model;
	}) || _class$1$1;

	/**
	 * Spina model classes.
	 *
	 * This provides classes and typing for creating new model classes.
	 */

	/**
	 * A base type for attributes or defaults for a model.
	 *
	 * Version Added:
	 *     2.0
	 */

	/**
	 * Base class for models.
	 *
	 * This extends :js:class:`Backbone.Model`, with types, and making it
	 * available as a Spina object that can be subclassed using ES6 classes.
	 *
	 * Note that unlike the typing for :js:class:`Backbone.Model`, we prioritize
	 * the option extensions in the generics, and we set it to ``unknown`` by
	 * default (``@types/backbone`` has a default of ``any``, which removes all
	 * type safety for options).
	 */
	class BaseModel extends spinaBaseClassExtends(backboneExports.Model, {
	  automergeAttrs: ['defaults'],
	  prototypeAttrs: ['defaults', 'idAttribute', 'urlRoot', 'url']
	}) {
	  /**
	   * The defined default attributes for the model.
	   *
	   * If provided, this must be static. It can be a hash of attribute names
	   * to values, or a function that returns a hash. The function can access
	   * ``this``.
	   *
	   * Version Added:
	   *     2.0:
	   *     Starting in Spina 2, this must be defined as static.
	   */
	  static defaults = {};

	  /**
	   * The name of the ID attribute to set.
	   *
	   * If provided, this must be static.
	   *
	   * Version Added:
	   *     2.0:
	   *     Starting in Spina 2, this must be defined as static.
	   */
	  static idAttribute = 'id';

	  /**
	   * The root for any relative URLs.
	   *
	   * If provided, this must be static. It can be a string with the URL root,
	   * or a function that returns a string. The function can access ``this``.
	   *
	   * Version Added:
	   *     2.0:
	   *     Starting in Spina 2, this must be defined as static.
	   */
	  static urlRoot;

	  /**
	   * Return the default attributes for the model.
	   *
	   * Consumers should use this instead of accessing :js:attr:`defaults`
	   * directly. It takes care of accessing either a static or dynamic
	   * value for :js:attr:`defaults`.
	   *
	   * Version Added:
	   *     3.0
	   *
	   * Returns:
	   *     object:
	   *     The mapping of attribute names to default values.
	   */
	  getDefaultAttrs() {
	    return result(this, 'defaults');
	  }

	  /**
	   * Return the URL for the model.
	   *
	   * Consumers should use this instead of accessing :js:attr:`url`
	   * directly. It takes care of accessing either a static or dynamic
	   * value for :js:attr:`url`.
	   *
	   * Version Added:
	   *     3.0
	   *
	   * Returns:
	   *     string:
	   *     The URL to the model, or ``null`` if there isn't a URL.
	   */
	  getURL() {
	    return result(this, 'url');
	  }

	  /**
	   * Return the root for any relative URLs.
	   *
	   * Consumers should use this instead of accessing :js:attr:`urlRoot`
	   * directly. It takes care of accessing either a static or dynamic
	   * value for :js:attr:`urlRoot`.
	   *
	   * Version Added:
	   *     3.0
	   *
	   * Returns:
	   *     string:
	   *     The root URL, or ``null`` if there isn't a root URL.
	   */
	  getURLRoot() {
	    return result(this, 'urlRoot');
	  }
	}
	var _class$f;

	/**
	 * Type for routes on a router.
	 *
	 * Version Added:
	 *     2.0
	 */

	/**
	 * Base class for a router.
	 */
	class BaseRouter extends spinaBaseClassExtends(backboneExports.Router, {
	  automergeAttrs: ['routes'],
	  prototypeAttrs: ['routes']
	}) {
	  /**
	   * The defined routes for the router.
	   *
	   * If provided, this must be static. It can be a hash of route keys to
	   * handler functions, or a function that returns a hash. The function
	   * can access ``this``.
	   *
	   * Version Added:
	   *     2.0:
	   *     Starting in Spina 2, this must be defined as static.
	   */
	  static routes;
	}

	/**
	 * Generic class for standalone routers.
	 *
	 * Unlike :js:class:`BaseRouter`, this does not need to be subclassed,
	 * and can be used to create a standalone instance.
	 */
	let Router = spinaSubclass(_class$f = class Router extends BaseRouter {
	  /* Prototype for Router. */
	}) || _class$f;

	/**
	 * A type for a hash mapping DOM attributes to values.
	 *
	 * Version Added:
	 *     2.0
	 */

	/**
	 * Options for rendering views into an element.
	 */

	/**
	 * Base class for views.
	 *
	 * This extends :js:class:`Backbone.View`, with types, and making it
	 * available as a Spina object that can be subclassed using ES6 classes.
	 */
	class BaseView extends spinaBaseClassExtends(backboneExports.View, {
	  automergeAttrs: ['attributes', 'events', 'modelEvents'],
	  prototypeAttrs: ['attributes', 'className', 'events', 'id', 'modelEvents', 'tagName']
	}) {
	  /**
	   * The defined map of attribute names to values for a created element.
	   *
	   * If provided, this must be static. It can be a hash of attributes, or a
	   * function that returns a hash. The function can access ``this``.
	   *
	   * Version Added:
	   *     2.0:
	   *     Starting in Spina 2, this must be defined as static, rather than
	   *     an instance variable. It can also now be a function.
	   */
	  static attributes;

	  /**
	   * The defined class name (or names) for a view.
	   *
	   * If provided, this must be static. It can be a string consisting of
	   * space-separated class names, or a function that returns a string. The
	   * function can access ``this``.
	   *
	   * Version Added:
	   *     2.0:
	   *     Starting in Spina 2, this must be defined as static, rather than
	   *     an instance variable. It can also now be a function.
	   */
	  static className;

	  /**
	   * The defined map of events to function handler names.
	   *
	   * If provided, this must be static. It can be a hash of event descriptors
	   * to handler functions, or a function that returns a hash. The function
	   * can access ``this``.
	   *
	   * Version Added:
	   *     2.0:
	   *     Starting in Spina 2, this must be defined as static, rather than
	   *     an instance variable.
	   */
	  static events;

	  /**
	   * The ID of the created element for the view.
	   *
	   * If provided, this must be static. It can be a string consisting of
	   * an ID for the element, or a function that returns a string. The
	   * function can access ``this``.
	   *
	   * Version Added:
	   *     2.0:
	   *     Starting in Spina 2, this must be defined as static, rather than
	   *     an instance variable. It can also now be a function.
	   */
	  static id;

	  /**
	   * A mapping of model events to callback handlers/names.
	   *
	   * On render, each of these will be connected automatically, allowing
	   * model state or events to update the view as needed.
	   *
	   * If provided, this must be static. It can be a hash of event names
	   * to handler functions, or a function that returns a hash. The function
	   * can access ``this``.
	   *
	   * Version Added:
	   *     2.0:
	   *     Starting in Spina 2, this must be defined as static, rather than
	   *     an instance variable. It can also now be a function.
	   */
	  static modelEvents = {};

	  /**
	   * The defined tag name to use for the view.
	   *
	   * If provided, this must be static. It can be a string consisting of
	   * a tag name for the element, or a function that returns a string. The
	   * function can access ``this``.
	   *
	   * Version Added:
	   *     2.0:
	   *     Starting in Spina 2, this must be defined as static, rather than
	   *     an instance variable. It can also now be a function.
	   */
	  static tagName = 'div';

	  /**********************
	   * Instance variables *
	   **********************/

	  /*
	   * These variables above are copied to the prototype and made available
	   * to the instance. Declare them to help with type checking.
	   */

	  /**
	   * Whether the view has been rendered at least once.
	   */
	  rendered = false;

	  /**
	   * Whether to auto-connect model events on render.
	   */
	  autoconnectModelEvents = true;
	  _modelEventsConnected = false;

	  /**
	   * Connect model events to handlers.
	   *
	   * This will loop through :js:attr:`modelEvents`, connecting any events
	   * on the view's model to the handlers provided.
	   */
	  connectModelEvents() {
	    const modelEvents = result(this, 'modelEvents');
	    const model = this.model;
	    if (!this._modelEventsConnected && modelEvents && model) {
	      for (const eventName in modelEvents) {
	        if (modelEvents.hasOwnProperty(eventName)) {
	          const eventValue = modelEvents[eventName];
	          const eventFunction = isFunction$1(eventValue) ? eventValue : this[eventValue];
	          if (eventFunction) {
	            this.listenTo(model, eventName, eventFunction);
	          }
	        }
	      }
	      this._modelEventsConnected = true;
	    }
	  }

	  /**
	   * Disconnect model events from handlers.
	   *
	   * This will loop through :js:attr:`modelEvents`, disconnecting any events
	   * formerly connected on the view's model.
	   */
	  disconnectModelEvents() {
	    const modelEvents = result(this, 'modelEvents');
	    const model = this.model;
	    if (this._modelEventsConnected && modelEvents && model) {
	      for (const eventName in modelEvents) {
	        if (modelEvents.hasOwnProperty(eventName)) {
	          const eventValue = modelEvents[eventName];
	          const eventFunction = isFunction$1(eventValue) ? eventValue : this[eventValue];
	          if (eventFunction) {
	            this.stopListening(model, eventName, eventFunction);
	          }
	        }
	      }
	      this._modelEventsConnected = false;
	    }
	  }

	  /**
	   * Return the DOm element attributes for this view's element.
	   *
	   * Consumers should use this instead of accessing :js:attr:`attributes`
	   * directly. It takes care of accessing either a static or dynamic
	   * value for :js:attr:`attributes`.
	   *
	   * Version Added:
	   *     3.0
	   *
	   * Returns:
	   *     object:
	   *     The mapping of attribute names to values.
	   */
	  getAttributes() {
	    return result(this, 'attributes') || {};
	  }

	  /**
	   * Return the class name (or names) used for the view's element.
	   *
	   * Consumers should use this instead of accessing :js:attr:`className`
	   * directly. It takes care of accessing either a static or dynamic
	   * value for :js:attr:`className`.
	   *
	   * Version Added:
	   *     3.0
	   *
	   * Returns:
	   *     string:
	   *     The class name for the view's element.
	   */
	  getClassName() {
	    return result(this, 'className') || '';
	  }

	  /**
	   * Return the ID used for the view's element.
	   *
	   * Consumers should use this instead of accessing :js:attr:`id` directly.
	   * takes care of accessing either a static or dynamic value for
	   * :js:attr:`id`.
	   *
	   * Version Added:
	   *     3.0
	   *
	   * Returns:
	   *     string:
	   *     The element ID, or ``null``.
	   */
	  getID() {
	    return result(this, 'id');
	  }

	  /**
	   * Return the tag name used for the view's element.
	   *
	   * Consumers should use this instead of accessing :js:attr:`tagName`
	   * directly. It takes care of accessing either a static or dynamic
	   * value for :js:attr:`tagName`.
	   *
	   * Version Added:
	   *     3.0
	   *
	   * Returns:
	   *     string:
	   *     The tag name for the view's element.
	   */
	  getTagName() {
	    return result(this, 'tagName');
	  }

	  /**
	   * Show the view.
	   *
	   * Returns:
	   *     object:
	   *     This object, for chaining.
	   */
	  show() {
	    this.$el.show();
	    return this;
	  }

	  /**
	   * Hide the view.
	   *
	   * Returns:
	   *     object:
	   *     This object, for chaining.
	   */
	  hide() {
	    this.$el.hide();
	    return this;
	  }

	  /**
	   * Render the view into another element.
	   *
	   * This is a convenience around calling :js:meth:`BaseView.render` and
	   * then appending the view's element somewhere. This is a pattern we use
	   * a lot in our code.
	   *
	   * This can optionally clear out the target element first, and can
	   * optionally prepend rather than append.
	   *
	   * Args:
	   *     targetEl (Element or jQuery):
	   *         The element to render into.
	   *
	   *     options (object, optional):
	   *         Options for inserting the view's element.
	   *
	   * Option Args:
	   *     empty (boolean, optional):
	   *         Whether to empty out the target element before inserting the
	   *         view's element.
	   *
	   *     prepend (boolean, optional):
	   *         Whether to prepend the view's element, instead of appending.
	   *
	   * Returns:
	   *     object:
	   *     This object, for chaining.
	   */
	  renderInto(targetEl, options = {}) {
	    if (!isElement(targetEl)) {
	      targetEl = targetEl[0];
	    }
	    if (options.empty) {
	      targetEl.innerHTML = '';
	    }
	    if (options.prepend) {
	      targetEl.insertBefore(this.el, targetEl.firstChild);
	    } else {
	      targetEl.appendChild(this.el);
	    }
	    this.render();
	    return this;
	  }

	  /**
	   * Render the view.
	   *
	   * This will take care to connect model events the first time that the
	   * view is rendered, and avoid re-connecting on subsequent renders.
	   *
	   * To simplify view management, this will call :js:func:`initialRender`
	   * on the first render, and :js:func:`eachRender` on each following
	   * render. These are cheap, don't require returning ``this``, and will
	   * aid in simplifying some views that are already either using this pattern
	   * or trying to avoid side effects for multiple render calls.
	   *
	   * Before rendering, this will trigger a ``rendering`` event. After
	   * render, this will trigger a ``rendered`` event. Both take an object
	   * parameter with an ``initialRender`` boolean.
	   *
	   * Version Changed:
	   *     3.0:
	   *     * Added the ``rendering`` and ``rendered`` events.
	   *     * The :js:attr:`rendered` state is now set after :js:func:`onRender`
	   *       is called, not after :js:func:`onInitialRender`.
	   *
	   * Returns:
	   *     object:
	   *     This object, for chaining.
	   */
	  render() {
	    const initialRender = !this.rendered;
	    const signalState = {
	      initialRender: initialRender
	    };
	    this.trigger('rendering', signalState);
	    if (initialRender) {
	      if (this.autoconnectModelEvents) {
	        this.connectModelEvents();
	      }
	      this.onInitialRender();
	    }
	    this.onRender();
	    this.rendered = true;
	    this.trigger('rendered', signalState);
	    return this;
	  }

	  /**
	   * Remove the view from the DOM.
	   *
	   * This will take care of removing the view's element and any related
	   * elements or state.
	   *
	   * Before removing, this will trigger a ``removing`` event. After removing,
	   * this will trigger a ``removed`` event.
	   *
	   * Version Changed:
	   *     3.1:
	   *     * This now triggers ``removing`` and ``removed`` events.
	   *     * :js:func:`onRemove` is now called before the view's element is
	   *       removed.
	   *
	   * Returns:
	   *     BaseView:
	   *     This object, for chaining.
	   */
	  remove() {
	    this.trigger('removing');
	    this.onRemove();
	    super.remove();
	    this.trigger('removed');
	    return this;
	  }

	  /**
	   * Handle an initial render of the view.
	   *
	   * Subclasses can put their logic here, instead of overriding in
	   * :js:meth:`BaseView.render`.
	   *
	   * Version Changed:
	   *     3.0:
	   *     This function is now protected, not public.
	   */
	  onInitialRender() {}

	  /**
	   * Handle each render of a view.
	   *
	   * Subclasses can put their logic here, instead of overriding in
	   * :js:meth:`BaseView.render`.
	   *
	   * Version Changed:
	   *     3.0:
	   *     This function is now protected, not public.
	   */
	  onRender() {}

	  /**
	   * Handle removing state or elements in this view.
	   *
	   * Subclasses can put their logic here, instead of overriding in
	   * :js:meth:`BaseView.remove`.
	   *
	   * Version Added:
	   *     3.1
	   */
	  onRemove() {}
	}

	const Spina = /*#__PURE__*/Object.defineProperty({
		__proto__: null,
		BaseCollection,
		BaseModel,
		BaseRouter,
		BaseView,
		Collection,
		Router,
		applyMixins,
		spina,
		spinaBaseClassExtends,
		spinaSubclass
	}, Symbol.toStringTag, { value: 'Module' });

	/**
	 * Support for defining, registering, and accessing components.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Type for a child of a component.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * A mapping of names to values for a component's properties.
	 *
	 * These are all properties that may be set when crafting the component,
	 * and are passed to the component during construction.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * A mapping of subcomponent names to handler function names.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Information on a parsed subcomponent.
	 *
	 * This is set when crafting a subcomponent, and can be used by components
	 * to validate and handle the subcomponent.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Type for a component.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Type for a constructor for a component.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * A component tracked in the registry.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * A registry for managing components.
	 *
	 * This takes care of storing the components registered and allows for
	 * retrieval by name.
	 *
	 * Version Added:
	 *     0.5
	 */
	class ComponentRegistry {
	  /**
	   * The map of component names to component classes.
	   */
	  components = {};

	  /**
	   * The map of full subcomponent names to subcomponent information.
	   */
	  subcomponents = {};

	  /**
	   * Return a registered component with the given name.
	   *
	   * Args:
	   *     name (string):
	   *         The name of the component.
	   *
	   * Returns:
	   *     Component:
	   *     The component, if found.
	   *
	   *     If the component was not registered, this will return ``null``.
	   */
	  getComponent(name) {
	    return this.components[name] ?? null;
	  }

	  /**
	   * Return a subcomponent with the specified name.
	   *
	   * Args:
	   *     name (string):
	   *         The full subcomponent name.
	   *
	   * Returns:
	   *     RegisteredSubcomponent:
	   *     The subcomponent information, if found.
	   *
	   *     If the subcomponent was not registered, this will return ``null``.
	   */
	  getSubcomponent(name) {
	    return this.subcomponents[name] ?? null;
	  }

	  /**
	   * Register a component.
	   *
	   * Args:
	   *     component (ComponentCtr):
	   *         The component to register.
	   *
	   *     name (string):
	   *         The name of the component.
	   *
	   *         This should generally be vendor-prefixed.
	   */
	  register(componentClass, name) {
	    const components = this.components;

	    /*
	     * Note that we'll allow reloading if running in Storybook. This is
	     * necessary so that HMR doesn't trigger assertion errors while setting
	     * up a Story after an edited module has been saved and reloaded.
	     */
	    console.assert(!components.hasOwnProperty(name) || window['IS_STORYBOOK'], `Component ${name} is already registered.`);
	    components[name] = componentClass;
	    if (componentClass.subcomponents) {
	      const subcomponents = this.subcomponents;
	      const subcomponentEntries = Object.entries(componentClass.subcomponents);
	      for (const [subcomponentName, funcName] of subcomponentEntries) {
	        subcomponents[`${name}.${subcomponentName}`] = {
	          funcName: funcName,
	          name: subcomponentName,
	          parentComponentClass: componentClass
	        };
	      }
	    }
	  }

	  /**
	   * Unregister a component.
	   *
	   * Args:
	   *     name (string):
	   *         The name of the component to unregister.
	   */
	  unregister(name) {
	    const components = this.components;
	    const componentClass = components[name];
	    console.assert(componentClass !== undefined, `Component ${name} was not registered.`);
	    if (componentClass.subcomponents) {
	      const subcomponents = this.subcomponents;
	      const subcomponentEntries = Object.keys(componentClass.subcomponents);
	      for (const subcomponentName of subcomponentEntries) {
	        delete subcomponents[`${name}.${subcomponentName}`];
	      }
	    }
	    delete components[name];
	  }
	}

	/**
	 * Decorator to register a component.
	 *
	 * This takes an explicit name for the component and registers it so it
	 * can be accessed, crafted, and painted.
	 *
	 * Version Added:
	 *     0.5
	 *
	 * Args:
	 *     name (string):
	 *         The name of the component.
	 *
	 *         This should generally be vendor-prefixed.
	 *
	 * Returns:
	 *     Function:
	 *     The decorator function for the class.
	 */
	function inkComponent(name) {
	  return function (component) {
	    componentRegistry.register(component, name);
	  };
	}

	/**
	 * Return whether an object is a parsed subcomponent.
	 *
	 * Version Added:
	 *     0.5
	 *
	 * Args:
	 *     subcomponentInfo (object):
	 *         The object that may be a parsed subcomponent.
	 *
	 * Returns:
	 *     boolean:
	 *     ``true`` if the object is a parsed subcomponent. ``false`` if it is not.
	 */
	function isSubcomponentInfo(subcomponentInfo) {
	  return subcomponentInfo['isSubcomponent'] === true;
	}

	/**
	 * The main registry for components.
	 *
	 * Version Added:
	 *     0.5
	 */
	const componentRegistry = new ComponentRegistry();

	/**
	 * Utilities for manipulating properties in the DOM.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * A mapping of attribute names to their Element counterparts for setProps().
	 *
	 * Version Added:
	 *     0.5
	 */
	const _SetPropsAliases = {
	  'class': 'className',
	  'tabindex': 'tabIndex'
	};

	/**
	 * Recursively set properties on a DOM element.
	 *
	 * This is a convenience for setting multiple attributes on a DOM element,
	 * recursing into any nested objects (such as ``style``).
	 *
	 * While most attributes are set directly via :js:`Element` attributes, some
	 * will be normalized or set via :js:class:`Element.setAttribute`:
	 *
	 * ``aria-*``:
	 *     These will be normalized to :js:class:`Element.setAttribute` calls.
	 *
	 * ``class``:
	 *     This will be normalized as ``className``.
	 *
	 * ``data-*``:
	 *     These will be normalized to :js:class:`Element.setAttribute` calls.
	 *
	 * Version Added:
	 *     0.5
	 *
	 * Args:
	 *     el (Element):
	 *         The element to set properties on.
	 *
	 *     props (object):
	 *         The properties to set.
	 *
	 * Returns:
	 *     Element:
	 *     The element, for chaining purposes.
	 */
	function setProps(el, props) {
	  /* First, handle the outer properties. */
	  for (const [key, value] of Object.entries(props)) {
	    if (key.startsWith('aria-') || key.startsWith('data-')) {
	      el.setAttribute(key, typeof value === 'string' ? value : String(value));
	    } else if (typeof value === 'object' && el[key] !== undefined) {
	      _mergeInnerProps(el[key], value);
	    } else {
	      el[_SetPropsAliases[key] || key] = value;
	    }
	  }
	  return el;
	}

	/**
	 * Merge properties inside an object.
	 *
	 * This will recursively merge properties from one object into another.
	 * It's used internally by :js:func:`setProps`.
	 *
	 * Version Added:
	 *     0.5
	 *
	 * Args:
	 *     el (object):
	 *         The object to merge properties into.
	 *
	 *     props (object):
	 *         The properties to merge.
	 */
	function _mergeInnerProps(mergeObj, mergeProps) {
	  for (const [key, value] of Object.entries(mergeProps)) {
	    if (typeof value === 'object' && mergeObj[key] !== undefined) {
	      _mergeInnerProps(mergeObj[key], value);
	    } else {
	      mergeObj[key] = value;
	    }
	  }
	}

	/**
	 * Internal support for crafting and painting instances and components.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Type for a crafted component or HTML element.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * An item that can be painted to an element.
	 *
	 * Version Added:
	 *     0.5
	 */

	/* Type stubs for craftComponent(). */

	/**
	 * Craft a component or HTML element.
	 *
	 * This will instantiate the component or element with any provided
	 * properties or children.
	 *
	 * If crafting a component, the component instance will be instantiated,
	 * rendered, and returned.
	 *
	 * If crafting an HTML element, the Element instance will be returned.
	 *
	 * Version Added:
	 *     0.5
	 *
	 * Args:
	 *     nameOrClass (string):
	 *         The name of the component or HTML element to craft.
	 *
	 *     props (object):
	 *         Properties to pass to the component constructor, or Element
	 *         attributes.
	 *
	 *         If crafting an Ink component, these will be passed to the
	 *         constructor.
	 *
	 *         If crafting an HTML element, these will be set as attributes on the
	 *         DOM Element object.
	 *
	 *     ...children (ComponentChild[]):
	 *         Any children to nest within the crafted component.
	 *
	 *         If crafting a component, then children will not be painted
	 *         automatically. It's up to the component to handle each item.
	 *
	 *         If crafting an HTML element, then children will be painted
	 *         automatically.
	 *
	 *         This is not supported for all components or HTML tags.
	 *
	 * Returns:
	 *     Component or HTMLElement:
	 *     The resulting component or HTML Element instance.
	 */
	function craftComponent(nameOrClass, props, ...children) {
	  if (typeof nameOrClass === 'string') {
	    /* This should be a component name, subcomponent name, or tag name. */
	    const ComponentCls = componentRegistry.getComponent(nameOrClass);
	    if (ComponentCls !== null) {
	      return _craftComponentCtr(ComponentCls, nameOrClass, props, children);
	    } else {
	      if (nameOrClass.startsWith('.')) {
	        /*
	         * This is a shortened subcomponent name. It may be invalid,
	         * but we'll record it.
	         */
	        return {
	          children: children,
	          fullName: nameOrClass,
	          funcName: null,
	          isSubcomponent: true,
	          name: nameOrClass.substring(1),
	          props: props || {}
	        };
	      }
	      const registeredSubcomponent = componentRegistry.getSubcomponent(nameOrClass);
	      if (registeredSubcomponent) {
	        return {
	          children: children,
	          fullName: nameOrClass,
	          funcName: registeredSubcomponent.funcName,
	          isSubcomponent: true,
	          name: registeredSubcomponent.name,
	          props: props || {}
	        };
	      } else {
	        return _craftElement(nameOrClass, props, children);
	      }
	    }
	  } else {
	    /* This should be a component class to instantiate. */
	    return _craftComponentCtr(nameOrClass, nameOrClass.name, props, children);
	  }
	}

	/* Type stubs for paintComponent(). */

	/**
	 * Paint a component or HTML element.
	 *
	 * This will craft and then paint a component or HTML element, returning an
	 * element that can be inserted into the DOM.
	 *
	 * If painting a component, the component instance will be instantiated (if
	 * not already an instance), rendered to an element, and returned.
	 *
	 * If painting an HTML element, the Element instance will be returned.
	 *
	 * Version Added:
	 *     0.5
	 *
	 * Args:
	 *     name (string):
	 *         The name of the component or HTML element to craft.
	 *
	 *     props (object):
	 *         Properties to pass to the component constructor, or Element
	 *         attributes.
	 *
	 *         If painting an Ink component, these will be passed to the
	 *         constructor.
	 *
	 *         If painting an HTML element, these will be set as attributes on the
	 *         DOM Element object.
	 *
	 *     ...children (ComponentChild[]):
	 *         Any children to nest within the crafted component.
	 *
	 *         If painting a component, then children will not be painted
	 *         automatically. It's up to the component to handle each item.
	 *
	 *         If painting an HTML element, then children will be painted
	 *         automatically.
	 *
	 *         This is not supported for all components or HTML tags.
	 *
	 * Returns:
	 *     HTMLElement:
	 *     The HTML Element instance.
	 */
	function paintComponent(nameOrClass, props, ...children) {
	  const component = craftComponent(nameOrClass, props, ...children);
	  return isSubcomponentInfo(component) ? component : paintCraftedElements([component])[0];
	}

	/**
	 * Paint an array of crafted components/elements or children to DOM nodes.
	 *
	 * This will loop through the items and convert each to an element using the
	 * following rules:
	 *
	 * 1. If it's an element already, it will be used as-is.
	 * 2. If it's a string, it will be converted to a :js:class:`Text` node.
	 * 3. If it's a component instance, it will be rendered and its element
	 *    returned.
	 *
	 * Note:
	 *     This will not craft components to instances.
	 *
	 *     It's the responsibility of the caller to ensure these are already
	 *     instantiated.
	 *
	 * Version Added:
	 *     0.5
	 *
	 * Args:
	 *     items (PaintableItem or PaintableItem[]):
	 *         The item or items to paint.
	 *
	 * Returns:
	 *     Node[]:
	 *     The painted nodes to insert into the DOM.
	 */
	function paintCraftedElements(items) {
	  if (!Array.isArray(items)) {
	    items = [items];
	  }
	  const nodes = [];
	  for (const item of items) {
	    if (item === null || item === undefined || item === false) {
	      continue;
	    }
	    if (item instanceof Node) {
	      nodes.push(item);
	    } else if (typeof item === 'string') {
	      nodes.push(document.createTextNode(item));
	    } else if (Array.isArray(item)) {
	      /*
	       * This is the result of an inner paintCraftedElements() call for
	       * children of a node. We should have a 1-element array of nodes
	       * that we can inline.
	       */
	      nodes.push(...paintCraftedElements(item));
	    } else if (item['el']) {
	      nodes.push(item['el']);
	    } else {
	      console.assert(false, 'Unsupported render item %o', item);
	    }
	  }
	  return nodes;
	}

	/**
	 * Craft a component instance.
	 *
	 * This will instantiate the component with any provided properties or
	 * children, and render it.
	 *
	 * Version Added:
	 *     0.5
	 *
	 * Args:
	 *     ComponentCls (ComponentCtr):
	 *         The class constructor for instantiating the component.
	 *
	 *     name (string):
	 *         The name of the component to craft.
	 *
	 *     props (object):
	 *         Properties to pass to the component constructor.
	 *
	 *     ...children (ComponentChild[]):
	 *         Any children to nest within the crafted component.
	 *
	 *         Children will not be painted automatically. It's up to the
	 *         component to handle each item.
	 *
	 *         This is not supported for all components. If not supported, an
	 *         assertion will be raised.
	 *
	 * Returns:
	 *     Component:
	 *     The component instance.
	 */
	function _craftComponentCtr(ComponentCls, name, props, children) {
	  const normProps = {};
	  const normAttrs = {};
	  let normClassName = null;

	  /*
	   * Strip out any props we want to set as attributes on the resulting
	   * element, leaving the rest as options for the component.
	   */
	  if (props) {
	    for (const [propKey, propValue] of Object.entries(props)) {
	      if (propKey === 'class' || propKey === 'className') {
	        normClassName = String(propValue);
	      } else if (propKey.startsWith('aria-') || propKey.startsWith('data-') || propKey === 'style') {
	        normAttrs[propKey] = propValue;
	      } else {
	        normProps[propKey] = propValue;
	      }
	    }
	  }
	  normProps['componentCrafted'] = true;

	  /* Create an instance of the component with the normalized props. */
	  const component = new ComponentCls(normProps);

	  /*
	   * Process any children of this component.
	   *
	   * If there are subcomponents, then they will be provided to the
	   * component prior to rendering.
	   *
	   * If there aren't any, but children are provided, then they'll be
	   * passed as children, if the component allows them.
	   */
	  if (children.length > 0) {
	    /* First check if there are any subcomponents included. */
	    let foundSubcomponent = false;
	    for (const rawChild of children) {
	      if (rawChild === null || rawChild === undefined) {
	        continue;
	      }

	      /*
	       * We may get a child, or an array of children. We'll need to
	       * handle both cases.
	       */
	      const normChildren = Array.isArray(rawChild) ? rawChild : [rawChild];
	      for (const child of normChildren) {
	        if (isSubcomponentInfo(child)) {
	          foundSubcomponent = true;
	          let subcomponentFullName = child.fullName;
	          let subcomponentFuncName = child.funcName;
	          if (subcomponentFullName.startsWith('.')) {
	            /*
	             * This was a shortened, pending subcomponent. We need
	             * to finish resolving it now.
	             */
	            subcomponentFullName = `${name}${subcomponentFullName}`;
	            child.fullName = subcomponentFullName;
	            subcomponentFuncName = ComponentCls.subcomponents[child.name];
	            child.funcName = subcomponentFuncName;
	          } else {
	            subcomponentFuncName = child.funcName;
	          }
	          console.assert(subcomponentFullName.startsWith(name), 'Subcomponent %s is not a direct child of %s', subcomponentFullName, name);
	          const func = component[subcomponentFuncName];
	          console.assert(func, 'Component %s is missing subcomponent handler %s', name, subcomponentFuncName);
	          func.call(component, child);
	        } else {
	          console.assert(!foundSubcomponent, 'Found a non-subcomponent child of %s alongside ' + 'subcomponents: %o', name, child);
	        }
	      }
	    }
	    if (!foundSubcomponent) {
	      if (ComponentCls.allowComponentChildren) {
	        const setComponentChildren = component.setComponentChildren;
	        console.assert(setComponentChildren, '%s.allowComponentChildren is true, but ' + '%s.setComponentChildren() does not exist!', component.constructor.name);
	        setComponentChildren.call(component, children);
	      } else {
	        console.assert('Component %s does not support children', name);
	      }
	    }
	  }

	  /* We can now render the component. */
	  component.render();

	  /*
	   * We can now set the attributes and class name from the props, if
	   * provided.
	   */
	  if (normAttrs) {
	    const el = component.el;
	    setProps(el, normAttrs);
	  }
	  if (normClassName) {
	    component.el.classList.add(...normClassName.split(/\s+/));
	  }

	  /* We're done! */
	  return component;
	}

	/**
	 * Craft a component instance.
	 *
	 * This will instantiate the component with any provided properties or
	 * children.
	 *
	 * Version Added:
	 *     0.5
	 *
	 * Args:
	 *     name (string):
	 *         The name of the HTML element to craft.
	 *
	 *     props (object):
	 *         Properties to set on the HTMLElement object.
	 *
	 *         These can be set recursively.
	 *
	 *     ...children (ComponentChild[]):
	 *         Any children to paint and nest within the element.
	 *
	 *         Children will be painted automatically.
	 *
	 *         This is not supported for all elements.
	 *
	 * Returns:
	 *     HTMLElement:
	 *     The component instance.
	 */
	function _craftElement(name, props, children) {
	  const el = document.createElement(name);
	  if (props) {
	    setProps(el, props);
	  }
	  if (children && children.length > 0) {
	    el.append(...paintCraftedElements(children));
	  }
	  return el;
	}

	/**
	 * Support for crafting instances and trees of components.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * An item to craft, when crafting a tree of components.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Utility interface for typing craft functions.
	 *
	 * This is used internally by :js:func:`craft`.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Template tag for crafting components using an HTML-like language.
	 *
	 * See https://github.com/developit/htm for details on usage.
	 *
	 * Results will be component or :js:class:`HTMLElement` instances. Callers
	 * can specify a more precise type as a generic.
	 *
	 * Version Added:
	 *     0.5
	 */
	const craft = htm.bind(craftComponent);

	/**
	 * Craft an array of components.
	 *
	 * This will craft each component item, returning an array with each
	 * resulting populated component in the order specified.
	 *
	 * Version Added:
	 *     0.5
	 *
	 * Args:
	 *     items (Array of object):
	 *         The component information items.
	 *
	 * Returns:
	 *     Array:
	 *     The resulting crafted components.
	 */
	function craftComponents(items) {
	  return items.map(item => craftComponent(item.name ?? item.component, item.props || {}, ...(item.children || [])));
	}

	/**
	 * Support for painting components into DOM elements.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Utility interface for typing paint functions.
	 *
	 * This is used internally by :js:func:`paint`.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Template tag for painting components using an HTML-like language.
	 *
	 * See https://github.com/developit/htm for details on usage.
	 *
	 * Results will :js:class:`HTMLElement` instances. Callers can specify a
	 * more precise type as a generic.
	 *
	 * Version Added:
	 *     0.5
	 */
	const paint = htm.bind(paintComponent);

	/**
	 * Paint an array of components.
	 *
	 * This will paint each component item, returning an array with each resulting
	 * populated element in the order specified.
	 *
	 * Version Added:
	 *     0.5
	 *
	 * Args:
	 *     items (Array of object):
	 *         The component information items.
	 *
	 * Returns:
	 *     Array:
	 *     The resulting painted elements.
	 */
	function paintComponents(items) {
	  return paintCraftedElements(craftComponents(items));
	}

	/**
	 * Utilities for rendering content in the DOM.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Options for a renderInto() call.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Render one or more elements or crafted components into a DOM element.
	 *
	 * This is a replacement for using :js:func:`Element.append` or
	 * :js:func:`Element.insertBefore`, and automatically takes care of painting
	 * anything that's not already an :js:class:`Element`.
	 *
	 * Version Added:
	 *     0.5
	 *
	 * Args:
	 *     targetEl (HTMLElement or JQuery):
	 *         The element or JQuery-wrapped element to render into.
	 *
	 *     items (CraftedComponent or CraftedComponent[]):
	 *         The item or items to paint and render into the target element.
	 *
	 *     options (RenderIntoOptions, optional):
	 *         Options to control rendering and where elements are placed.
	 *
	 * Returns:
	 *     HTMLElement or JQuery:
	 *     The target element or JQuery-wrapped element, for chaining.
	 */
	function renderInto(targetEl, items, options = {}) {
	  return renderNodesInto(targetEl, paintCraftedElements(items), options);
	}

	/**
	 * Render nodes into a DOM element.
	 *
	 * This is a replacement for using :js:func:`Element.append` or
	 * :js:func:`Element.insertBefore`, handling batches of nodes at once.
	 *
	 * Version Added:
	 *     0.5
	 *
	 * Args:
	 *     targetEl (HTMLElement or JQuery):
	 *         The element or JQuery-wrapped element to render into.
	 *
	 *     items (CraftedComponent or CraftedComponent[]):
	 *         The item or items to paint and render into the target element.
	 *
	 *     options (RenderIntoOptions, optional):
	 *         Options to control rendering and where elements are placed.
	 *
	 * Returns:
	 *     HTMLElement or JQuery:
	 *     The target element or JQuery-wrapped element, for chaining.
	 */
	function renderNodesInto(targetEl, nodes, options = {}) {
	  const normTargetEl = isElement(targetEl) ? targetEl : targetEl[0];
	  if (options.empty) {
	    normTargetEl.innerHTML = '';
	  }
	  if (options.prepend) {
	    const firstChild = normTargetEl.firstChild;
	    for (const node of nodes) {
	      normTargetEl.insertBefore(node, firstChild);
	    }
	  } else {
	    normTargetEl.append(...nodes);
	  }
	  return targetEl;
	}

	/**
	 * Utilities for working with the DOM.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Standard enum types useful across components.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Standard values for layout orientation.
	 *
	 * Version Added:
	 *     0.5
	 */
	let Orientation = /*#__PURE__*/function (Orientation) {
	  /** Horizontal orientation. */
	  Orientation["HORIZONTAL"] = "horizontal";
	  /** Vertical orientation. */
	  Orientation["VERTICAL"] = "vertical";
	  return Orientation;
	}({});

	/* This is in rough dependency order. */

	var _class$e;
	/**
	 * The type of a menu item.
	 *
	 * Version Added:
	 *     0.5
	 */
	let MenuItemType = /*#__PURE__*/function (MenuItemType) {
	  /** A standard menu item. */
	  MenuItemType["ITEM"] = "item";
	  /** A menu item that can be toggled on or off. */
	  MenuItemType["CHECKBOX_ITEM"] = "checkbox-item";
	  /**
	   * A menu item that provides a header above other items.
	   *
	   * Version Added:
	   *     0.8
	   */
	  MenuItemType["HEADER"] = "header";
	  /** A menu item that can be toggled on or off in a radio group. */
	  MenuItemType["RADIO_ITEM"] = "radio-item";
	  /** A separator between menu items. */
	  MenuItemType["SEPARATOR"] = "separator";
	  return MenuItemType;
	}({});

	/**
	 * Model attributes for MenuItem.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Information on a menu item to display in a menu.
	 *
	 * Menu items may take the form of a typical menu item (which performs an
	 * action when clicked), a toggleable checkbox, a toggleable group of radio
	 * items, or a separator.
	 *
	 * They always contain a label, but may optionally contain an icon and
	 * keyboard shortcuts.
	 *
	 * All item types may include an ``onClick`` handler, for invoking an action
	 * when clicked or invoked via keyboard shortcut.
	 *
	 * For special cases, a custom element may also be provided for the element
	 * in the form of ``childEl``.
	 *
	 * Version Added:
	 *     0.5
	 */
	let MenuItem = spina(_class$e = class MenuItem extends BaseModel {
	  static defaults = {
	    checked: null,
	    childEl: null,
	    disabled: false,
	    iconName: null,
	    id: null,
	    keyboardShortcut: null,
	    keyboardShortcutRegistry: null,
	    label: null,
	    onClick: null,
	    radioGroup: null,
	    type: MenuItemType.ITEM,
	    url: null
	  };

	  /**
	   * Initialize the menu item.
	   *
	   * This will perform validation on the attributes and set up the
	   * menu item.
	   *
	   * Args:
	   *     ...args (any[]):
	   *         Arguments to pass to the parent.
	   *
	   * Raises:
	   *     Error:
	   *         There were missing or invalid attributes provided for the
	   *         menu item type.
	   */
	  initialize(...args) {
	    super.initialize(...args);
	    const itemType = this.get('type');
	    switch (itemType) {
	      case MenuItemType.CHECKBOX_ITEM:
	        /*
	         * Checkbox menu item.
	         *
	         * Ensure ``checked`` has a default boolean.
	         */
	        if (this.get('checked') === null) {
	          this.set('checked', false);
	        }
	        break;
	      case MenuItemType.RADIO_ITEM:
	        /*
	         * Radio menu item.
	         *
	         * Ensure ``checked`` has a default boolean, and add to the
	         * radio group if provide.
	         */
	        if (this.get('checked') === null) {
	          this.set('checked', false);
	        }
	        this.get('radioGroup')?.add(this);
	        break;
	      case MenuItemType.HEADER: /* Fall-through */
	      case MenuItemType.ITEM:
	      case MenuItemType.SEPARATOR:
	        break;
	      default:
	        throw Error(`Invalid menu item type: "${itemType}"`);
	    }
	  }

	  /**
	   * Invoke the menu item's action.
	   *
	   * For standard menu items, this will call any ``onClick`` callback
	   * provided.
	   *
	   * For checkbox menu items, the :js:attr:`checked` state will be toggled.
	   * An ``onClick`` callback will also be invoked, if provided.
	   *
	   * For radio menu items, this menu item's :js:attr:`checked`` state will
	   * be set, and all others in the radio group will be unset. An ``onClick``
	   * callback will also be invoked, if provided and if this item was not
	   * already checked.
	   *
	   * Separators don't perform any kind of action.
	   *
	   * If the menu item is disabled, nothing will happen.
	   *
	   * Args:
	   *     e (MouseEvent, optional):
	   *         The mouse event triggering this action, if any.
	   */
	  invokeAction(e) {
	    if (this.get('disabled')) {
	      return;
	    }
	    switch (this.get('type')) {
	      case MenuItemType.CHECKBOX_ITEM:
	        /*
	         * Checkbox menu item.
	         *
	         * Toggle the checked state before performing an action.
	         */
	        this.set('checked', !this.get('checked'));
	        break;
	      case MenuItemType.ITEM:
	        /* Common case. */
	        break;
	      case MenuItemType.RADIO_ITEM:
	        /*
	         * Radio menu item.
	         *
	         * Toggle the state of all items so only this one is
	         * checked.
	         */
	        if (!this.get('checked')) {
	          this.set('checked', true);
	        }
	        break;
	      case MenuItemType.SEPARATOR:
	        /* Separators don't perform actions. */
	        return;
	    }

	    /* Now invoke any provided onClick handler, if allowed above. */
	    const onClick = this.get('onClick');
	    if (onClick) {
	      onClick(this, e);
	    }
	  }
	}) || _class$e;
	var _class$d;

	/**
	 * A collection of menu items.
	 *
	 * This can hold and track any number of menu items.
	 *
	 * Version Added:
	 *     0.5
	 */
	let MenuItemsCollection = spina(_class$d = class MenuItemsCollection extends BaseCollection {
	  static model = MenuItem;
	}) || _class$d;
	var _class$c;

	/**
	 * A collection for a group of radio menu items
	 *
	 * This will track one or more radio menu items that belong to the same
	 * toggle group. It will track the currently-checked item and ensure that
	 * at most only one menu item is ever checked at a time.
	 *
	 * Version Added:
	 *     0.5
	 */
	let MenuItemsRadioGroup = spina(_class$c = class MenuItemsRadioGroup extends MenuItemsCollection {
	  /**********************
	   * Instance variables *
	   **********************/

	  /**
	   * The currently-checked menu item.
	   *
	   * This will be ``null`` if no item is checked.
	   */
	  checkedMenuItem = null;

	  /**
	   * Initialize the radio group.
	   *
	   * This will begin listening to changes to any menu items included in the
	   * group, and will set up the state for any menu items provided during
	   * construction.
	   *
	   * Args:
	   *     models (TMenuItem[]):
	   *         The menu items added during construction.
	   *
	   *     ...args (any[]):
	   *         Additional arguments passed during initialization.
	   */
	  initialize(models, ...args) {
	    super.initialize(models, ...args);
	    this.on('add', this.#onAdd);
	    this.on('remove', this.#onRemove);
	    this.on('reset', this.#onReset);
	    this.on('change:checked', this.#onItemCheckedChanged);
	    if (models) {
	      models.forEach(this.#onAdd.bind(this));
	    }
	  }

	  /**
	   * Handle a change to the checked attribute for a menu item.
	   *
	   * If the menu item is now checked, then this will uncheck the
	   * previously-checked menu item (if any). This item will then be set
	   * as the currently-checked item.
	   *
	   * If the menu item is now unchecked, this will ensure that the checked
	   * value is a proper boolean and unset this item as the currently-checked
	   * item.
	   *
	   * Args:
	   *     menuItem (TMenuItem):
	   *         The menu item that was updated.
	   */
	  #onItemCheckedChanged(menuItem) {
	    const checked = menuItem.get('checked');
	    if (checked) {
	      if (this.checkedMenuItem !== null && this.checkedMenuItem !== menuItem) {
	        /* Clear the checked states of the previously-checked item. */
	        this.checkedMenuItem.set('checked', false);
	      }
	      this.checkedMenuItem = menuItem;
	    } else {
	      if (checked !== false) {
	        /* Normalize the checked state, but don't trigger an event. */
	        menuItem.set('checked', false, {
	          silent: true
	        });
	      }
	      if (this.checkedMenuItem === menuItem) {
	        this.checkedMenuItem = null;
	      }
	    }
	  }

	  /**
	   * Process new menu items in the radio group.
	   *
	   * This will ensure that the menu item is set to belong to this radio
	   * group and update the group's checked state if it's checked.
	   *
	   * Args:
	   *     menuItem (TMenuItem):
	   *         The menu item that was added.
	   */
	  #onAdd(menuItem) {
	    if (menuItem.get('radioGroup') !== this) {
	      menuItem.set('radioGroup', this);
	    }
	    this.#onItemCheckedChanged(menuItem);
	  }

	  /**
	   * Handle removing a  menu item from the radio group.
	   *
	   * This will unset the radio group on the item and, if this item was
	   * checked, clear the radio group's checked item state.
	   *
	   * Args:
	   *     menuItem (TMenuItem):
	   *         The menu item that was removed.
	   */
	  #onRemove(menuItem) {
	    menuItem.set('radioGroup', null);
	    if (menuItem === this.checkedMenuItem) {
	      this.checkedMenuItem = null;
	    }
	  }

	  /**
	   * Handle resetting items in the radio group.
	   *
	   * This will clean up state on all removed items, and set up new state on
	   * all remaining or newly-added items.
	   *
	   * Args:
	   *     collection (MenuItemsRadioGroup):
	   *         This radio group instance.
	   *
	   *     options (object):
	   *         The options passed to the handler. This will contain the list
	   *         of previous models.
	   */
	  #onReset(collection, options) {
	    options.previousModels.forEach(this.#onRemove.bind(this));

	    /* onAdd() won't be called above, since reset() will add silently. */
	    this.forEach(this.#onAdd.bind(this));
	  }
	}) || _class$c;

	/**
	 * Base class for Spina-based Ink components.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Base options passed into components.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Initial pre-render state for a component.
	 *
	 * This collects information on the options passed in to the component,
	 * any children or subcomponents used during its construction, and any
	 * additional information that may be needed to correctly render the
	 * component.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Base class for a Spina-based component.
	 *
	 * This can be used as a base class for building a component. It takes care
	 * of tracking any initial pre-render state from the construction or crafting
	 * process, and then helping facilitate the rendering of the component.
	 *
	 * Version Added:
	 *     0.5
	 */
	class BaseComponentView extends BaseView {
	  /**********************
	   * Instance variables *
	   **********************/

	  /**
	   * Initial options passed during construction.
	   *
	   * These will be removed after initial render.
	   */
	  initialComponentState;

	  /**
	   * Initialize the component.
	   *
	   * This will set up some initial state for the component, used to collect
	   * and track state that can be used when rendering the component.
	   *
	   * Subclasses must call this when overriding this method.
	   *
	   * Args:
	   *     options (object, optional):
	   *         Options passed to the component.
	   */
	  initialize(options = {}) {
	    if (!options) {
	      options = {};
	    }
	    this.initialComponentState = {
	      crafted: !!options.componentCrafted,
	      options: options,
	      subcomponents: {}
	    };
	  }

	  /**
	   * Set the direct children for this component.
	   *
	   * This will be called with the complete list of children when crafting
	   * or painting a component.
	   *
	   * If subcomponents are used, then this will not be called. Instead,
	   * the subcomponent handles will be called.
	   *
	   * This will never be called after rendering the component.
	   *
	   * Args:
	   *     children (Array):
	   *         The children passed to the component.
	   */
	  setComponentChildren(children) {
	    const state = this.initialComponentState;
	    if (!state) {
	      throw Error(`${this.constructor.name}.setComponentChildren() cannot ` + `be called after the component is rendered.`);
	    }
	    state.children = children;
	  }

	  /**
	   * Helper to record a single instance of a subcomponent.
	   *
	   * This can be used as a callback in ``subcomponents`` to handle a
	   * single instance of a subcomponent. If a second instance of that
	   * subcomponent is provided, then this will fail with an error.
	   *
	   * Args:
	   *     subcomponent (object):
	   *         Information on the subcomponent.
	   */
	  recordOneSubcomponent(subcomponent) {
	    const state = this.initialComponentState;
	    if (!state) {
	      throw Error(`${this.constructor.name}.recordOneSubcomponent() cannot ` + `be called after the component is rendered.`);
	    }
	    const allSubcomponents = state.subcomponents;
	    const name = subcomponent.name;
	    if (name in allSubcomponents) {
	      throw Error(`Subcomponent "${name}" cannot be provided more than once.`);
	    }
	    allSubcomponents[name] = [subcomponent];
	  }

	  /**
	   * Helper to record all instances of a subcomponent in an array.
	   *
	   * This can be used as a callback in ``subcomponents`` to handle
	   * recording all instances of a subcomponent for processing.
	   *
	   * Args:
	   *     subcomponent (object):
	   *         Information on the subcomponent.
	   */
	  recordAllSubcomponents(subcomponent) {
	    const state = this.initialComponentState;
	    if (!state) {
	      throw Error(`${this.constructor.name}.recordAllSubcomponents() cannot ` + `be called after the component is rendered.`);
	    }
	    const allSubcomponents = state.subcomponents;
	    let subcomponents;
	    if (subcomponent.name in allSubcomponents) {
	      subcomponents = allSubcomponents[subcomponent.name];
	    } else {
	      subcomponents = [];
	      allSubcomponents[subcomponent.name] = subcomponents;
	    }
	    subcomponents.push(subcomponent);
	  }

	  /**
	   * Handle the initial render of the component.
	   *
	   * This is meant to be overridden by subclasses to handle rendering the
	   * component based on any collected state.
	   *
	   * Once rendered, the :js:attr:`initialComponentState` will be discarded.
	   *
	   * Subclasses do not need to call the parent method.
	   */
	  onComponentInitialRender() {
	    /* Intentionally empty. */
	  }

	  /**
	   * Handle the initial render of the view.
	   *
	   * This will call :js:func:`onComponentInitialRender` and then clear any
	   * initial pre-render state.
	   *
	   * This should not be overridden by subclasses.
	   */
	  onInitialRender() {
	    this.onComponentInitialRender();
	    this.initialComponentState = null;
	  }
	}
	var _dec$8, _class$b;
	/**
	 * The type of a button.
	 *
	 * Version Added:
	 *     0.5
	 */
	let ButtonType = /*#__PURE__*/function (ButtonType) {
	  /** A button representing a dangerous or destructive operation. */
	  ButtonType["DANGER"] = "danger";
	  /** A primary or default button. */
	  ButtonType["PRIMARY"] = "primary";
	  /** A button that resets the form. */
	  ButtonType["RESET"] = "reset";
	  /** A standard, non-default button. */
	  ButtonType["STANDARD"] = "standard";
	  /** A button that submits the form. */
	  ButtonType["SUBMIT"] = "submit";
	  return ButtonType;
	}({});

	/**
	 * Options for ButtonView.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Component for showing a standard button.
	 *
	 * Ink buttons are based on standard HTML buttons, but provide additional
	 * information such as icons, keyboard shortcut indicators, and even busy
	 * animations. They're built to be accessible, using appropriate ARIA
	 * attributes to indicate state.
	 *
	 * Buttons can take an explicit click handler during construction, which will
	 * be used whenever the button is clicked (as long as it's not in a busy
	 * state). When set, DOM "click" events will not be used. If an explicit
	 * handler is not set, consumers should listen to DOM "click" events.
	 *
	 * If the click handler returns a Promise, the button will stay in a busy
	 * state until the Promise resolves.
	 *
	 * Button state can be modified at runtime.
	 *
	 * They may also be ``<button>`` elements (default) or ``<a>`` elements.
	 *
	 * Version Changed:
	 *     0.9:
	 *     Click handlers that return a Promise now cause the button to stay in
	 *     a busy state until the Promise resolves.
	 *
	 * Version Added:
	 *     0.5
	 */
	let ButtonView = (_dec$8 = inkComponent('Ink.Button'), _dec$8(_class$b = spina(_class$b = class ButtonView extends BaseComponentView {
	  static tagName = 'button';
	  static className = 'ink-c-button';
	  static allowComponentChildren = true;

	  /**********************
	   * Instance variables *
	   **********************/

	  /**
	   * Whether to lock rendering of the button.
	   *
	   * This is used to manage internal state updates.
	   */
	  #lockRender = false;

	  /** The name of an icon to show. */
	  #iconName;

	  /** A keyboard shortcut used to activate this button. */
	  #keyboardShortcut;

	  /** The keyboard shortcut registry used for shortcut registration. */
	  #keyboardShortcutRegistry;

	  /** A keyboard shortcut used to activate this button. */
	  #keyboardShortcutView;

	  /** The label to show on the button. */
	  #label = null;

	  /**
	   * Whether to show a registered keyboard shortcut.
	   */
	  #showKeyboardShortcut;

	  /**
	   * Initialize the button.
	   *
	   * Args:
	   *     options (ButtonViewOptions):
	   *         Options for the button.
	   */
	  initialize(options) {
	    super.initialize(options);
	    this.#iconName = options.iconName || null;
	    this.#keyboardShortcut = options.keyboardShortcut || null;
	    this.#keyboardShortcutRegistry = options.keyboardShortcutRegistry || null;
	    this.#showKeyboardShortcut = !!options.showKeyboardShortcut;
	    if (!options.type) {
	      options.type = ButtonType.STANDARD;
	    }
	  }

	  /**
	   * Handle children set in the button.
	   *
	   * This component takes a single text string as a child, for use as the
	   * label.
	   *
	   * Args:
	   *     children (string[]):
	   *         The button label.
	   *
	   * Raises:
	   *     Error:
	   *         An incompatible child was provided, or the wrong number of
	   *         children were provided.
	   */
	  setComponentChildren(children) {
	    if (children.length > 0) {
	      if (children.length !== 1 || typeof (children[0] || '') !== 'string') {
	        throw Error('Ink.Button can only accept a single string child as a ' + 'label.');
	      }
	      this.label = children[0];
	    } else {
	      this.label = '';
	    }
	  }

	  /**
	   * Return whether the button is set to have focus automatically.
	   *
	   * Returns:
	   *     boolean:
	   *     ``true`` if the button is set to auto-focus. ``false`` if it is not.
	   */
	  get autofocus() {
	    return this.el.autofocus;
	  }

	  /**
	   * Set whether the button is set to have focus automatically.
	   *
	   * Args:
	   *     newAutoFocus (boolean):
	   *         ``true`` if the button should be set to auto-focus. ``false``
	   *         if it should not.
	   */
	  set autofocus(newAutoFocus) {
	    this.el.autofocus = newAutoFocus;
	  }

	  /**
	   * Return whether the button is in a busy state.
	   *
	   * Returns:
	   *     boolean:
	   *     ``true`` if the button is in a busy state. ``false`` if it is not.
	   */
	  get busy() {
	    return this.el.getAttribute('aria-busy') === 'true';
	  }

	  /**
	   * Set whether the button is in a busy state.
	   *
	   * Args:
	   *     newBusy (boolean):
	   *         ``true`` if the button should be in a busy state. ``false``
	   *         if it should not.
	   */
	  set busy(newBusy) {
	    if (newBusy) {
	      this.el.setAttribute('aria-busy', 'true');
	    } else {
	      this.el.removeAttribute('aria-busy');
	    }
	  }

	  /**
	   * Return whether the button is disabled.
	   *
	   * Returns:
	   *     boolean:
	   *     ``true`` if the button is disabled. ``false`` if it is not.
	   */
	  get disabled() {
	    const el = this.el;
	    if (el instanceof HTMLButtonElement) {
	      return el.disabled;
	    } else {
	      return el.classList.contains('-is-disabled');
	    }
	  }

	  /**
	   * Set whether the button is disabled.
	   *
	   * Args:
	   *     newDisabled (boolean):
	   *         ``true`` if the button should be disabled. ``false``
	   *         if it should not.
	   */
	  set disabled(newDisabled) {
	    const el = this.el;
	    if (el instanceof HTMLButtonElement) {
	      el.disabled = newDisabled;
	    } else {
	      el.classList.toggle('-is-disabled', newDisabled);
	    }
	  }

	  /**
	   * Return the link target to navigate to on click.
	   *
	   * This is only supported for button links (``tagName="a"``).
	   *
	   * Returns:
	   *     string:
	   *     The link target.
	   */
	  get href() {
	    return this.el.getAttribute('href') || null;
	  }

	  /**
	   * Set the link target to navigate to on click.
	   *
	   * This is only supported for button links (``tagName="a"``).
	   *
	   * Args:
	   *     newHref (string):
	   *         The new link target.
	   */
	  set href(newHref) {
	    const el = this.el;
	    if (el instanceof HTMLAnchorElement) {
	      if (newHref) {
	        el.setAttribute('href', newHref);
	      } else {
	        el.removeAttribute('href');
	      }
	    } else if (newHref) {
	      console.warn('href is not valid for button links (tagName="a").');
	    }
	  }

	  /**
	   * Return the name of the icon shown on the button.
	   *
	   * Returns:
	   *     string:
	   *     The name of the icon shown.
	   */
	  get iconName() {
	    return this.#iconName;
	  }

	  /**
	   * Set the name of the icon to show on the button.
	   *
	   * Args:
	   *     newIconName (string):
	   *         The name of the icon to show.
	   *
	   *         This can be set to ``null`` to hide an icon.
	   */
	  set iconName(newIconName) {
	    if (newIconName !== this.#iconName) {
	      this.#iconName = newIconName;
	      this.#renderInterior();
	    }
	  }

	  /**
	   * Return the label shown on the button.
	   *
	   * Returns:
	   *     string:
	   *     The label shown on the button.
	   */
	  get label() {
	    return this.#label || null;
	  }

	  /**
	   * Set the label to show on the button.
	   *
	   * Args:
	   *     newLabel (string):
	   *         The label to show.
	   */
	  set label(newLabel) {
	    if (newLabel !== this.#label) {
	      this.#label = newLabel;
	      this.#renderInterior();
	    }
	  }

	  /**
	   * Return the type of the button.
	   *
	   * Returns:
	   *     ButtonType:
	   *     The current type of the button.
	   */
	  get type() {
	    if (!this.rendered) {
	      /*
	       * This will only be returned during construction, and is needed
	       * when setting the type in order to check for a change.
	       */
	      return null;
	    }
	    const el = this.el;

	    /*
	     * We explicitly access the button type via DOM attribute and not
	     * via HTMLButtonElement.type, in order to check an explicitly-set
	     * value and not the default value of "type" (which would be "submit").
	     */
	    if (el instanceof HTMLButtonElement) {
	      const buttonType = el.getAttribute('type');
	      if (buttonType === 'submit') {
	        return ButtonType.SUBMIT;
	      } else if (buttonType === 'reset') {
	        return ButtonType.RESET;
	      }
	    }
	    if (el.classList.contains('-is-primary')) {
	      return ButtonType.PRIMARY;
	    } else if (el.classList.contains('-is-danger')) {
	      return ButtonType.DANGER;
	    } else {
	      return ButtonType.STANDARD;
	    }
	  }

	  /**
	   * Set the type of the button.
	   *
	   * Args:
	   *     newType (ButtonType):
	   *         The type of the button.
	   */
	  set type(newType) {
	    if (this.type !== newType) {
	      const el = this.el;
	      const classList = el.classList;
	      if (el instanceof HTMLButtonElement) {
	        if (newType === ButtonType.SUBMIT) {
	          el.type = 'submit';
	        } else if (newType === ButtonType.RESET) {
	          el.type = 'reset';
	        } else {
	          el.type = 'button';
	        }
	      } else {
	        if (newType === ButtonType.SUBMIT || newType === ButtonType.RESET) {
	          console.warn(`Button type "${newType}" is not valid for ` + `button links (tagName="a").`);
	          newType = ButtonType.STANDARD;
	        }
	      }
	      classList.toggle('-is-primary', newType === ButtonType.PRIMARY);
	      classList.toggle('-is-danger', newType === ButtonType.DANGER);
	    }
	  }

	  /**
	   * Handle the initial rendering of the component.
	   *
	   * This will perform a render of the button's icon, label, and any
	   * shortcuts, and set up event handlers.
	   */
	  onComponentInitialRender() {
	    const el = this.el;
	    const options = this.initialComponentState.options;
	    const onClick = options.onClick;
	    if (!(el instanceof HTMLButtonElement)) {
	      el.setAttribute('role', 'button');
	    }

	    /*
	     * Setup an event handler for button clicks.
	     *
	     * Note that if an onClick is not provided, this will still trigger
	     * a standard DOM "click" event. If an onClick is provided, we skip
	     * that entirely, and prevent any bubbling or default behavior.
	     */
	    el.addEventListener('click', async e => {
	      const isClickable = !this.busy && !this.disabled;
	      if (onClick || !isClickable) {
	        e.preventDefault();
	        e.stopPropagation();
	        if (onClick && isClickable) {
	          const result = onClick();

	          /*
	           * If this returned a promise, then we'll keep the
	           * button in a busy state until it finished.
	           */
	          if (result instanceof Promise) {
	            this.busy = true;
	            try {
	              await result;
	            } finally {
	              this.busy = false;
	            }
	          }
	        }
	      }
	    }, {
	      capture: true
	    });

	    /* If there's a keyboard shortcut, register it. */
	    const keyboardShortcut = this.#keyboardShortcut;
	    const keyboardShortcutRegistry = this.#keyboardShortcutRegistry;
	    if (keyboardShortcut) {
	      this.#keyboardShortcutView = craftComponent("Ink.KeyboardShortcut", {
	        "class": "ink-c-button__keyboard-shortcut",
	        attachTo: el,
	        keys: keyboardShortcut,
	        onInvoke: "click",
	        registry: keyboardShortcutRegistry
	      });
	    }
	    if (options.attrs) {
	      setProps(el, options.attrs);
	    }

	    /*
	     * Set properties from any initial options. This will update the
	     * button to reflect the state.
	     *
	     * Any re-rendering of the interior contents will be blocked.
	     */
	    this.#lockRender = true;
	    Object.assign(this, _.pick(options, 'autofocus', 'busy', 'disabled', 'href', 'iconName', 'label', 'type'));
	    this.#lockRender = false;

	    /* We can now perform the render of the button. */
	    this.#renderInterior();
	  }

	  /**
	   * Render the interior of the button.
	   *
	   * This will rebuild the button based on the current state.
	   */
	  #renderInterior() {
	    if (this.#lockRender) {
	      return;
	    }
	    const el = this.el;
	    const iconName = this.#iconName;
	    const label = this.#label;
	    const showKeyboardShortcut = this.#showKeyboardShortcut && this.#keyboardShortcutView;
	    el.innerHTML = '';
	    if (iconName || showKeyboardShortcut) {
	      renderInto(el, [iconName && paintComponent("span", {
	        "class": "ink-c-button__icon " + iconName,
	        "aria-hidden": "true"
	      }), label && paintComponent("label", {
	        "class": "ink-c-button__label"
	      }, label), showKeyboardShortcut && this.#keyboardShortcutView]);
	    } else if (label) {
	      el.append(label);
	    }
	  }
	}) || _class$b) || _class$b);
	var _dec$7, _class$a, _dec2$1, _dec3, _class2$1;

	/**
	 * The action type for a DialogActionView.
	 *
	 * Version Added:
	 *     0.6
	 */
	let DialogActionType = /*#__PURE__*/function (DialogActionType) {
	  /**
	   * Trigger a callback.
	   *
	   * The dialog will stay open when clicked, allowing the caller to
	   * determine whether to close the dialog or keep it open.
	   *
	   * This is equivalent to ``null``, and will be deprecated in a future
	   * release.
	   */
	  DialogActionType["CALLBACK"] = "callback";
	  /**
	   * Cancel the dialog.
	   *
	   * The first action set to this type will be invoked automatically if
	   * the user presses Escape to close the dialog.
	   *
	   * Version ADded:
	   *     0.9
	   */
	  DialogActionType["CANCEL"] = "cancel";
	  /**
	   * Close the dialog.
	   *
	   * If a callback is provided, this will close the dialog once the
	   * callback has returned. If the callback returns a Promise, the dialog
	   * won't be closed until the Promise is resolved.
	   *
	   * If the callback errors out, the dialog will stay open. The callback
	   * should ideally render errors itself and not raise.
	   *
	   * Version Changed:
	   *     0.9:
	   *     This now supports running a callback before closing, if one is
	   *     provided.
	   */
	  DialogActionType["CLOSE"] = "close";
	  /**
	   * Trigger a callback and then close the dialog.
	   *
	   * This will only close the dialog once the callback has returned. If
	   * the callback returns a Promise, the dialog won't be closed until the
	   * Promise is resolved.
	   *
	   * If the callback errors out, the dialog will stay open. The callback
	   * should ideally render errors itself and not raise.
	   *
	   * This is equivalent to ``CLOSE``, and will be deprecated in a future
	   * release.
	   */
	  DialogActionType["CALLBACK_AND_CLOSE"] = "callback-and-close";
	  return DialogActionType;
	}({});

	/**
	 * Options for DialogActionView.
	 *
	 * Version Added:
	 *     0.6
	 */

	/**
	 * A component for dialog actions.
	 *
	 * This is a specialization of ButtonView, which can be used to handle common
	 * patterns with actions in a dialog.
	 *
	 * Any dialog action can trigger a callback, if provided. Along with this,
	 * dialog actions can be given a type, which indicates if they will close
	 * or cancel the dialog after the action concludes.
	 *
	 * Version Changed:
	 *     0.9:
	 *     Dialog action types no longer need to specify whether a callback
	 *     will be provided.
	 *
	 * Version Added:
	 *     0.6
	 */
	let DialogActionView = (_dec$7 = inkComponent('Ink.DialogAction'), _dec$7(_class$a = spina(_class$a = class DialogActionView extends ButtonView {
	  /**********************
	   * Instance variables *
	   **********************/

	  /**
	   * The type of action, dictating behavior when clicked.
	   *
	   * If ``null``, it doesn't have a specific type of action.
	   *
	   * Version Added:
	   *     0.9
	   */
	  actionType;

	  /** The dialog parent. */
	  dialog;

	  /** The type of action to perform. */
	  #action;

	  /** The function to call, if the action type is callback. */
	  #callback;
	  initialize(options) {
	    if (options.onClick) {
	      console.error(`Ink.DialogAction was instantiated with an onClick handler.
The "callback" attribute should be used instead.`);
	    } else {
	      options.onClick = this.onClick.bind(this);
	    }

	    /* Normalize the action. */
	    let action = options.action;
	    if (!action) {
	      /*
	       * Check if this is a legacy action type, and convert to a
	       * modern one.
	       */
	      if (action === DialogActionType.CALLBACK) {
	        action = null;
	      } else if (action === DialogActionType.CALLBACK_AND_CLOSE) {
	        action = DialogActionType.CLOSE;
	      }
	    }
	    this.actionType = action;
	    this.#callback = options.callback;
	    super.initialize(options);
	  }

	  /**
	   * Handle a click on the button.
	   *
	   * If a callback is set, it will be invoked. If it's asynchronous,
	   * the dialog will be placed in a busy state until the action finishes.
	   *
	   * If the action type closes or cancels the dialog, the dialog will be
	   * closed or canceled once any provided callback has finished.
	   *
	   * Returns:
	   *     Promise<void>:
	   *     The promise for the action.
	   */
	  async onClick() {
	    const actionType = this.actionType;
	    const dialog = this.dialog;
	    console.assert(dialog !== undefined);
	    const callback = this.#callback;
	    let actionResult;
	    if (callback) {
	      const result = callback();
	      if (result instanceof Promise) {
	        dialog.setBusy({
	          activeAction: this,
	          busy: true
	        });
	        try {
	          actionResult = await result;
	        } catch (e) {
	          console.error('Dialog action callback returned an error: %s', e);
	          return;
	        }
	        dialog.setBusy({
	          activeAction: this,
	          busy: false
	        });
	      }
	    }
	    if (actionType === DialogActionType.CLOSE) {
	      dialog.close({
	        action: this,
	        actionResult: actionResult,
	        canceled: false
	      });
	    } else if (actionType === DialogActionType.CANCEL) {
	      dialog.close({
	        action: this,
	        actionResult: actionResult,
	        canceled: true
	      });
	    }
	  }
	}) || _class$a) || _class$a);

	/**
	 * Values for the dialog size.
	 *
	 * Version Added:
	 *     0.6
	 */
	let DialogSize = /*#__PURE__*/function (DialogSize) {
	  /** Custom size: user must specify width/height styles. */
	  DialogSize["CUSTOM"] = "custom";
	  /** Fit to the size of the content. */
	  DialogSize["FIT"] = "fit";
	  /** Medium size: 60% of the viewport width. */
	  DialogSize["MEDIUM"] = "medium";
	  /** Large size: 80% of the viewport width. */
	  DialogSize["LARGE"] = "large";
	  /** Max size: viewport width minus some spacing. */
	  DialogSize["MAX"] = "max";
	  return DialogSize;
	}({});

	/**
	 * Options for DialogView.
	 *
	 * Version Added:
	 *     0.6
	 */

	/**
	 * Options for the DialogView.open operation.
	 *
	 * Version Added:
	 *     0.6
	 */

	/**
	 * Options for the DialogView.setBusy operation.
	 *
	 * Version Added:
	 *     6.0
	 */

	/**
	 * A reason the dialog is closed.
	 *
	 * This can be set when closing the dialog in order to provide extra
	 * information as to what led to the closing of the dialog.
	 *
	 * It's set automatically when clicking a button or when the user or browser
	 * triggers a cancelation of the dialog.
	 *
	 * Version Added:
	 *     0.9
	 */

	/**
	 * The dialog component.
	 *
	 * Dialogs display a title and messages (or other content) along with one or
	 * more action buttons (grouped into primary and secondary areas). They can
	 * be modal or non-modal.
	 *
	 * A dialog can also be marked as suppressable, allowing users to choose
	 * whether to see the dialog again in the future. If enabled, this component
	 * will handle the UI, though it's up to the caller to handle and respect
	 * the setting.
	 *
	 * Version Changed:
	 *     0.9:
	 *     * Added built-in support for cancelable actions.
	 *     * Added the ``canSuppress`` and ``suppressText`` options.
	 *     * Added max widths and heights to help dialogs size correctly.
	 *     * Modal dialogs now use the ``alertdialog`` role.
	 *
	 * Version Added:
	 *     0.6
	 */
	let DialogView = (_dec2$1 = inkComponent('Ink.Dialog'), _dec3 = spina({
	  prototypeAttrs: ['title']
	}), _dec2$1(_class2$1 = _dec3(_class2$1 = class DialogView extends BaseComponentView {
	  /** The title for the dialog */
	  static title = null;
	  static tagName = 'dialog';
	  static className = 'ink-c-dialog';
	  static subcomponents = {
	    'PrimaryActions': 'recordOneSubcomponent',
	    'SecondaryActions': 'recordOneSubcomponent',
	    'Body': 'recordOneSubcomponent'
	  };
	  static events = {
	    'cancel': '_onCancel',
	    'close': '_onClose'
	  };

	  /**********************
	   * Instance variables *
	   **********************/

	  /**
	   * The set of all actions.
	   *
	   * This only includes actions which are subclasses of DialogActionView.
	   * Regular buttons or other components will not be included in this.
	   */
	  #actions = [];

	  /**
	   * The reason the dialog was closed.
	   *
	   * This is only set once :js:meth:`close` has been called.
	   *
	   * Version Added:
	   *     0.9
	   */
	  #closeReason = null;

	  /**
	   * The callback handler when the dialog is closed.
	   *
	   * Version Added:
	   *     0.9
	   */
	  #onClose = null;

	  /**
	   * The suppress checkbox, if added to the dialog.
	   *
	   * Version Added:
	   *     0.9
	   */
	  #suppressEl;

	  /**
	   * Return whether the dialog is open.
	   *
	   * Returns:
	   *     boolean:
	   *     true if the dialog is currently open.
	   */
	  get isOpen() {
	    return this.el.open;
	  }

	  /**
	   * Return whether the user checked the suppressed checkbox.
	   *
	   * Version Added:
	   *     0.9
	   *
	   * Returns:
	   *     boolean:
	   *     ``true`` if the suppressed checkbox was added and checked.
	   *     ``false`` otherwise.
	   */
	  get isSuppressChecked() {
	    return !!this.#suppressEl?.checked;
	  }

	  /**
	   * Initialize the view.
	   *
	   * Args:
	   *     options (DialogViewOptions):
	   *         The options for the view.
	   */
	  preinitialize(options) {
	    this.id ??= _.uniqueId('_ink-c-dialog');
	    super.preinitialize(options);
	  }

	  /**
	   * Open the dialog.
	   *
	   * Args:
	   *     options (DialogViewOpenOptions):
	   *         Whether to show the dialog as modal or not.
	   */
	  open(options = {}) {
	    if (!this.rendered) {
	      console.error('DialogView.show called before view was rendered');
	      return;
	    }
	    const el = this.el;
	    if (!document.body.contains(el)) {
	      document.body.append(el);
	    }
	    if (options.modal === false) {
	      el.setAttribute('role', 'dialog');
	      el.show();
	    } else {
	      el.setAttribute('role', 'alertdialog');
	      el.showModal();
	    }
	  }

	  /**
	   * Open the dialog, returning a Promise that resolves once closed.
	   *
	   * This is a convenient way of opening a dialog and resolving when
	   * closed, helping callers build and show dialogs in a more
	   * straight-forward fashion.
	   *
	   * Version Added:
	   *     0.9
	   *
	   * Args:
	   *     options (DialogViewOpenOptions):
	   *         Whether to show the dialog as modal or not.
	   *
	   * Returns:
	   *     Promise<DialogCloseReason>:
	   *     A promise that resolves with a close reason once closed.
	   */
	  async openAndWait(options = {}) {
	    return new Promise(done => {
	      this.listenToOnce(this, 'closed', done);
	      this.open(options);
	    });
	  }

	  /**
	   * Close the dialog.
	   *
	   * Version Changed:
	   *     0.9:
	   *     Added the ``reason`` argument.
	   *
	   * Args:
	   *     reason (DialogCloseReason, optional):
	   *         The reason the dialog is closed.
	   */
	  close(reason) {
	    this.#closeReason = reason ?? {
	      action: null,
	      canceled: false
	    };
	    this.el.close();
	  }

	  /**
	   * Set the dialog as busy.
	   *
	   * When the dialog is busy, all of the actions which are instances of
	   * DialogActionView will be set to either busy or disabled depending on
	   * whether they are the active action. This allows potentially long-running
	   * responses to disable everything while the operation runs.
	   *
	   * Args:
	   *     options (DialogViewSetBusyOptions):
	   *         Options for the busy operation.
	   */
	  setBusy(options) {
	    const {
	      activeAction,
	      busy
	    } = options;
	    for (const action of this.#actions) {
	      if (action === activeAction) {
	        action.busy = busy;
	      } else {
	        action.disabled = busy;
	      }
	    }
	  }

	  /**
	   * Handle the initial rendering of the component.
	   *
	   * This will perform a render of the buttons in the dialog.
	   */
	  onComponentInitialRender() {
	    const el = this.el;
	    const state = this.initialComponentState;
	    const options = state.options;
	    const size = options.size;
	    this.#onClose = options.onClose || null;
	    if (size && size !== 'custom') {
	      el.dataset.size = size;
	    }
	    const title = this.renderTitle();
	    const body = this.renderBody();
	    const primaryActions = this.renderPrimaryActions();
	    const secondaryActions = this.renderSecondaryActions();
	    const id = this.id;
	    const titleID = `${id}__title`;
	    el.setAttribute('aria-labelledby', titleID);
	    this.#addActions(primaryActions);
	    this.#addActions(secondaryActions);
	    let suppressLabel = null;
	    if (options.canSuppress) {
	      const suppressID = `ink-dialog-suppress-${this.cid}`;
	      const suppressEl = paintComponent("input", {
	        id: suppressID,
	        "class": "ink-c-dialog__suppress",
	        type: "checkbox"
	      });
	      suppressLabel = paintComponent("label", {
	        "class": "ink-c-dialog__suppress-label",
	        "for": suppressID
	      }, suppressEl, options.suppressText || 'Do not ask again');
	      this.#suppressEl = suppressEl;
	    }
	    renderInto(this.el, paintComponent("div", {
	      "class": "ink-c-dialog__inner"
	    }, paintComponent("header", {
	      "class": "ink-c-dialog__title",
	      id: titleID
	    }, title), paintComponent("main", {
	      "class": "ink-c-dialog__body"
	    }, body), paintComponent("footer", {
	      "class": "ink-c-dialog__actions"
	    }, paintComponent("div", {
	      "class": "ink-c-dialog__actions-secondary"
	    }, suppressLabel, secondaryActions), paintComponent("div", {
	      "class": "ink-c-dialog__actions-primary"
	    }, primaryActions))));
	  }

	  /**
	   * Handle when the dialog is removed.
	   */
	  onRemove() {
	    if (this.isOpen) {
	      this.close({
	        canceled: true
	      });
	    }
	    super.onRemove();
	  }

	  /**
	   * Render the title for the dialog.
	   *
	   * Returns:
	   *     ComponentChild or array of ComponentChild:
	   *     The elements to add for the title.
	   */
	  renderTitle() {
	    return this.initialComponentState.options.title || this.title;
	  }

	  /**
	   * Render the body for the dialog.
	   *
	   * Returns:
	   *     ComponentChild or array of ComponentChild:
	   *     The elements to add for the body.
	   */
	  renderBody() {
	    const body = this.initialComponentState.subcomponents['Body'];
	    return body ? body[0].children : null;
	  }

	  /**
	   * Render the primary actions for the dialog.
	   *
	   * Returns:
	   *     ComponentChild or Array of ComponentChild:
	   *     The elements to add for the primary actions.
	   */
	  renderPrimaryActions() {
	    const primaryActions = this.initialComponentState.subcomponents['PrimaryActions'];
	    return primaryActions ? primaryActions[0].children : null;
	  }

	  /**
	   * Render the secondary actions for the dialog.
	   *
	   * Returns:
	   *     ComponentChild or Array of ComponentChild:
	   *     The elements to add for the secondary actions.
	   */
	  renderSecondaryActions() {
	    const secondaryActions = this.initialComponentState.subcomponents['SecondaryActions'];
	    return secondaryActions ? secondaryActions[0].children : null;
	  }

	  /**
	   * Add actions to the dialog.
	   *
	   * Args:
	   *     actions (ComponentChild or Array of ComponentChild):
	   *         The child components to add.
	   */
	  #addActions(actions) {
	    if (_.isArray(actions)) {
	      for (const action of actions) {
	        this.#addAction(action);
	      }
	    } else {
	      this.#addAction(actions);
	    }
	  }

	  /**
	   * Add an action to the dialog.
	   *
	   * Children of the primary or secondary actions areas may be instances of
	   * DialogActionView. In this case, they are provided a reference back to
	   * this dialog so that they can call methods such as :js:meth:`close` or
	   * :js:meth:`setBusy`.
	   *
	   * Other components or elements may also be present in the actions areas.
	   * These are currently ignored here, so any state must be manually managed
	   * by the consumer.
	   *
	   * Args:
	   *     action (ComponentChild):
	   *         The child component to add.
	   */
	  #addAction(action) {
	    if (action instanceof DialogActionView) {
	      action.dialog = this;
	      this.#actions.push(action);
	    }
	  }

	  /**
	   * Handle a "cancel" event on the dialog element.
	   *
	   * This will attempt to locate a Cancel action, and if found, trigger it.
	   *
	   * If a Cancel action is not found, this will set a default cancel reason
	   * for the signal handlers and close callback, and then let the event
	   * bubble up, triggering :js:func:`_onClose`.
	   *
	   * Version Added:
	   *     0.9
	   *
	   * Args:
	   *     e (Event):
	   *         The "cancel" event.
	   */
	  _onCancel(e) {
	    /*
	     * Look for a Cancel action. If found, prevent default behavior and
	     * invoke it.
	     *
	     * Note that "cancel" events don't bubble up, and if not prevented
	     * will trigger a "close" event.
	     */
	    for (const action of this.#actions) {
	      if (action.actionType === DialogActionType.CANCEL) {
	        e.preventDefault();
	        action.el.click();
	        return;
	      }
	    }

	    /*
	     * Fall back to setting a generic close reason for the _onClose()
	     * handler to use.
	     */
	    this.#closeReason ??= {
	      action: null,
	      canceled: true
	    };
	  }

	  /**
	   * Handle a "close" event on the dialog element.
	   *
	   * This will notify the caller-provided ``onClose`` handler and then
	   * trigger a ``closed`` event on the view. Both receive a
	   * :js:class:`DialogCloseReason` argument to indicate how the dialog
	   * was closed.
	   *
	   * Version Added:
	   *     0.9
	   */
	  _onClose() {
	    /*
	     * If close() was not called and we didn't get a "cancel" event,
	     * then the dialog was manually closed through another mechanism.
	     * Provide a defaut, non-canceled reason.
	     */
	    const closeReason = this.#closeReason ??= {
	      action: null,
	      canceled: false
	    };

	    /* If there's an onClose handler, call this. */
	    const onClose = this.#onClose;
	    if (onClose) {
	      onClose(closeReason);
	    }

	    /* Trigger any event listeners. */
	    this.trigger('closed', closeReason);
	  }
	}) || _class2$1) || _class2$1);

	/**
	 * The type for a confirm dialog's body content.
	 *
	 * Version Added:
	 *     0.9
	 */

	/**
	 * Options for :js:func:`Ink.showErrorDialog`.
	 *
	 * Version Added:
	 *     0.9
	 */

	/**
	 * Options for :js:func:`Ink.showConfirmDialog`.
	 *
	 * Version Added:
	 *     0.9
	 */

	/**
	 * The result from the confirmation dialog.
	 *
	 * This will be returned from :js:func:`Ink.showConfirmDialog` if the user has
	 * confirmed the choice. It functions as a truthy value and contains state
	 * to help further process the confirmation choice.
	 *
	 * Version Added:
	 *     0.9
	 */

	/**
	 * Prompt the user for confirmation before performing an action.
	 *
	 * This will display a dialog with the provided title and body, asking the
	 * user to confirm an action or operation.
	 *
	 * The result of this call is a Promise, which will resolve only when the
	 * dialog has been closed. This makes it easy for a caller to request
	 * confirmation and wait until a choice is made before continuing on.
	 *
	 * If the caller provides a confirmation callback, and the user has clicked
	 * the Confirm button, the dialog's confirmation button will be in a busy
	 * state until that callback completes.
	 *
	 * Once a choice is made, the caller will receive a result through the
	 * Promise. If Cancel was clicked, the resulting promise will contain a
	 * ``null`` result. If Confirm was clicked, the caller will receive a
	 * :js:class:`ShowConfirmDialogResult`.
	 *
	 * Version Added:
	 *     0.9
	 *
	 * Args:
	 *     options (ShowConfirmDialogOptions):
	 *         Options for controlling the text and behavior of the dialog.
	 *
	 * Returns:
	 *     Promise<ShowConfirmDialogResult | null>:
	 *     The promise resolved once a choice is made.
	 */
	async function showConfirmDialog(options) {
	  async function onConfirm() {
	    let result = {
	      confirmButton: confirmButton,
	      dialog: dialogView,
	      suppressed: dialogView.isSuppressChecked
	    };
	    if (options.onConfirm) {
	      /* Let any errors bubble up, if not handled by onConfirm. */
	      const success = await options.onConfirm(result);
	      if (success === false) {
	        result = null;
	      }
	    }
	    return result;
	  }
	  const id = options.id || _.uniqueId('ink-confirm-dialog');
	  const confirmButton = craftComponent("Ink.DialogAction", {
	    id: id + "__confirm-action",
	    type: options.isDangerous ? ButtonType.DANGER : ButtonType.PRIMARY,
	    action: DialogActionType.CLOSE,
	    callback: async () => await onConfirm()
	  }, options.confirmButtonText || `Okay`);
	  const body = buildMessageDialogBody(options.body);
	  const dialogView = craftComponent("Ink.Dialog", {
	    id: id,
	    canSuppress: options.canSuppress,
	    suppressText: options.suppressText,
	    title: options.title
	  }, craftComponent("Ink.Dialog.Body", null, body), craftComponent("Ink.Dialog.PrimaryActions", null, craftComponent("Ink.DialogAction", {
	    id: id + "__cancel-action",
	    action: DialogActionType.CANCEL
	  }, options.cancelButtonText || `Cancel`), confirmButton));
	  const result = await dialogView.openAndWait();
	  return result.actionResult ?? null;
	}

	/**
	 * Display an error dialog containing a message and a Close button.
	 *
	 * This is useful for basic errors that demand a user's attention.
	 *
	 * The result of this call is a Promise, which will resolve only when the
	 * dialog has been closed. This makes it easy for a caller to display an
	 * error and wait until it's closed to continue on.
	 *
	 * Version Added:
	 *     0.9
	 *
	 * Args:
	 *     options (ShowErrorDialogOptions):
	 *         Options for controlling the text and behavior of the dialog.
	 *
	 * Returns:
	 *     Promise<void>:
	 *     The promise resolved once the dialog is closed.
	 */
	async function showErrorDialog(options) {
	  const error = options.error;
	  const id = options.id || _.uniqueId('ink-error-dialog');
	  let body;
	  if (error instanceof Error) {
	    body = error.message;
	  } else {
	    body = buildMessageDialogBody(error);
	  }
	  const dialogView = craftComponent("Ink.Dialog", {
	    id: id,
	    title: options.title ?? 'Something went wrong'
	  }, craftComponent("Ink.Dialog.Body", null, body), craftComponent("Ink.Dialog.PrimaryActions", null, craftComponent("Ink.DialogAction", {
	    id: id + "__close-action",
	    action: DialogActionType.CLOSE,
	    type: ButtonType.PRIMARY
	  }, `Close`)));
	  await dialogView.openAndWait();
	}

	/**
	 * Return HTML elements for a message dialog's body.
	 *
	 * This takes a string, HTMLElement, or array containing any number of either
	 * and returns HTML elements that can be used for a message dialog.
	 *
	 * Version Added:
	 *     0.9
	 *
	 * Args:
	 *     rawBody (MessageDialogBody):
	 *         The body to process.
	 *
	 * Returns:
	 *     Array of HTMLElement:
	 *     The resulting body contents.
	 */
	function buildMessageDialogBody(rawBody) {
	  let body;
	  if (rawBody) {
	    if (typeof rawBody === 'string') {
	      body = paintComponent("p", null, rawBody);
	    } else if (rawBody instanceof HTMLElement) {
	      body = [rawBody];
	    } else if (typeof rawBody[Symbol.iterator] === 'function') {
	      body = [];
	      for (const item of rawBody) {
	        if (typeof item === 'string') {
	          body.push(paintComponent("p", null, item));
	        } else if (item instanceof HTMLElement) {
	          body.push(item);
	        }
	      }
	    } else {
	      console.error('Invalid message dialog body: %o', rawBody);
	    }
	  }
	  return body || [];
	}
	var _dec$6, _class$9;

	/**
	 * The type of an alert.
	 *
	 * Version Added:
	 *     0.5
	 */
	let AlertType = /*#__PURE__*/function (AlertType) {
	  /** An alert showing an error. */
	  AlertType["ERROR"] = "error";
	  /** An alert representing an informational display. */
	  AlertType["INFO"] = "info";
	  /** A standard alert. */
	  AlertType["STANDARD"] = "standard";
	  /** An alert showing an operation was successful. */
	  AlertType["SUCCESS"] = "success";
	  /** An alert showing a warning. */
	  AlertType["WARNING"] = "warning";
	  return AlertType;
	}({});

	/**
	 * Options for AlertView.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Component for showing an alert panel for communicating status or information.
	 *
	 * Alerts are used to show helpful information or communicate status of an
	 * operation. They provide an icon, color, and title to represent the summary,
	 * and an optional description providing further detail.
	 *
	 * Version Added:
	 *     0.5
	 */
	let AlertView = (_dec$6 = inkComponent('Ink.Alert'), _dec$6(_class$9 = spina(_class$9 = class AlertView extends BaseComponentView {
	  static className = 'ink-c-alert';
	  static subcomponents = {
	    'Content': 'recordOneSubcomponent',
	    'Heading': 'recordOneSubcomponent',
	    'Actions': 'recordOneSubcomponent'
	  };
	  static events = {
	    'click .ink-c-alert__close': '_onClose'
	  };

	  /**********************
	   * Instance variables *
	   **********************/

	  /**
	   * The handler to invoke when the alert is closed.
	   */
	  #onClose;

	  /**
	   * Initialize the alert component.
	   *
	   * Args:
	   *     options (AlertViewOptions):
	   *         The options for the view.
	   */
	  initialize(options) {
	    super.initialize(options);
	    if (options) {
	      this.#onClose = options.onClose;
	    }
	  }

	  /**
	   * Handle the initial rendering of the component.
	   */
	  onComponentInitialRender() {
	    const el = this.el;
	    const state = this.initialComponentState;
	    const options = state.options;
	    const closeText = options.closeText || 'Close';
	    const subcomponents = state.subcomponents || {};
	    const actions = subcomponents['Actions'];
	    const content = subcomponents['Content'];
	    const heading = subcomponents['Heading'];
	    el.setAttribute('data-type', options.type || 'standard');
	    el.setAttribute('role', options.important ? 'alert' : 'status');
	    renderInto(el, [options.canClose && paintComponent("span", {
	      "class": "ink-c-alert__close",
	      role: "button",
	      title: closeText,
	      "aria-label": closeText,
	      tabindex: "0"
	    }), paintComponent("div", {
	      "class": "ink-c-alert__content"
	    }, paintComponent("h3", {
	      "class": "ink-c-alert__heading"
	    }, heading && heading[0].children), content && paintComponent("div", {
	      "class": "ink-c-alert__body"
	    }, content[0].children), actions && paintComponent("div", {
	      "class": "ink-c-alert__actions"
	    }, actions[0].children))]);
	  }

	  /**
	   * Handle clicking the close event.
	   *
	   * This will close the alert, and then call a close handler if provided
	   * by the consumer.
	   */
	  _onClose() {
	    this.remove();
	    if (this.#onClose) {
	      this.#onClose();
	    }
	  }
	}) || _class$9) || _class$9);
	var _class$8;

	/**
	 * Keyboard modifier flags.
	 *
	 * This is intentionally built as a subset of the attributes found in
	 * :js:class:`KeyboardEvent`.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Information on a registered keyboard shortcut.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Options for registering a keyboard shortcut.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Options for unregistering a keyboard shortcut.
	 */

	/**
	 * A registry for managing keyboard shortcuts.
	 *
	 * This allows consumers to register keyboard shortcuts that should activate
	 * a method when pressed. These may include :js:class:`KeyboardEvent` key
	 * names along with standard Control/Shift/Meta/Alt modifiers.
	 *
	 * This class is responsible for handling the registration. It should be
	 * passed as a model to :js:class:`KeyboardShortcutRegistryView`, which can be
	 * bound to the element that should handle these shortcuts.
	 *
	 * Version Added:
	 *     0.5
	 */
	let KeyboardShortcutRegistry = spina(_class$8 = class KeyboardShortcutRegistry extends BaseModel {
	  /**********************
	   * Instance variables *
	   **********************/

	  /**
	   * A mapping of keys representing shortcuts to registration information.
	   */
	  _shortcuts = new Map();

	  /**
	   * A registry for tracking when bound objects are finalized.
	   *
	   * This is used to attempt to proactively unregister shortcuts that are
	   * no longer needed.
	   */
	  #finalizationRegistry;

	  /**
	   * Initialize the registry.
	   *
	   * This will set up state to begin tracking and expiring keyboard
	   * shortcuts.
	   */
	  initialize() {
	    super.initialize();

	    /*
	     * Optimistically listen for when keyboard shortcuts bound to an
	     * element are garbage-collected. We can then unregister them.
	     */
	    this.#finalizationRegistry = new FinalizationRegistry(mapKey => {
	      const shortcuts = this._shortcuts;
	      if (shortcuts.has(mapKey)) {
	        shortcuts.delete(mapKey);
	      }
	    });
	  }

	  /**
	   * Register a keyboard shortcut.
	   *
	   * The provided handler will be invoked by the associated registry view
	   * any time this shortcut is pressed.
	   *
	   * Only one shortcut can be registered for any given combination of a key
	   * and modifiers.
	   *
	   * Args:
	   *     options (object):
	   *         The options for registering this shortcut.
	   *
	   * Returns:
	   *     object:
	   *     Information on the registered shortcut.
	   *
	   *     If there was a conflict, this will be ``null``.
	   */
	  registerShortcut(options) {
	    const shortcuts = this._shortcuts;
	    const key = options.key;
	    const modifiers = {
	      altKey: !!options.altKey,
	      ctrlKey: !!options.ctrlKey,
	      metaKey: !!options.metaKey,
	      shiftKey: !!options.shiftKey
	    };
	    const mapKey = this.#buildMapKey(key, modifiers);
	    const existingInfo = shortcuts.get(mapKey);

	    /*
	     * If the old shortcut is bound to an element that no longer
	     * exists, we can replace it. Ideally FinalizationRegistry would
	     * have told us, but it may not have had a chance yet.
	     */
	    if (existingInfo && !this._isExpired(existingInfo)) {
	      const label = this.#buildKeyLabel(key, modifiers);
	      console.warn(`Keyboard shortcut "${label}" is already registered.`);
	      return null;
	    }
	    const boundObj = options.boundObj;
	    const registeredInfo = {
	      boundObj: boundObj ? new WeakRef(boundObj) : null,
	      key: key,
	      modifiers: modifiers,
	      onInvoke: options.onInvoke
	    };
	    shortcuts.set(mapKey, registeredInfo);
	    if (boundObj) {
	      this.#finalizationRegistry.register(boundObj, mapKey);
	    }
	    return registeredInfo;
	  }

	  /**
	   * Unregister a keyboard shortcut.
	   *
	   * Args:
	   *     options (object):
	   *         The options for registering this shortcut.
	   */
	  unregisterShortcut(options) {
	    const shortcuts = this._shortcuts;
	    const key = options.key;
	    const modifiers = options;
	    const mapKey = this.#buildMapKey(key, modifiers);
	    if (shortcuts.has(mapKey)) {
	      shortcuts.delete(mapKey);
	    } else {
	      const label = this.#buildKeyLabel(key, modifiers);
	      console.warn(`Keyboard shortcut "${label}" is not registered.`);
	    }
	  }

	  /**
	   * Return a registered keyboard shortcut.
	   *
	   * Args:
	   *     key (string):
	   *         The registered key.
	   *
	   *     modifiers (object):
	   *         The registered modifier flags.
	   *
	   * Returns:
	   *     object:
	   *     Information on the keyboard shortcut.
	   *
	   *     This will be ``null`` if the shortcut could not be found.
	   */
	  getShortcut(key, modifiers = {}) {
	    const mapKey = this.#buildMapKey(key, modifiers);
	    let registeredShortcut = this._shortcuts.get(mapKey) || null;
	    if (registeredShortcut && this._isExpired(registeredShortcut)) {
	      this._shortcuts.delete(mapKey);
	      registeredShortcut = null;
	    }
	    return registeredShortcut;
	  }

	  /**
	   * Return whether a registered keyboard shortcut is expired.
	   *
	   * Args:
	   *     registeredShortcut (object):
	   *         The registered keyboard shortcut to check.
	   *
	   * Returns:
	   *     boolean:
	   *     ``true`` if the shortcut has expired. ``false`` if it is still
	   *     valid.
	   */
	  _isExpired(registeredShortcut) {
	    const boundObj = registeredShortcut.boundObj;
	    return boundObj !== null && boundObj.deref() === null;
	  }

	  /**
	   * Iterate over all registered keyboard shortcuts.
	   *
	   * Returns:
	   *     Iterator:
	   *     An iterator of registered keyboard shortcuts.
	   */
	  [Symbol.iterator]() {
	    const valuesIter = this._shortcuts.values();
	    return {
	      next: () => {
	        /*
	         * We need to ensure we only return shortcuts that are still
	         * valid. Ideally FinalizationRegistry would have told us, but
	         * it may not have had a chance yet.
	         *
	         * So the approach is to loop until we're either done or get a
	         * non-expired value, which we'll then return to the user.
	         */
	        let value;
	        while (value === undefined) {
	          const result = valuesIter.next();
	          if (result.done) {
	            return {
	              done: true,
	              value: undefined
	            };
	          } else {
	            value = result.value;
	            if (this._isExpired(value)) {
	              /* We'll skip this and try again. */
	              value = undefined;
	            }
	          }
	        }
	        return {
	          done: false,
	          value: value
	        };
	      }
	    };
	  }

	  /**
	   * Return a label describing a key and modifiers.
	   *
	   * This is currently only used internally for error reporting.
	   *
	   * Args:
	   *     key (string):
	   *         The key to show.
	   *
	   *     modifiers (object):
	   *         The modifiers to show.
	   *
	   * Returns:
	   *     string:
	   *     A label describing the keys.
	   */
	  #buildKeyLabel(key, modifiers) {
	    const parts = [];
	    if (modifiers.altKey) {
	      parts.push('Alt');
	    }
	    if (modifiers.shiftKey) {
	      parts.push('Shift');
	    }
	    if (modifiers.ctrlKey) {
	      parts.push('Control');
	    }
	    if (modifiers.metaKey) {
	      parts.push('Meta');
	    }
	    parts.push(key);
	    return parts.join('-');
	  }

	  /**
	   * Return a map key for shortcut registration and lookup.
	   *
	   * Args:
	   *     key (string):
	   *         The shortcut key.
	   *
	   *     modifiers (object):
	   *         The shortcut modifiers.
	   *
	   * Returns:
	   *     string:
	   *     A map key used for registration and lookup.
	   */
	  #buildMapKey(key, modifiers) {
	    let flags = 0;
	    if (modifiers.altKey) {
	      flags |= 0x01;
	    }
	    if (modifiers.ctrlKey) {
	      flags |= 0x02;
	    }
	    if (modifiers.metaKey) {
	      flags |= 0x04;
	    }
	    if (modifiers.shiftKey) {
	      flags |= 0x08;
	    }
	    return `${key.toLowerCase()}-${flags}`;
	  }
	}) || _class$8;
	var _class$7;

	/**
	 * Options for :js:func:`TypeaheadBuffer.helpFindItemWithPrefix`.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Attributes for TypeaheadBuffer.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * A typeahead buffer for tracking keys typed for UI navigation purposes.
	 *
	 * This tracks a sequence of keys entered within a short window of time, for
	 * the purpose of navigating or selecting items in a UI. It helps with
	 * navigating items, matching text, and automatically clearing the buffer
	 * once enough time has passed.
	 *
	 * Version Added:
	 *     0.5
	 */
	let TypeaheadBuffer = spina(_class$7 = class TypeaheadBuffer extends BaseModel {
	  static defaults = {
	    autoClearDelayMS: 3 * 1000
	  };

	  /**********************
	   * Instance variables *
	   **********************/

	  /**
	   * The type-ahead buffer, for navigating within the sidebar.
	   *
	   * This is cleared after ``autoClearDelayMS`` has passed since the last
	   * key was typed.
	   */
	  buffer = '';

	  /**
	   * A timeout handle for tracking when to clear the type-ahead buffer.
	   */
	  #clearTimeout = null;

	  /**
	   * Return whether there is content in the buffer.
	   *
	   * Returns:
	   *     boolean:
	   *     ``true`` if there's content in the buffer. ``false`` if there is
	   *     not.
	   */
	  hasContent() {
	    return this.buffer.length > 0;
	  }

	  /**
	   * Match text in the buffer against a provided string.
	   *
	   * The provided string will be normalized for comparison purposes. Only
	   * alphanumeric Latin characters will be considered.
	   *
	   * Args:
	   *     text (string):
	   *         The text to check for a match.
	   *
	   * Returns:
	   *     boolean:
	   *     ``true`` if the text matches. ``false`` if it does not.
	   */
	  matchesText(text) {
	    return this.#normalizeText(text).startsWith(this.buffer);
	  }

	  /**
	   * Helper to find an item matching the buffer.
	   *
	   * Args:
	   *     options (HelpFindItemWithPrefixOptions):
	   *         Options for performing the match.
	   *
	   * Returns:
	   *     any:
	   *     A matched item if found, or ``null`` if not found.
	   */
	  helpFindItemWithPrefix(options) {
	    const lastItem = options.lastItem !== undefined ? options.lastItem : null;
	    const getNextItem = options.getNextItem;
	    const getItemText = options.getItemText;
	    for (let item = options.firstItem;; item = getNextItem(item)) {
	      if (this.matchesText(getItemText(item))) {
	        return item;
	      }
	      if (item === lastItem || item === null || item === undefined) {
	        /* We're done. */
	        break;
	      }
	    }
	    return null;
	  }

	  /**
	   * Clear the buffer.
	   *
	   * This will reset the buffer and auto-clear timeout.
	   */
	  clearBuffer() {
	    this.#setBuffer('');
	  }

	  /**
	   * Handle a keydown event.
	   *
	   * This should be called by the consumer on ``keydown`` events. Depending
	   * on the key, this will add to the buffer, clear the buffer, or ignore
	   * the event.
	   *
	   * If this results in any change to the buffer, a ``bufferChanged`` event
	   * will be emitted with the buffer contents.
	   *
	   * Args:
	   *     evt (KeyboardEvent):
	   *         The keyboard event to handle.
	   *
	   * Returns:
	   *     boolean:
	   *     ``true`` if the event was handled. ``false`` if it was not.
	   */
	  handleKeyDown(evt) {
	    const key = evt.key;
	    if (key.length === 1 && (key.match(/[A-Za-z0-9]/) || this.buffer.length > 0)) {
	      /* Record the key and notify the consumer. */
	      evt.preventDefault();
	      evt.stopPropagation();
	      this.#setBuffer(this.buffer + key.toLowerCase());
	      return true;
	    } else if (key === 'Backspace') {
	      /* Backspace the typeahead buffer. */
	      evt.preventDefault();
	      evt.stopPropagation();
	      const bufLen = this.buffer.length;
	      if (bufLen > 0) {
	        this.#setBuffer(this.buffer.substring(0, bufLen - 1));
	      }
	      return true;
	    } else if (key === 'Escape') {
	      /* Clear the typeahead buffer. */
	      evt.preventDefault();
	      evt.stopPropagation();
	      this.#setBuffer('');
	      return true;
	    }
	    return false;
	  }

	  /**
	   * Set the current buffer contents.
	   *
	   * This will clear any current auto-clear timeout, set the buffer, emit
	   * a ``bufferChanged`` event, and then set up a new timeout (if there's
	   * content in the buffer).
	   *
	   * Args:
	   *     text (string):
	   *         The buffer text to set.
	   */
	  #setBuffer(text) {
	    text = this.#normalizeText(text);
	    if (text === this.buffer) {
	      return;
	    }
	    if (this.#clearTimeout !== null) {
	      clearTimeout(this.#clearTimeout);
	      this.#clearTimeout = null;
	    }
	    this.buffer = text;
	    this.trigger('bufferChanged', text);
	    if (text.length > 0) {
	      this.#clearTimeout = setTimeout(() => this.clearBuffer(), this.get('autoClearDelayMS'));
	    }
	  }

	  /**
	   * Normalize text for comparison.
	   *
	   * This is used for normalizing both the buffer contents and when
	   * normalizing text for comparison purposes.
	   *
	   * Args:
	   *     text (string):
	   *         The text to normalize
	   *         .
	   * Returns:
	   *     string:
	   *     The normalized text.
	   */
	  #normalizeText(text) {
	    return text.trim().replace(/[^A-Za-z0-9]/g, '').toLowerCase();
	  }
	}) || _class$7;
	var _class$6;
	/**
	 * A view for managing keyboard shortcut events on an element.
	 *
	 * This listens for keydown events on the bound element and invokes any
	 * shortcuts registered on the associated registry model. It can be used to
	 * bind keyboard shortcuts to the document or to a specific element and its
	 * ancestors.
	 *
	 * Version Added:
	 *     0.5
	 */
	let KeyboardShortcutRegistryView = spina(_class$6 = class KeyboardShortcutRegistryView extends BaseView {
	  static events = {
	    'keydown': '_onKeyDown'
	  };

	  /**
	   * A mapping of registered elements to views.
	   */
	  static registryViews = new WeakMap();

	  /**
	   * Return the nearest shortcut registry view in the element tree.
	   *
	   * This will scan up the element tree, looking for the nearest
	   * registry view, and return it if found.
	   *
	   * Args:
	   *     startEl (HTMLElement):
	   *         The starting element in the tree to search.
	   *
	   * Returns:
	   *     KeyboardShortcutRegistryView:
	   *     The registry view, or ``null`` if not found.
	   */
	  static findNearestRegistryView(startEl) {
	    const registryViews = KeyboardShortcutRegistryView.registryViews;
	    for (let el = startEl; el !== null; el = el.parentElement) {
	      const view = registryViews.get(el);
	      if (view) {
	        return view;
	      }
	    }
	    return null;
	  }

	  /**
	   * Return the nearest shortcut registry in the element tree.
	   *
	   * This will scan up the element tree, looking for the nearest
	   * registry view, and return its registry if found.
	   *
	   * Args:
	   *     startEl (HTMLElement):
	   *         The starting element in the tree to search.
	   *
	   * Returns:
	   *     KeyboardShortcutRegistry:
	   *     The registry, or ``null`` if not found.
	   */
	  static findNearestRegistry(startEl) {
	    const registryView = KeyboardShortcutRegistryView.findNearestRegistryView(startEl);
	    return registryView ? registryView.model : null;
	  }

	  /**
	   * Initialize the view.
	   *
	   * This will register the view with the provided element for future lookup.
	   */
	  initialize(...args) {
	    super.initialize(...args);
	    const registryViews = KeyboardShortcutRegistryView.registryViews;
	    const el = this.el;
	    if (registryViews.has(el)) {
	      console.warn('A KeyboardShortcutRegistryView is already registered for ' + 'element %o', el);
	    } else {
	      registryViews.set(el, this);
	    }
	  }

	  /**
	   * Handle the removal of the view.
	   *
	   * This will disassociate the view's registration from the element.
	   */
	  onRemove() {
	    KeyboardShortcutRegistryView.registryViews.delete(this.el);
	  }

	  /**
	   * Handle a keydown event.
	   *
	   * If the keydown maps to a registered shortcut, its handler will be
	   * invoked.
	   *
	   * Args:
	   *     e (KeyboardEvent):
	   *         The keydown event.
	   */
	  _onKeyDown(e) {
	    const shortcut = this.model.getShortcut(e.key, {
	      altKey: e.altKey,
	      ctrlKey: e.ctrlKey,
	      metaKey: e.metaKey,
	      shiftKey: e.shiftKey
	    });
	    if (shortcut) {
	      e.preventDefault();
	      e.stopPropagation();
	      shortcut.onInvoke();
	    }
	  }
	}) || _class$6;
	var _dec$5, _class$5, _dec2, _class2, _class3, _class4, _class5, _class6, _class7, _class8;

	/**
	 * Base options for menu open/close methods.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Options for opening a menu.
	 *
	 * This is used to control animation, events, and current item selection.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Options for closing a menu.
	 *
	 * This is used to control animation and events.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Options for a menu.
	 *
	 * This is used to control the menu's drop-down or embedded mode, list of
	 * menu items, and accessibility information.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * A drop-down or embedded menu of items.
	 *
	 * This is a standard menu, showing a list of items (standard action items,
	 * checkbox items, radio items, and separators) used to invoke actions or
	 * change configuration.
	 *
	 * Menu items can contain optional icons and keyboard shortcuts. They're
	 * expected to have a label.
	 *
	 * Menus and items are built to be accessible, helping those with screen
	 * readers navigate the menu.
	 *
	 * Version Added:
	 *     0.5
	 */
	let MenuView = (_dec$5 = inkComponent('Ink.Menu'), _dec$5(_class$5 = spina(_class$5 = class MenuView extends BaseComponentView {
	  static tagName = 'menu';
	  static className = 'ink-c-menu';
	  static subcomponents = {
	    'CheckboxItem': '_recordMenuItem',
	    'Header': '_recordMenuItem',
	    'Item': '_recordMenuItem',
	    'RadioItem': '_recordMenuItem',
	    'Separator': '_recordMenuItem'
	  };
	  static events = {
	    'click': '_onClick',
	    'focusin': '_onFocusIn',
	    'focusout': '_onFocusOut',
	    'keydown': '_onKeyDown',
	    'mouseenter .ink-c-menu__item': '_onMouseEnter',
	    'mouseleave': '_onMouseLeave'
	  };

	  /**
	   * The time in milliseconds before the menu is closed with a delay.
	   */
	  static DELAY_CLOSE_MS = 200;

	  /**
	   * The currently-opened menu item on the page.
	   */
	  static openedMenu = null;

	  /**********************
	   * Instance variables *
	   **********************/

	  /**
	   * The element that controls the display of this menu.
	   */
	  controllerEl = null;

	  /**
	   * Whether this menu is embedded within another element.
	   *
	   * When embedded, the menu will persist within an element, and won't
	   * automatically open or close.
	   */
	  embedded;

	  /**
	   * Whether an opened menu is sticky.
	   *
	   * A sticky menu will remain open until clicking a parent element or
	   * when another menu is opened. It will not close when moving the mouse
	   * outside of the menu or its controller.
	   */
	  isStickyOpen = null;

	  /** The collection of menu items used in this menu. */
	  menuItems;

	  /**
	   * The list of all all item views.
	   *
	   * Version Added:
	   *     0.5
	   */
	  #allItemViews = [];

	  /**
	   * A timeout handle ID for closing a menu with a delay.
	   */
	  #closeTimeoutHandle = null;

	  /**
	   * The index of the currently-selected item in the menu.
	   */
	  #curItemIndex = null;

	  /**
	   * The list of all menu item elements.
	   */
	  #items = [];

	  /**
	   * The list of all interactive item views.
	   */
	  #itemViews = [];

	  /**
	   * Whether focus is being carefully managed.
	   *
	   * When set, focus events won't be processed.
	   */
	  #managingFocus = false;

	  /**
	   * A bound handler for when the document is clicked.
	   *
	   * This is used as a stable handle when registering and unregistering
	   * event handlers for document clicks.
	   */
	  #onDocClick = null;

	  /**
	   * The typeahead buffer used for keyboard-based navigation.
	   */
	  #typeaheadBuffer;

	  /**
	   * Initialize the menu.
	   *
	   * Args:
	   *     options (MenuViewOptions, optional):
	   *         Options for customizing the menu.
	   */
	  initialize(options = {}) {
	    super.initialize(options);
	    options ??= {};
	    this.controllerEl = options.controllerEl ?? null;
	    this.embedded = !!options.embedded;

	    /* Ensure there's always an ID set, for accessibility references. */
	    this.id ||= _.uniqueId('_ink-c-menu');
	    const menuItems = options.menuItems || new MenuItemsCollection();
	    this.menuItems = menuItems;
	    this.initialComponentState.hasExistingMenuItems = !menuItems.isEmpty();
	    const typeaheadBuffer = new TypeaheadBuffer();
	    this.#typeaheadBuffer = typeaheadBuffer;
	    this.listenTo(typeaheadBuffer, 'bufferChanged', this.#onTypeaheadBufferChanged);
	  }

	  /**
	   * Return whether the menu is currently open.
	   *
	   * If the menu is in embedded mode, it's always considered open.
	   *
	   * Returns:
	   *     boolean:
	   *     ``true`` if the menu is open. ``false`` if it is closed.
	   */
	  get isOpen() {
	    return this.embedded || this.el.classList.contains('-is-open');
	  }

	  /**
	   * Open the menu.
	   *
	   * This will show the menu on the screen. Before it's shown, an ``opening``
	   * event will be emitted. Once shown (and after the animation finishes),
	   * the ``opened`` event will be emitted.
	   *
	   * If the menu is embedded, this won't do anything.
	   *
	   * Args:
	   *     options (MenuTransitionOptions, optional):
	   *         Options to use when opening the menu.
	   */
	  open(options = {}) {
	    /* Guard against null values from toggle(). */
	    options ??= {};

	    /*
	     * Regardless of the open state, we want to respect a stickyOpen=true
	     * setting. The user may have performed an action that should keep
	     * the menu open.
	     */
	    if (!this.isStickyOpen) {
	      this.isStickyOpen = !!options.sticky || this.embedded;
	    }
	    if (this.isOpen) {
	      /* If there's a delayed close in progress, cancel it. */
	      this.#clearDelayClose();
	      return;
	    }
	    const el = this.el;
	    const triggerEvents = options.triggerEvents !== false;
	    const currentItemIndex = options.currentItemIndex ?? null;

	    /* Close any existing menu. */
	    const cls = this.constructor;
	    if (cls.openedMenu !== null) {
	      cls.openedMenu.close({
	        animate: false
	      });
	    }
	    if (options.animate === false) {
	      /* Disable animation until the next render loop. */
	      el.classList.add('js-no-animation');
	      window.requestAnimationFrame(() => el.classList.remove('js-no-animation'));
	    }
	    if (triggerEvents) {
	      this.trigger('opening');
	    }
	    el.classList.add('-is-open');
	    el.tabIndex = 0;
	    if (currentItemIndex !== null) {
	      this.setCurrentItem(currentItemIndex);
	    }
	    cls.openedMenu = this;

	    /*
	     * Set up a handler so any click on the document will close the menu.
	     */
	    document.addEventListener('click', this.#onDocClick, {
	      once: true
	    });

	    /* Update the opened state on the controller. */
	    const controllerEl = this.controllerEl;
	    if (controllerEl !== null) {
	      controllerEl.setAttribute('aria-expanded', 'true');
	      controllerEl.classList.add('-is-menu-open');
	    }
	    if (triggerEvents) {
	      this.trigger('opened');
	    }
	  }

	  /**
	   * Close the menu.
	   *
	   * This will hide the menu. Before it's hidden, a ``closing`` event will
	   * be emitted. Once hidden (and after the animation finishes), the
	   * ``closed`` event will be emitted.
	   *
	   * Args:
	   *     options (CloseMenuOptions, optional):
	   *         Options for closing the menu.
	   */
	  close(options = {}) {
	    if (!this.isOpen) {
	      return;
	    }
	    this.#clearCurrentItem(false);
	    if (this.embedded) {
	      return;
	    }

	    /* Guard against null values from toggle(). */
	    options ??= {};

	    /*
	     * If there's an existing delay close operation, or we just completed
	     * one, we'l need to clear the handle.
	     */
	    this.#clearDelayClose();
	    if (options.delay) {
	      /*
	       * Wait until closing the menu.
	       *
	       * Once closed, the handle will be cleared as normal.
	       */
	      this.#closeTimeoutHandle = setTimeout(() => this.close(Object.assign({}, options, {
	        delay: false
	      })), MenuView.DELAY_CLOSE_MS);
	      return;
	    }
	    const el = this.el;
	    const controllerEl = this.controllerEl;
	    const triggerEvents = options.triggerEvents !== false;
	    if (options.animate === false) {
	      /* Disable animation until the next render loop. */
	      el.classList.add('js-no-animation');
	      window.requestAnimationFrame(() => el.classList.remove('js-no-animation'));
	    }
	    if (triggerEvents) {
	      this.trigger('closing');
	    }

	    /* Remove the opened accessibility state from the controller. */
	    if (controllerEl !== null) {
	      controllerEl.classList.remove('-is-menu-open');
	      controllerEl.setAttribute('aria-expanded', 'false');
	    }

	    /* Remove focus from the current item. */
	    const curItemIndex = this.#curItemIndex;
	    if (curItemIndex !== null) {
	      this.#items[curItemIndex].blur();
	    }
	    this.#clearCurrentItem(false);
	    el.classList.remove('-is-open');
	    el.tabIndex = -1;
	    document.removeEventListener('click', this.#onDocClick);
	    this.constructor.openedMenu = null;
	    this.isStickyOpen = null;
	    if (triggerEvents) {
	      this.trigger('closed');
	    }
	  }

	  /**
	   * Toggle display of the menu.
	   *
	   * This wraps :js:meth:`open` or :js:meth:`close`, based on the current
	   * state.
	   *
	   * Args:
	   *     openOptions (OpenMenuOptions, optional):
	   *         Options for opening the menu.
	   *
	   *     closeOptions (CloseMenuOptions, optional):
	   *         Options for closing the menu.
	   */
	  toggle(openOptions = {}, closeOptions = {}) {
	    if (this.isOpen) {
	      this.close(closeOptions);
	    } else {
	      this.open(openOptions);
	    }
	  }

	  /**
	   * Set the current selected item in the menu.
	   *
	   * Any negative index will wrap to the end, and any number higher than
	   * the length of items will wrap to the beginning.
	   *
	   * Args:
	   *     index (number):
	   *         The index to set.
	   *
	   *         If ``null``, the current selected item will be cleared, and
	   *         no new one will be set.
	   */
	  setCurrentItem(index) {
	    const items = this.#items;
	    const curItemIndex = this.#curItemIndex;
	    if (index === curItemIndex) {
	      return;
	    }
	    if (index === null || items.length === 0) {
	      this.#clearCurrentItem(true);
	      return;
	    }
	    this.#clearCurrentItem(false);
	    this.#clearDelayClose();
	    if (index < 0) {
	      index = items.length - 1;
	    } else if (index >= items.length) {
	      index = 0;
	    }
	    const itemEl = items[index];
	    itemEl.setAttribute('aria-selected', 'true');
	    itemEl.tabIndex = 0;
	    itemEl.focus();
	    this.el.setAttribute('aria-activedescendant', itemEl.id);
	    this.#curItemIndex = index;
	  }

	  /**
	   * Remove the menu from the DOM.
	   */
	  onRemove() {
	    this.close();
	    this.#clearMenuItems();
	  }

	  /**
	   * Handle initial rendering for the component.
	   *
	   * This will set up the menu's element in preparation for rendering the
	   * menu items.
	   */
	  onComponentInitialRender() {
	    const el = this.el;
	    const state = this.initialComponentState;
	    const options = state.options;
	    const embedded = this.embedded;

	    /* Set the initial attributes and state for the menu. */
	    el.setAttribute('role', 'menu');
	    el.id ||= _.result(this, 'id');
	    el.tabIndex = this.embedded ? 0 : -1;
	    if (options.ariaLabelledBy) {
	      el.setAttribute('aria-labelled-by', options.ariaLabelledBy);
	    } else if (options.ariaLabel) {
	      el.setAttribute('aria-label', options.ariaLabel);
	    }
	    if (embedded) {
	      el.classList.add('-is-embedded', '-is-open');
	    } else {
	      this.#onDocClick = () => this.close();
	    }

	    /* Set up the controller for the menu. */
	    const controllerEl = this.controllerEl;
	    if (controllerEl !== null) {
	      console.assert(el.id, 'MenuView element ID unexpectedly unset!');
	      controllerEl.setAttribute('aria-controls', el.id);
	      controllerEl.setAttribute('aria-expanded', 'false');
	      controllerEl.setAttribute('aria-haspopup', 'true');
	    }

	    /* Listen for updates to the menu items. */
	    this.listenTo(this.menuItems, 'update reset', this.render);
	  }

	  /**
	   * Render the menu items for the menu.
	   */
	  onRender() {
	    const el = this.el;
	    const curItemIndex = this.#curItemIndex;

	    /* Clear any old state. */
	    this.#clearMenuItems();
	    el.removeAttribute('aria-activedescendant');

	    /* Set up the items for the menu. */
	    let hasIcons = false;
	    let hasShortcuts = false;
	    const allItems = [];
	    const itemViews = [];
	    const menuItemEls = [];
	    const cid = this.cid;
	    for (const menuItem of this.menuItems) {
	      const menuItemType = menuItem.get('type');
	      const menuItemViewCls = _menuItemViews[menuItemType];
	      if (!menuItemViewCls) {
	        console.error('Unexpected menu item type: %s: %o', menuItemType, menuItem);
	        continue;
	      }
	      const interactive = !menuItemViewCls.isDecorative;
	      const menuItemID = menuItem.id || (interactive ? `menuitem-${cid}-${menuItemEls.length}` : null);
	      const menuItemView = craftComponent(menuItemViewCls, {
	        model: menuItem,
	        id: menuItemID
	      });
	      allItems.push(menuItemView);

	      /* Record all interactive menu items. */
	      if (interactive) {
	        const menuItemEl = menuItemView.el;
	        menuItemEl.dataset.itemIndex = menuItemEls.length.toString();
	        menuItemEls.push(menuItemEl);
	        itemViews.push(menuItemView);

	        /*
	         * Check and handle menu items that should close the menu
	         * when clicked.
	         */
	        if (menuItemView.closeOnClick) {
	          this.listenTo(menuItemView, 'clicked', () => this.close());
	        }
	      }
	      if (menuItemView.hasIcon) {
	        hasIcons = true;
	      }
	      if (menuItemView.hasShortcut) {
	        hasShortcuts = true;
	      }

	      /* If the menu item re-renders, re-compute menu state. */
	      this.listenTo(menuItemView, 'rendered', () => this.#updateMenuState());
	    }
	    renderInto(el, allItems, {
	      empty: true
	    });
	    this.#updateMenuState({
	      hasIcons: hasIcons,
	      hasShortcuts: hasShortcuts
	    });
	    this.#allItemViews = allItems;
	    this.#items = menuItemEls;
	    this.#itemViews = itemViews;

	    /*
	     * If a current menu item was already set, and is in the range,
	     * preserve it.
	     */
	    this.setCurrentItem(curItemIndex === null || curItemIndex >= menuItemEls.length ? null : curItemIndex);
	  }

	  /**
	   * Update the state of the menu.
	   *
	   * This will set the icon and shortcut classes based on the states either
	   * provided or calculated from the menu items.
	   *
	   * Args:
	   *     state (object):
	   *         Pre-computed flags indicating the current state.
	   */
	  #updateMenuState(state) {
	    let hasIcons;
	    let hasShortcuts;
	    if (state) {
	      hasIcons = state.hasIcons;
	      hasShortcuts = state.hasShortcuts;
	    } else {
	      hasIcons = false;
	      hasShortcuts = false;
	      for (const menuItemView of this.#allItemViews) {
	        if (menuItemView.hasIcon) {
	          hasIcons = true;
	        }
	        if (menuItemView.hasShortcut) {
	          hasShortcuts = true;
	        }
	        if (hasIcons && hasShortcuts) {
	          /* We can bail early. */
	          break;
	        }
	      }
	    }
	    const el = this.el;
	    el.classList.toggle('-has-icons', hasIcons);
	    el.classList.toggle('-has-shortcuts', hasShortcuts);
	  }

	  /**
	   * Clear the state for all the menu items.
	   *
	   * This will remove each menu item and clear the state so that changes
	   * to the items will no longer impact the menu.
	   */
	  #clearMenuItems() {
	    for (const menuItemView of this.#allItemViews) {
	      menuItemView.remove();
	    }
	    this.#allItemViews = [];
	    this.#items = [];
	    this.#itemViews = [];
	  }

	  /**
	   * Record a menu item from a subcomponent.
	   *
	   * This may represent a menu item (``Ink.Menu.Item``) or a separator
	   * (``Ink.Menu.Separator``).
	   *
	   * Args:
	   *     subcomponent (SubcomponentInfo):
	   *         Information on the subcomponent.
	   */
	  _recordMenuItem(subcomponent) {
	    if (this.initialComponentState.hasExistingMenuItems) {
	      throw Error('Ink.Menu can\'t contain subcomponents if configured with a ' + 'populated menuItems collection.');
	    }
	    const children = subcomponent.children;
	    const props = subcomponent.props || {};
	    let menuItemProps = {};
	    switch (subcomponent.name) {
	      case 'CheckboxItem': /* Pass-through */

	      case 'Item': /* Pass-through */

	      case 'RadioItem':
	        menuItemProps = {
	          childEl: props.childEl,
	          disabled: !!props.disabled,
	          iconName: props.iconName,
	          id: props.id,
	          keyboardShortcut: props.keyboardShortcut,
	          keyboardShortcutRegistry: props.keyboardShortcutRegistry,
	          label: children.length === 1 ? children[0] : null,
	          onClick: props.onClick,
	          url: props.url
	        };
	        if (subcomponent.name === 'CheckboxItem') {
	          menuItemProps['checked'] = props.checked;
	          menuItemProps['type'] = MenuItemType.CHECKBOX_ITEM;
	        } else if (subcomponent.name === 'RadioItem') {
	          menuItemProps['checked'] = props.checked;
	          menuItemProps['radioGroup'] = props.radioGroup;
	          menuItemProps['type'] = MenuItemType.RADIO_ITEM;
	        } else {
	          menuItemProps['type'] = MenuItemType.ITEM;
	        }
	        break;
	      case 'Header':
	        menuItemProps = {
	          childEl: props.childEl,
	          iconName: props.iconName,
	          id: props.id,
	          label: children.length === 1 ? children[0] : null,
	          type: MenuItemType.HEADER
	        };
	        break;
	      case 'Separator':
	        menuItemProps['type'] = MenuItemType.SEPARATOR;
	        break;
	      default:
	        console.assert(false, 'Not reached');
	        return;
	    }
	    this.menuItems.add(menuItemProps);
	  }

	  /**
	   * Clear a pending delayed close operation.
	   */
	  #clearDelayClose() {
	    if (this.#closeTimeoutHandle !== null) {
	      clearTimeout(this.#closeTimeoutHandle);
	      this.#closeTimeoutHandle = null;
	    }
	  }

	  /**
	   * Clear the current selection.
	   *
	   * Args:
	   *     setFocus (boolean, optional):
	   *         Whether to set the menu to be focused after clearing the
	   *         selection.
	   */
	  #clearCurrentItem(setFocus = true) {
	    const index = this.#curItemIndex;
	    this.el.removeAttribute('aria-activedescendant');
	    if (index !== null) {
	      const itemEl = this.#items[index];
	      if (itemEl) {
	        itemEl.removeAttribute('aria-selected');
	        itemEl.tabIndex = -1;
	      }
	      this.#curItemIndex = null;
	      this.#managingFocus = true;
	      if (setFocus) {
	        this.el.focus();
	      } else {
	        itemEl.blur();
	      }
	      this.#managingFocus = false;
	    }
	  }

	  /**
	   * Activate the current item.
	   *
	   * This will perform a click event on any ``<a>`` tag within the item,
	   * or on the item itself if needed.
	   *
	   * Args:
	   *     itemEl (MenuItemElement):
	   *         The item to activate.
	   */
	  #activateItem(itemEl) {
	    this.#clearDelayClose();
	    const clickEl = itemEl.querySelector('a') || itemEl;
	    clickEl.click();
	  }

	  /**
	   * Return the index for an item matching the typeahead buffer.
	   *
	   * Args:
	   *     firstIndex (number):
	   *         The first index to search.
	   *
	   *     lastIndex (number):
	   *         The last index to search.
	   *
	   * Returns:
	   *     number:
	   *     The index of the item that was found, or ``null`` if not found.
	   */
	  #findItemIndexForTypeahead(firstIndex, lastIndex) {
	    const items = this.#items;
	    return this.#typeaheadBuffer.helpFindItemWithPrefix({
	      firstItem: firstIndex,
	      lastItem: lastIndex,
	      getItemText: curIndex => items[curIndex].querySelector('.ink-c-menu__item-label').textContent,
	      getNextItem: curIndex => curIndex + 1
	    });
	  }

	  /**
	   * Handle a change to the typeahead buffer.
	   *
	   * If there's content in the buffer, this will attempt to find a menu
	   * item that matches.
	   *
	   * Args:
	   *     buffer (string):
	   *         The current typeahead buffer.
	   */
	  #onTypeaheadBufferChanged(buffer) {
	    if (buffer === '') {
	      return;
	    }
	    const items = this.#items;
	    const curItemIndex = this.#curItemIndex;
	    let index = this.#findItemIndexForTypeahead(curItemIndex || 0, items.length - 1);
	    if (index === null && curItemIndex) {
	      index = this.#findItemIndexForTypeahead(0, curItemIndex - 1);
	    }
	    if (index !== null) {
	      this.setCurrentItem(index);
	    }
	  }

	  /**
	   * Handle a click event.
	   *
	   * This will prevent the event from bubbling up past the menu.
	   *
	   * Args:
	   *     evt (MouseEvent):
	   *         The click event.
	   */
	  _onClick(evt) {
	    /* Prevent bubbling up. */
	    evt.stopPropagation();
	  }

	  /**
	   * Handle a focusin event.
	   *
	   * If focusing to the menu itself, the first item will be selected.
	   *
	   * Args:
	   *     evt (FocusEvent):
	   *         The focus event.
	   */
	  _onFocusIn(evt) {
	    evt.stopPropagation();
	    evt.preventDefault();
	    if (!this.#managingFocus && evt.target === this.el) {
	      this.setCurrentItem(this.#curItemIndex || 0);
	    }
	  }

	  /**
	   * Handle a focusout event.
	   *
	   * If focusing outside of the menu, the menu will be closed.
	   *
	   * Args:
	   *     evt (FocusEvent):
	   *         The focus event.
	   */
	  _onFocusOut(evt) {
	    evt.stopPropagation();
	    evt.preventDefault();
	    if (this.#managingFocus) {
	      return;
	    }
	    const relatedTarget = evt.relatedTarget;
	    const controllerEl = this.controllerEl;
	    if (!this.el.contains(relatedTarget) && (!controllerEl || controllerEl !== relatedTarget && !controllerEl.contains(relatedTarget))) {
	      /* Focus moved outside of this element. */
	      if (this.embedded) {
	        /* Clear focus when moving out of the element.*/
	        this.#clearCurrentItem(false);
	      } else {
	        /* This is a drop-down menu. Close the menu. */
	        this.close();
	      }
	    }
	  }

	  /**
	   * Handle a keydown event.
	   *
	   * See the view's docs for the list of supported keyboard shortcuts.
	   *
	   * Args:
	   *     evt (KeyboardEvent):
	   *         The keydown event.
	   */
	  _onKeyDown(evt) {
	    const key = evt.key;
	    this.#typeaheadBuffer.handleKeyDown(evt);
	    switch (key) {
	      /* Move down an item */
	      case 'ArrowDown': /* Fall through */

	      case 'Down':
	        /*
	         * Focus the next item in the menu, or wrap to the beginning
	         * of the menu.
	         */
	        evt.preventDefault();
	        evt.stopPropagation();
	        this.setCurrentItem(this.#curItemIndex === null ? 0 : this.#curItemIndex + 1);
	        break;

	      /* Move up an item */
	      case 'ArrowUp': /* Fall through */

	      case 'Up':
	        /*
	         * Focus the previous item in the menu, or wrap to the end
	         * of the menu.
	         */
	        evt.preventDefault();
	        evt.stopPropagation();
	        this.setCurrentItem(this.#curItemIndex === null ? -1 : this.#curItemIndex - 1);
	        break;

	      /* Navigate to start of menu */
	      case 'PageUp': /* Fall through */

	      case 'Home':
	        /*
	         * Focus to the first item in the menu.
	         */
	        evt.preventDefault();
	        evt.stopPropagation();
	        this.setCurrentItem(0);
	        break;

	      /* Navigate to end of menu */
	      case 'PageDown': /* Fall through */

	      case 'End':
	        /*
	         * Focus to the last item in the menu.
	         */
	        evt.preventDefault();
	        evt.stopPropagation();
	        this.setCurrentItem(-1);
	        break;

	      /* Activate current item */
	      case ' ': /* Fall through */

	      case 'Enter':
	        /*
	         * Activate the current item.
	         */
	        if (this.#curItemIndex !== null) {
	          evt.preventDefault();
	          evt.stopPropagation();
	          const index = this.#curItemIndex;
	          if (!this.#itemViews[index].model.get('disabled')) {
	            const itemEl = this.#items[index];
	            this.#activateItem(itemEl);

	            /*
	             * For checkbox and radio menu items, Space should
	             * activate but not close. For standard menu items, it
	             * should close.
	             */
	            if (key === 'Enter' || itemEl.getAttribute('role') === 'menuitem') {
	              this.close();
	            }
	          }
	        }
	        break;

	      /* Close the menu */
	      case 'Tab': /* Fall through */

	      case 'Escape':
	        /*
	         * Close the menu.
	         */
	        evt.preventDefault();
	        evt.stopPropagation();
	        this.close({
	          animate: false
	        });

	        /* Focus the controller. */
	        if (this.controllerEl !== null) {
	          this.controllerEl.focus();
	        }
	        break;
	    }
	  }

	  /**
	   * Handle a mouseenter event.
	   *
	   * This will set the current item based on the item receiving the event.
	   *
	   * Args:
	   *     evt (MouseEvent):
	   *         The mouseenter event.
	   */
	  _onMouseEnter(evt) {
	    evt.stopPropagation();
	    evt.preventDefault();
	    const itemEl = evt.target.closest('.ink-c-menu__item');
	    if (itemEl) {
	      const itemIndex = itemEl.dataset.itemIndex;
	      if (itemIndex !== undefined) {
	        this.setCurrentItem(parseInt(itemIndex, 10));
	      } else {
	        this.#clearCurrentItem(false);
	      }
	    }
	  }

	  /**
	   * Handle a mouseleave event.
	   *
	   * This will unset the current item, if the mouse is leaving the menu.
	   *
	   * Args:
	   *     evt (MouseEvent):
	   *         The mouseleave event.
	   */
	  _onMouseLeave(evt) {
	    if (!this.el.contains(evt.relatedTarget)) {
	      evt.stopPropagation();
	      evt.preventDefault();
	      this.#clearCurrentItem(true);
	      if (!this.isStickyOpen) {
	        this.close();
	      }
	    }
	  }
	}) || _class$5) || _class$5);

	/**
	 * Base class for menu items.
	 *
	 * This sets some basic state on the menu item. It's meant to be subclassed
	 * to control additional state and rendering.
	 *
	 * Version Added:
	 *     0.5
	 */
	let BaseMenuItemView = (_dec2 = spina({
	  prototypeAttrs: ['isDecorative']
	}), _dec2(_class2 = class BaseMenuItemView extends BaseComponentView {
	  static tagName = 'li';
	  static attributes = {
	    'draggable': false,
	    'tabIndex': '-1'
	  };

	  /**
	   * Whether the menu item is purely decorational/informative.
	   *
	   * Decorative menu items cannot be selected or invoked.
	   *
	   * Version Added:
	   *     0.8
	   */
	  static isDecorative = false;
	  /**********************
	   * Instance variables *
	   **********************/

	  /** Whether clicking the menu item should close the menu. */
	  closeOnClick = false;

	  /** Whether the menu item will display or reserve space for an icon. */
	  hasIcon = false;

	  /** Whether the menu item will display a keyboard shortcut. */
	  hasShortcut = false;
	}) || _class2);
	/**
	 * A standard menu item.
	 *
	 * This provides common rendering and state management for menu items. It
	 * will render the label (or custom element) and an optional icon and
	 * keyboard shortcut. Updates to the information in the model will trigger
	 * a re-render of the menu item.
	 *
	 * Subclasses can introduce additional state and rendering logic.
	 *
	 * Version Added:
	 *     0.5
	 */
	let MenuItemView = spina(_class3 = class MenuItemView extends BaseMenuItemView {
	  static className = 'ink-c-menu__item';
	  static attributes = {
	    'role': 'menuitem'
	  };
	  static events = {
	    'click': '_onClick'
	  };
	  static modelEvents = {
	    'change:childEl': '_onMenuItemChanged',
	    'change:disabled': '_onMenuItemChanged',
	    'change:iconName': '_onMenuItemChanged',
	    'change:keyboardShortcut': '_onMenuItemChanged',
	    'change:keyboardShortcutRegistry': '_onMenuItemChanged',
	    'change:label': '_onMenuItemChanged',
	    'change:url': '_onMenuItemChanged'
	  };

	  /**********************
	   * Instance variables *
	   **********************/

	  /**
	   * Whether clicking the menu item should close the menu.
	   *
	   * By default, menu items will close when clicked. This can be overridden
	   * by subclasses.
	   */
	  closeOnClick = true;

	  /**
	   * The view managing the keyboard shortcut.
	   */
	  #keyboardShortcutView = null;

	  /**
	   * Update state for the menu item.
	   *
	   * This will compute state to set on the view. Subclasses can override
	   * this to compute or override any state.
	   */
	  updateMenuItemState() {
	    const model = this.model;
	    this.hasIcon = !!model.get('iconName');
	    this.hasShortcut = !!model.get('keyboardShortcut');
	  }

	  /**
	   * Handle removing the menu item.
	   *
	   * This will unregister state associated with the menu item.
	   */
	  onRemove() {
	    super.onRemove();
	    this.#keyboardShortcutView?.remove();
	  }

	  /**
	   * Handle the initial rendering of the component.
	   *
	   * This will calculate the state from the model prior to the first render.
	   */
	  onComponentInitialRender() {
	    this.updateMenuItemState();
	  }

	  /**
	   * Render the menu item.
	   *
	   * This will rebuild the internals of the menu item based on the current
	   * menu item state.
	   */
	  onRender() {
	    const el = this.el;
	    const model = this.model;
	    const iconName = model.get('iconName');
	    const label = model.get('label');
	    const registry = model.get('keyboardShortcutRegistry');
	    const shortcut = model.get('keyboardShortcut');
	    const url = model.get('url');
	    const innerProps = {};
	    let iconEl;
	    let innerTag;

	    /* Clean up any old state. */
	    this.#keyboardShortcutView?.remove();
	    if (url) {
	      innerTag = 'a';
	      innerProps['href'] = url;
	    } else {
	      innerTag = 'span';
	    }
	    if (this.hasIcon) {
	      const iconClass = iconName ? `ink-c-menu__item-icon ${iconName}` : 'ink-c-menu__item-icon';
	      iconEl = paintComponent("span", {
	        "class": iconClass,
	        "aria-hidden": "true"
	      });
	    }
	    let keyboardShortcutView = null;
	    if (shortcut) {
	      keyboardShortcutView = craftComponent("Ink.KeyboardShortcut", {
	        className: "ink-c-menu__item-shortcut",
	        keys: shortcut,
	        registry: registry,
	        onInvoke: "click"
	      });
	    }
	    if (model.get('disabled')) {
	      el.setAttribute('aria-disabled', 'true');
	    } else {
	      el.removeAttribute('aria-disabled');
	    }
	    renderInto(el, paintComponent(innerTag, {
	      "class": "ink-c-menu__item-inner",
	      role: "presentation",
	      tabIndex: "-1",
	      ...innerProps
	    }, iconEl, paintComponent("label", {
	      "class": "ink-c-menu__item-label"
	    }, model.get('childEl') || label), keyboardShortcutView), {
	      empty: true
	    });
	    this.#keyboardShortcutView = keyboardShortcutView;
	  }

	  /**
	   * Handle changes to the menu item.
	   *
	   * This will compute new menu item state and then trigger a re-render.
	   */
	  _onMenuItemChanged() {
	    this.updateMenuItemState();
	    this.render();
	  }

	  /**
	   * Handle a click on the menu item.
	   *
	   * This will invoke the action associated with the menu item, and then
	   * emit a ``clicked`` event.
	   *
	   * Args:
	   *     evt (MouseEvent):
	   *         The mouse event triggering this handler.
	   */
	  _onClick(evt) {
	    evt.stopPropagation();
	    const model = this.model;
	    model.get('disabled');
	    if (model.get('disabled')) {
	      evt.preventDefault();
	      return;
	    }
	    if (!model.get('url')) {
	      evt.preventDefault();
	    }
	    model.invokeAction(evt);
	    this.trigger('clicked');
	  }
	}) || _class3;
	/**
	 * Base class for a checkable menu item.
	 *
	 * This provides common state management for checkable menu items (checkbox
	 * and radio button items).
	 *
	 * Version Added:
	 *     0.5
	 */
	let BaseCheckableMenuItemView = spina(_class4 = class BaseCheckableMenuItemView extends MenuItemView {
	  static modelEvents = {
	    'change:checked': '_onCheckedChanged'
	  };

	  /**
	   * A mapping of item types to checkmark icon classes.
	   *
	   * This is only for checkbox and radio items.
	   *
	   * Version Added:
	   *     0.5
	   */
	  static _CHECKED_ICONS = {
	    [MenuItemType.CHECKBOX_ITEM]: 'ink-i-check',
	    [MenuItemType.RADIO_ITEM]: 'ink-i-dot'
	  };

	  /**********************
	   * Instance variables *
	   **********************/

	  /* Never close on click. Keep the menu open so the toggle can occur. */
	  closeOnClick = false;

	  /**
	   * Update state for the menu item.
	   *
	   * This will load state from the menu item and then force the parent menu
	   * to always reserve space for a checkable state icon, even if not
	   * checked.
	   */
	  updateMenuItemState() {
	    super.updateMenuItemState();

	    /* Always claim space for an icon. */
	    this.hasIcon = true;
	  }

	  /**
	   * Render the menu item.
	   *
	   * This will perform the standard rendering of the menu item and then
	   * update the icon to reflect the current checkable state.
	   */
	  onRender() {
	    super.onRender();
	    this._onCheckedChanged();
	  }

	  /**
	   * Handle changes to the checked state of the menu item.
	   *
	   * This will update the icon to reflect the state of the menu item.
	   */
	  _onCheckedChanged() {
	    const el = this.el;
	    const model = this.model;
	    const checked = model.get('checked');
	    const checkIconName = this.constructor._CHECKED_ICONS[model.get('type')];
	    el.setAttribute('aria-checked', `${checked}`);
	    el.querySelector('.ink-c-menu__item-icon').classList.toggle(checkIconName, checked);
	  }
	}) || _class4;
	/**
	 * A checkbox menu item.
	 *
	 * Version Added:
	 *     0.5
	 */
	let CheckboxMenuItemView = spina(_class5 = class CheckboxMenuItemView extends BaseCheckableMenuItemView {
	  static attributes = {
	    'role': 'menuitemcheckbox'
	  };
	}) || _class5;
	/**
	 * A radio menu item.
	 *
	 * Version Added:
	 *     0.5
	 */
	let RadioMenuItemView = spina(_class6 = class RadioMenuItemView extends BaseCheckableMenuItemView {
	  static attributes = {
	    'role': 'menuitemradio'
	  };
	}) || _class6;
	/**
	 * A header menu item.
	 *
	 * This can't be clicked, but can be used to group together related menu
	 * items.
	 *
	 * Version Added:
	 *     0.8
	 */
	let HeaderMenuItemView = spina(_class7 = class HeaderMenuItemView extends MenuItemView {
	  static className = 'ink-c-menu__item -is-header';
	  static attributes = {
	    /* Headers are essentially titled separators. */
	    'role': 'separator'
	  };
	  static isDecorative = true;
	  closeOnClick = false;
	}) || _class7;
	/**
	 * A separator menu item.
	 *
	 * Version Added:
	 *     0.5
	 */
	let SeparatorMenuItemView = spina(_class8 = class SeparatorMenuItemView extends BaseMenuItemView {
	  static className = 'ink-c-menu__separator';
	  static attributes = {
	    'role': 'separator'
	  };
	  static isDecorative = true;
	}) || _class8;
	/**
	 * A mapping of menu item types to view classes.
	 *
	 * Version Added:
	 *     0.5
	 */
	const _menuItemViews = {
	  [MenuItemType.ITEM]: MenuItemView,
	  [MenuItemType.CHECKBOX_ITEM]: CheckboxMenuItemView,
	  [MenuItemType.HEADER]: HeaderMenuItemView,
	  [MenuItemType.RADIO_ITEM]: RadioMenuItemView,
	  [MenuItemType.SEPARATOR]: SeparatorMenuItemView
	};

	/**
	 * The direction in which a menu will open from the handle.
	 *
	 * Menu handles compute this automatically, based on available screen space.
	 *
	 * Version Added:
	 *     0.5
	 */
	let MenuHandleOpenDirection = /*#__PURE__*/function (MenuHandleOpenDirection) {
	  /** The menu opens in an up direction. */
	  MenuHandleOpenDirection["UP"] = "up";
	  /** The menu opens in a down direction. */
	  MenuHandleOpenDirection["DOWN"] = "down";
	  return MenuHandleOpenDirection;
	}({});

	/**
	 * Options for building a menu for a menu handle.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Options for BaseMenuHandleView.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Base class for components that work as a drop-down menu handle.
	 *
	 * This contains the base logic for managing a menu, including its menu items
	 * and open state. Subclasses can build upon this to control the rendering
	 * of the menu handle, while leveraging standard behavior and accessibility
	 * for the menu.
	 *
	 * Version Added:
	 *     0.5
	 */
	class BaseMenuHandleView extends BaseComponentView {
	  static allowComponentChildren = true;
	  static subcomponents = MenuView.subcomponents;

	  /**********************
	   * Instance variables *
	   **********************/

	  /** The menu associated with the handle. */
	  menuView = null;

	  /** The direction that the menu will open. */
	  _openDirection = MenuHandleOpenDirection.DOWN;

	  /**
	   * Return the menu items collection for the drop-down menu.
	   *
	   * This can be used to fetch or manipulate the items in the menu.
	   *
	   * Returns:
	   *     MenuItemsCollection:
	   *     The collection of menu items.
	   */
	  get menuItems() {
	    return this.menuView.menuItems;
	  }

	  /**
	   * Whether the menu can be opened.
	   *
	   * Subclasses can override this to only allow opening a menu based on
	   * a disabled state or similar.
	   *
	   * Returns:
	   *     boolean:
	   *     ``true`` if the menu is allowed to be opened. ``false`` if it is
	   *     not.
	   */
	  canOpenMenu() {
	    return true;
	  }
	  buildMenu(options) {
	    const state = this.initialComponentState;
	    const componentOptions = state.options;
	    const menuLabel = options.menuAriaLabel || componentOptions.menuAriaLabel || 'Menu';
	    const controllerEl = options.controllerEl;
	    const menuID = options.menuID ?? `ink-menu-handle__${this.cid}`;

	    /* Build the internal menu and listen for events. */
	    const menuView = craftComponent("Ink.Menu", {
	      "aria-label": menuLabel,
	      "class": options.menuClassName,
	      controllerEl: controllerEl,
	      id: menuID,
	      menuItems: componentOptions.menuItems
	    }, state.subcomponents['_MenuItem']);
	    this.menuView = menuView;
	    this.listenTo(menuView, 'opening', () => controllerEl.classList.add('js-hover'));
	    this.listenTo(menuView, 'closing', () => controllerEl.classList.remove('js-hover'));
	    this.listenTo(menuView, 'opened', () => this._updateMenuPosition(controllerEl));
	    controllerEl.addEventListener('click', evt => this.#onControllerClicked(evt));
	    controllerEl.addEventListener('keydown', evt => this.#onControllerKeyDown(evt));
	    if (options.openOnHover !== false) {
	      controllerEl.addEventListener('mouseover', evt => this.#onControllerMouseEnter(evt));
	    }
	    return menuView;
	  }

	  /**
	   * Handle removing the element.
	   *
	   * This will explicitly remove the menu.
	   *
	   * Subclasses must call this.
	   */
	  onRemove() {
	    this.menuView.remove();
	  }

	  /**
	   * Record a menu item subcomponent.
	   *
	   * The subcomponent will be updated to work with ``Ink.Menu`` so that it
	   * can be passed in during render.
	   *
	   * Args:
	   *     subcomponent (SubcomponentInfo):
	   *         Information on the subcomponent.
	   */
	  _recordMenuItem(subcomponent) {
	    const subcomponents = this.initialComponentState.subcomponents;
	    let menuItems = subcomponents['_MenuItem'];
	    if (!menuItems) {
	      menuItems = [];
	      subcomponents['_MenuItem'] = menuItems;
	    }

	    /* Transform this for the internal Ink.Menu, and store it. */
	    subcomponent.fullName = `Ink.Menu.${subcomponent.name}`;
	    menuItems.push(subcomponent);
	  }

	  /**
	   * Position the drop-down menu.
	   *
	   * This will attempt to determine whether there's enough space below
	   * the controller for the menu to fully appear. If there is not, then the
	   * menu will appear above the controller instead.
	   *
	   * The resulting direction will also impact the styling of the controller
	   * and menu, helping to create a connected appearance.
	   *
	   * This also ensures that the menu will always appear fully on screen
	   * according to the width of the viewport.
	   *
	   * Args:
	   *     controllerEl (HTMLElement):
	   *         The controller for the menu that the element will be positioned
	   *         relative to.
	   */
	  _updateMenuPosition(controllerEl) {
	    const controllerElBoundingRect = controllerEl.getBoundingClientRect();
	    const controllerY1 = controllerElBoundingRect.top + window.pageYOffset - document.documentElement.clientTop;
	    const controllerY2 = controllerY1 + controllerEl.clientHeight;
	    const pageY1 = window.pageYOffset;
	    const pageY2 = window.pageYOffset + window.innerHeight;
	    const menuEl = this.menuView.el;
	    let direction;
	    if (pageY1 >= controllerY1) {
	      /*
	       * The controller is at least partially off-screen, above the
	       * current viewport. Drop the menu down.
	       */
	      direction = MenuHandleOpenDirection.DOWN;
	    } else if (pageY2 <= controllerY2) {
	      /*
	       * The controller is at least partially off-screen, below the
	       * current viewport. Drop the menu up.
	       */
	      direction = MenuHandleOpenDirection.UP;
	    } else {
	      const menuHeight = menuEl.offsetHeight;

	      /*
	       * The controller is fully on-screen. See if there's enough room
	       * below the controller for the menu.
	       */
	      if (pageY2 >= controllerY2 + menuHeight || controllerY1 - pageY1 - menuHeight < 0) {
	        /* The menu can fully fit below the controller. */
	        direction = MenuHandleOpenDirection.DOWN;
	      } else {
	        /* The menu cannot fully fit below the controller. */
	        direction = MenuHandleOpenDirection.UP;
	      }
	    }
	    this._openDirection = direction;
	    this.el.classList.toggle('-opens-up', direction === MenuHandleOpenDirection.UP);

	    /* Position the menu relative to the controller. */
	    const offsetPx = `${controllerEl.clientHeight}px`;
	    menuEl.style.top = direction === MenuHandleOpenDirection.DOWN ? offsetPx : '';
	    menuEl.style.bottom = direction === MenuHandleOpenDirection.UP ? offsetPx : '';

	    /* Position the menu laterally according to the viewport width. */
	    const menuWidth = menuEl.offsetWidth;
	    const windowWidth = document.documentElement.clientWidth;
	    const elOffsetLeft = controllerElBoundingRect.left;
	    let newMenuLeft = '';
	    if (elOffsetLeft + menuWidth > windowWidth) {
	      /*
	       * The right side of the menu is being clipped. Try to right-align
	       * it with the handle first.
	       */
	      let newMenuLeftNum = controllerElBoundingRect.width - menuWidth;
	      if (newMenuLeftNum + menuWidth > windowWidth) {
	        /*
	         * That was still off-screen (meaning the handle was likely
	         * off-screen. Align this with the right edge of the viewport.
	         */
	        newMenuLeftNum = windowWidth - menuWidth - elOffsetLeft;
	      }
	      if (newMenuLeftNum + elOffsetLeft < 0) {
	        /*
	         * It's off the left of the screen. Align this with the
	         * left edge of the viewport.
	         */
	        newMenuLeftNum = -elOffsetLeft;
	      }
	      newMenuLeft = `${newMenuLeftNum}px`;
	    }
	    menuEl.style.left = newMenuLeft;

	    /* Make sure the menu is never wider than the viewport. */
	    menuEl.style.maxWidth = `${windowWidth}px`;
	  }

	  /**
	   * Handle a click event on the controller.
	   *
	   * When clicked, the menu will be opened in sticky mode.
	   *
	   * Args:
	   *     evt (MouseEvent):
	   *         The click event.
	   */
	  #onControllerClicked(evt) {
	    evt.stopPropagation();
	    evt.preventDefault();
	    if (this.canOpenMenu()) {
	      this.menuView.open({
	        sticky: true
	      });
	    }
	  }

	  /**
	   * Handle a keydown event on the controller.
	   *
	   * When the menu handle has focus, this will take care of handling
	   * keyboard-based navigation, allowing the menu to be opened or closed.
	   * Opening the menu will transfer focus to the menu items.
	   *
	   * Args:
	   *     evt (KeyboardEvent):
	   *         The keydown event.
	   */
	  #onControllerKeyDown(evt) {
	    if (evt.key === 'ArrowDown' || evt.key === 'ArrowUp' || evt.key === 'Enter' || evt.key === ' ') {
	      /*
	       * Open the menu and set the current item, based on the open
	       * direction.
	       */
	      evt.stopPropagation();
	      evt.preventDefault();
	      if (this.canOpenMenu()) {
	        const menu = this.menuView;
	        menu.open({
	          animate: false,
	          sticky: true
	        });
	        if (this._openDirection === MenuHandleOpenDirection.UP) {
	          menu.setCurrentItem(-1);
	        } else {
	          menu.setCurrentItem(0);
	        }
	      }
	    } else if (evt.key === 'Escape') {
	      /* Close out of the menu. */
	      evt.stopPropagation();
	      evt.preventDefault();
	      this.menuView.close({
	        animate: false
	      });
	    }
	  }

	  /**
	   * Handle a mouseenter event on the controller.
	   *
	   * This will open the menu.
	   *
	   * Args:
	   *     e (MouseEvent):
	   *         The mouseenter event.
	   */
	  #onControllerMouseEnter(evt) {
	    evt.stopPropagation();
	    evt.preventDefault();
	    if (this.canOpenMenu()) {
	      this.menuView.open();
	    }
	  }
	}
	var _dec$4, _class$4;

	/**
	 * Options for ButtonGroupView.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Component for showing a group of buttons either horizontally or vertically.
	 *
	 * This allows a group of buttons that are closely related to be grouped
	 * together without visual separation.
	 *
	 * This is not meant to be used as a toolbar, but more of a menu of buttons.
	 *
	 * Version Added:
	 *     0.5
	 */
	let ButtonGroupView = (_dec$4 = inkComponent('Ink.ButtonGroup'), _dec$4(_class$4 = spina(_class$4 = class ButtonGroupView extends BaseComponentView {
	  static tagName = 'div';
	  static className = 'ink-c-button-group';
	  static allowComponentChildren = true;

	  /**
	   * Set the orientation for the group layout.
	   *
	   * Args:
	   *     newOrientation (Orientation):
	   *         The new orientation.
	   */
	  set orientation(newOrientation) {
	    this.el.setAttribute('aria-orientation', newOrientation === Orientation.VERTICAL ? 'vertical' : 'horizontal');
	  }

	  /**
	   * Return the orientation for the group layout.
	   *
	   * Returns:
	   *     Orientation:
	   *     The current group layout orientation.
	   */
	  get orientation() {
	    return this.el.getAttribute('aria-orientation') === 'vertical' ? Orientation.VERTICAL : Orientation.HORIZONTAL;
	  }

	  /**
	   * Handle the initial rendering of the component.
	   *
	   * This will perform a render of the buttons in the group.
	   */
	  onComponentInitialRender() {
	    const el = this.el;
	    const state = this.initialComponentState;
	    el.setAttribute('role', 'group');
	    this.orientation = state.options.orientation;
	    renderInto(el, state.children);
	  }
	}) || _class$4) || _class$4);
	var _dec$3, _class$3;

	/**
	 * A mapping from consumer-provided key labels to symbols.
	 *
	 * This will map certain key labels (such as Control or Tab) to familiar
	 * symbols or strings, depending on the platform.
	 *
	 * Version Added:
	 *     0.5
	 */
	const SYMBOL_MAP = window.navigator.platform === 'MacIntel' ? {
	  'Alt': '⌥',
	  'AltGraph': '⌥',
	  'ArrowDown': '↓',
	  'ArrowLeft': '←',
	  'ArrowRight': '→',
	  'ArrowUp': '↑',
	  'Backspace': '⌫',
	  'CapsLock': '⇪',
	  'Control': '⌃',
	  'Delete': '⌫',
	  'Enter': '↩︎',
	  'Escape': 'Esc',
	  'Meta': '⌘',
	  'Return': '↩︎',
	  'Shift': '⇧',
	  'Tab': '⇥'
	} : {
	  'ArrowDown': '↓',
	  'ArrowLeft': '←',
	  'ArrowRight': '→',
	  'ArrowUp': '↑',
	  'Escape': 'Esc'
	};

	/**
	 * A mapping of consumer-provided key labels to standard labels.
	 *
	 * Mapped labels are used both for symbol lookup and for inclusion in
	 * ``aria-keyshortcuts``.
	 *
	 * Version Added:
	 *     0.5
	 */
	const KEY_ALIAS_MAP = {
	  'Cmd': 'Meta',
	  'Down': 'ArrowDown',
	  'Left': 'ArrowLeft',
	  'Option': 'AltGraph',
	  'Right': 'ArrowRight',
	  'Up': 'ArrowUp'
	};

	/**
	 * A mapping of normalized key modifier labels to flags.
	 *
	 * Version Added:
	 *     0.5
	 */
	const KEY_EVENT_MODIFIER_MAP = {
	  'Alt': 'altKey',
	  'AltGraph': 'altKey',
	  'Cmd': 'metaKey',
	  'Control': 'ctrlKey',
	  'Meta': 'metaKey',
	  'Shift': 'shiftKey'
	};

	/**
	 * Options for KeyboardShortcutView.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Component for showing and registering a keyboard shortcut.
	 *
	 * This displays a visual indicator for a keyboard shortcut, attempting to
	 * display the keys in a form that makes sense on the target platform. It
	 * also takes care of registering ARIA information on the keyboard shortcuts
	 * and an event handler for the shortcut to invoke an action (if ``onInvoke``
	 * and ``registry`` are provided).
	 *
	 * Version Added:
	 *     0.5
	 */
	let KeyboardShortcutView = (_dec$3 = inkComponent('Ink.KeyboardShortcut'), _dec$3(_class$3 = spina(_class$3 = class KeyboardShortcutView extends BaseComponentView {
	  static tagName = 'span';
	  static className = 'ink-c-keyboard-shortcut';

	  /**********************
	   * Instance variables *
	   **********************/

	  /**
	   * The computed value for an ``aria-keyshortcuts`` attributes.
	   */
	  #ariaKeyShortcuts = null;

	  /**
	   * A reference to information on a keyboard shortcut registration.
	   */
	  #registeredInfoRef = null;

	  /**
	   * A reference to a keyboard shortcut registry used for registration.
	   */
	  #registryRef = null;

	  /**
	   * Initialize the component.
	   *
	   * This will validate the options. It may throw an error if there are
	   * necessary options missing.
	   *
	   * Args:
	   *     options (object):
	   *         The options for the component.
	   */
	  initialize(options) {
	    super.initialize(options);

	    /* Validate and normalize settings. */
	    if (!options || !options.keys) {
	      throw Error('Ink.KeyboardShortcut is missing a value for option "keys".');
	    }
	    const onInvoke = options.onInvoke;
	    if (!!onInvoke !== !!options.registry) {
	      throw Error('Ink.KeyboardShortcut onInvoke and registry must both be ' + 'set in order to register a shortcut.');
	    }
	    if (onInvoke) {
	      if (onInvoke === 'click') {
	        options.onInvoke = () => this.el.click();
	      } else if (typeof onInvoke !== 'function') {
	        throw Error('Ink.KeyboardShortcut onInvoke must be "click" or a ' + 'function.');
	      }
	    }
	  }

	  /**
	   * Attach information for this keyboard shortcut to a parent element.
	   *
	   * This should be called for interactive elements registering keyboard
	   * shortcuts in order to set the proper accessibility information on
	   * parent elements.
	   *
	   * Args:
	   *     el (HTMLElement):
	   *         The interactive element to attach this to.
	   */
	  attachTo(el) {
	    el.setAttribute('aria-keyshortcuts', this.#ariaKeyShortcuts);
	    this.el.setAttribute('aria-hidden', 'true');
	  }

	  /**
	   * Handle the removal of the component.
	   *
	   * This will unregister any registered keyboard shortcut.
	   */
	  onRemove() {
	    const registeredInfo = this.#registeredInfoRef?.deref();
	    if (registeredInfo) {
	      const modifiers = registeredInfo.modifiers;
	      this.#registryRef?.deref()?.unregisterShortcut({
	        altKey: modifiers.altKey,
	        ctrlKey: modifiers.ctrlKey,
	        key: registeredInfo.key,
	        metaKey: modifiers.metaKey,
	        shiftKey: modifiers.shiftKey
	      });
	    }
	    this.#registryRef = null;
	    this.#registeredInfoRef = null;
	  }

	  /**
	   * Handle the initial render of the component.
	   *
	   * This will render the keyboard shortcut in a form suitable for the
	   * local operating system, and attach ARIA information.
	   *
	   * It will also take care of registering the shortcut with a registry,
	   * if needed.
	   */
	  onComponentInitialRender() {
	    const el = this.el;
	    const options = this.initialComponentState.options;
	    const rawKeys = options.keys;
	    const keys = rawKeys.split('-');
	    const ariaKeys = [];
	    const registerOptions = {};
	    const symbolMap = options.showSymbols !== false ? SYMBOL_MAP : {};
	    el.title = rawKeys;
	    el.setAttribute('aria-label', rawKeys);
	    for (const key of keys) {
	      const normKey = KEY_ALIAS_MAP[key] || key;
	      const modifier = KEY_EVENT_MODIFIER_MAP[key];
	      ariaKeys.push(normKey);
	      if (modifier) {
	        registerOptions[modifier] = true;
	      } else {
	        console.assert(!registerOptions.key, `Too many non-modifier keys in "${rawKeys}"`);
	        registerOptions.key = normKey;
	      }
	      renderInto(el, paintComponent("span", {
	        "class": "ink-c-keyboard-shortcut__key",
	        "aria-hidden": "true"
	      }, symbolMap[normKey] || key));
	    }
	    this.#ariaKeyShortcuts = ariaKeys.join('+');
	    if (options.attachTo) {
	      this.attachTo(options.attachTo);
	    }

	    /* Register the keyboard shortcut, if requested. */
	    const onInvoke = options.onInvoke;
	    const registry = options.registry;
	    if (registry && onInvoke) {
	      /* Set up the event dispatch handler. */
	      const registeredInfo = registry.registerShortcut({
	        altKey: registerOptions.altKey,
	        boundObj: this.el,
	        ctrlKey: registerOptions.ctrlKey,
	        key: registerOptions.key,
	        metaKey: registerOptions.metaKey,
	        onInvoke: onInvoke,
	        shiftKey: registerOptions.shiftKey
	      });

	      /* Make sure registration was successful, and didn't conflict. */
	      if (registeredInfo) {
	        this.#registeredInfoRef = new WeakRef(registeredInfo);
	        this.#registryRef = new WeakRef(registry);
	      }
	    }
	  }
	}) || _class$3) || _class$3);
	var _dec$2, _class$2;

	/**
	 * Options for MenuButtonView.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Component for showing a button that opens a drop-down menu.
	 *
	 * Menu Buttons contain a label and a drop-down handle. When hovering over
	 * the button or invoking it via a click or Space/Enter/arrow key, a specified
	 * menu will appear.
	 *
	 * A Menu Button may contain a separate action button, which is distinct from
	 * the drop-down menu handle button. This allows for a primary action that is
	 * separate from a menu of actions or options.
	 *
	 * Just like a Button, a Menu Button may have a type, which communicates its
	 * intent via a color hint.
	 *
	 * Version Added:
	 *     0.5
	 */
	let MenuButtonView = (_dec$2 = inkComponent('Ink.MenuButton'), _dec$2(_class$2 = spina(_class$2 = class MenuButtonView extends BaseMenuHandleView {
	  static className = 'ink-c-menu-button';

	  /**********************
	   * Instance variables *
	   **********************/

	  /** The action button, if one is configured. */
	  actionButtonView = null;

	  /** The action button, if one is configured. */
	  actionButtonEl = null;

	  /** The drop-down button. */
	  dropdownButtonView = null;

	  /**
	   * Return whether the menu button is in a busy state.
	   *
	   * Returns:
	   *     boolean:
	   *     ``true`` if the menu button is in a busy state. ``false`` if it
	   *     is not.
	   */
	  get busy() {
	    return this.el.getAttribute('aria-busy') === 'true';
	  }

	  /**
	   * Set whether the menu button is in a busy state.
	   *
	   * Args:
	   *     newBusy (boolean):
	   *         ``true`` if the menu button should be in a busy state. ``false``
	   *         if it should not.
	   */
	  set busy(newBusy) {
	    if (newBusy) {
	      this.el.setAttribute('aria-busy', 'true');
	    } else {
	      this.el.removeAttribute('aria-busy');
	    }
	    if (this.actionButtonView !== null) {
	      this.actionButtonView.busy = newBusy;
	      if (!this.disabled) {
	        this.dropdownButtonView.disabled = newBusy;
	      }
	    } else {
	      this.dropdownButtonView.busy = newBusy;
	    }
	  }

	  /**
	   * Return whether the menu button is disabled.
	   *
	   * Returns:
	   *     boolean:
	   *     ``true`` if the button is disabled. ``false`` if it is not.
	   */
	  get disabled() {
	    return (this.actionButtonView || this.dropdownButtonView).disabled;
	  }

	  /**
	   * Set whether the menu button is disabled.
	   *
	   * Args:
	   *     newDisabled (boolean):
	   *         ``true`` if the button should be disabled. ``false``
	   *         if it should not.
	   */
	  set disabled(newDisabled) {
	    this.dropdownButtonView.disabled = newDisabled;
	    if (this.actionButtonView !== null) {
	      this.actionButtonView.disabled = newDisabled;
	    }
	  }

	  /**
	   * Return the name of the icon shown on the dropdown handle button.
	   *
	   * Returns:
	   *     string:
	   *     The name of the icon shown.
	   */
	  get iconName() {
	    return this.dropdownButtonView.iconName;
	  }

	  /**
	   * Set the name of the icon to show on the dropdown handle button.
	   *
	   * Args:
	   *     newIconName (string):
	   *         The name of the icon to show.
	   *
	   *         This can be set to ``null`` to hide an icon.
	   */
	  set iconName(newIconName) {
	    this.dropdownButtonView.iconName = newIconName;
	  }

	  /**
	   * Return the label shown on the button.
	   *
	   * Returns:
	   *     string:
	   *     The label shown on the button.
	   */
	  get label() {
	    return (this.actionButtonView || this.dropdownButtonView).label;
	  }

	  /**
	   * Set the label to show on the button.
	   *
	   * Args:
	   *     newLabel (string):
	   *         The label to show.
	   */
	  set label(newLabel) {
	    (this.actionButtonView || this.dropdownButtonView).label = newLabel;
	  }

	  /**
	   * Return the type of the menu button.
	   *
	   * Returns:
	   *     ButtonType:
	   *     The current type of the menu button.
	   */
	  get type() {
	    return this.dropdownButtonView.type;
	  }

	  /**
	   * Set the type of the button.
	   *
	   * Args:
	   *     newType (ButtonType):
	   *         The type of the button.
	   */
	  set type(newType) {
	    this.dropdownButtonView.type = newType;
	    if (this.actionButtonView !== null) {
	      this.actionButtonView.type = newType;
	    }
	  }

	  /**
	   * Whether the menu can be opened.
	   *
	   * Menus can be opened if the button is not disabled.
	   *
	   * Returns:
	   *     boolean:
	   *     ``true`` if the menu is allowed to be opened. ``false`` if it is
	   *     not.
	   */
	  canOpenMenu() {
	    return !this.disabled;
	  }

	  /**
	   * Handle initially rendering the button.
	   *
	   * This will set up the button, based on any provided options, and
	   * then render the menu.
	   */
	  onComponentInitialRender() {
	    const el = this.el;
	    const state = this.initialComponentState;
	    const options = state.options;
	    el.setAttribute('role', 'group');
	    const buttonLabel = options.label || '';
	    const cid = this.cid;

	    /*
	     * Build the internal buttons.
	     *
	     * If there's an action button, we'll build that and put it and
	     * the dropdown handle button into a group.
	     *
	     * If there's no action button, we'll just use the handle button
	     * as the only button, and place the label there.
	     */
	    const dropdownButtonProps = {
	      'aria-label': options.dropdownButtonAriaLabel || 'Open menu',
	      'class': 'ink-c-menu-button__dropdown-button',
	      'iconName': options.menuIconName || 'ink-i-dropdown',
	      'id': `ink-menu-button__dropdown__${cid}`
	    };
	    const dropdownButton = craftComponent("Ink.Button", dropdownButtonProps);
	    if (options.hasActionButton) {
	      const actionButton = craftComponent("Ink.Button", {
	        "class": "ink-c-menu-button__action-button",
	        onClick: options.onActionButtonClick
	      }, buttonLabel);
	      this.actionButtonView = actionButton;
	      renderInto(el, paintComponent("Ink.ButtonGroup", {
	        "class": "ink-c-menu-button__buttons"
	      }, actionButton, dropdownButton));
	    } else {
	      dropdownButton.label = buttonLabel;
	      renderInto(el, dropdownButton);
	    }
	    this.dropdownButtonView = dropdownButton;

	    /* Build the internal menu and listen for events. */
	    renderInto(el, this.buildMenu({
	      controllerEl: dropdownButton.el,
	      menuAriaLabel: options.menuAriaLabel || `Menu for ${buttonLabel}`,
	      menuClassName: 'ink-c-menu-button__menu',
	      menuID: `ink-menu-button__menu__${cid}`,
	      openOnHover: true
	    }));
	    Object.assign(this, _.pick(options, 'busy', 'disabled', 'label', 'type'));
	  }

	  /**
	   * Handle removing the element.
	   *
	   * This will explicitly remove the menu as well.
	   */
	  onRemove() {
	    this.dropdownButtonView.remove();
	    super.onRemove();
	  }
	}) || _class$2) || _class$2);
	var _dec$1, _class$1;

	/**
	 * Options for MenuLabelView.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Component for showing a label that opens a drop-down menu.
	 *
	 * Menu Labels contain label text, a drop-down handle icon, and an optional
	 * icon. When hovering over the label or invoking it via a click or
	 * Space/Enter/arrow key, a specified menu will appear.
	 *
	 * Version Added:
	 *     0.5
	 */
	let MenuLabelView = (_dec$1 = inkComponent('Ink.MenuLabel'), _dec$1(_class$1 = spina(_class$1 = class MenuLabelView extends BaseMenuHandleView {
	  static tagName = 'span';
	  static className = 'ink-c-menu-label';

	  /**********************
	   * Instance variables *
	   **********************/

	  /** The element managing the icon. */
	  #iconEl = null;

	  /** The name of the icon shown. */
	  #iconName = null;

	  /** The inner element containing the label and icon information. */
	  #innerEl = null;

	  /** The element managing the label text. */
	  #textEl = null;

	  /**
	   * Return whether the menu label is disabled.
	   *
	   * Returns:
	   *     boolean:
	   *     ``true`` if the button is disabled. ``false`` if it is not.
	   */
	  get disabled() {
	    return this.el.getAttribute('aria-disabled') === 'true';
	  }

	  /**
	   * Set whether the menu label is disabled.
	   *
	   * Args:
	   *     newDisabled (boolean):
	   *         ``true`` if the button should be disabled. ``false``
	   *         if it should not.
	   */
	  set disabled(newDisabled) {
	    if (newDisabled) {
	      this.el.setAttribute('aria-disabled', 'true');
	    } else {
	      this.el.removeAttribute('aria-disabled');
	    }
	  }

	  /**
	   * Return the name of the icon shown alongside the label.
	   *
	   * Returns:
	   *     string:
	   *     The name of the icon shown.
	   */
	  get iconName() {
	    return this.#iconName;
	  }

	  /**
	   * Set the name of the icon to show on the dropdown handle button.
	   *
	   * Args:
	   *     newIconName (string):
	   *         The name of the icon to show.
	   *
	   *         This can be set to ``null`` to hide an icon.
	   */
	  set iconName(newIconName) {
	    if (!newIconName) {
	      newIconName = null;
	    }
	    if (newIconName === this.#iconName) {
	      return;
	    }
	    let iconEl = this.#iconEl;
	    if (iconEl === null) {
	      if (newIconName) {
	        iconEl = paintComponent("span", {
	          "class": "ink-c-menu-label__icon " + newIconName,
	          "aria-hidden": "true"
	        });
	        this.#iconEl = iconEl;
	        renderInto(this.#innerEl, iconEl, {
	          prepend: true
	        });
	      }
	    } else {
	      if (newIconName) {
	        iconEl.className = `ink-c-menu-label__icon ${newIconName}`;
	      } else {
	        iconEl.remove();
	        this.#iconEl = null;
	      }
	    }
	    this.#iconName = newIconName;
	  }

	  /**
	   * Return the text shown on the label.
	   *
	   * Returns:
	   *     string:
	   *     The text shown on the label.
	   */
	  get text() {
	    return this.#textEl.textContent || '';
	  }

	  /**
	   * Set the text to show on the label.
	   *
	   * Args:
	   *     newLabel (string):
	   *         The text to show.
	   */
	  set text(newLabel) {
	    this.#textEl.textContent = newLabel || '';
	  }

	  /**
	   * Whether the menu can be opened.
	   *
	   * Menus can be opened if the button is not disabled.
	   *
	   * Returns:
	   *     boolean:
	   *     ``true`` if the menu is allowed to be opened. ``false`` if it is
	   *     not.
	   */
	  canOpenMenu() {
	    return !this.disabled;
	  }

	  /**
	   * Handle initially rendering the label.
	   *
	   * This will set up the label, based on any provided options, and then
	   * render the menu.
	   */
	  onComponentInitialRender() {
	    const el = this.el;
	    const state = this.initialComponentState;
	    const options = state.options;
	    el.setAttribute('role', 'menuitem');
	    el.setAttribute('tabindex', '0');
	    const text = options.text || '';
	    const innerEl = craftComponent("span", {
	      "class": "ink-c-menu-label__inner"
	    });
	    const textEl = craftComponent("span", {
	      "class": "ink-c-menu-label__text"
	    });
	    innerEl.appendChild(textEl);
	    const dropDownIconName = options.dropDownIconName;
	    if (dropDownIconName !== null && dropDownIconName !== '') {
	      const className = 'ink-c-menu-label__dropdown-icon ' + (options.dropDownIconName || 'ink-i-dropdown');
	      innerEl.appendChild(craftComponent("span", {
	        "class": className
	      }));
	    }
	    this.#textEl = textEl;
	    this.#innerEl = innerEl;
	    el.appendChild(innerEl);

	    /* Build the internal menu and listen for events. */
	    renderInto(el, this.buildMenu({
	      controllerEl: el,
	      menuAriaLabel: options.menuAriaLabel || `Menu for ${text}`,
	      menuClassName: 'ink-c-menu-label__menu',
	      menuID: `ink-menu-label__menu__${this.cid}`,
	      openOnHover: true
	    }));
	    Object.assign(this, _.pick(options, 'disabled', 'iconName', 'text'));
	  }
	}) || _class$1) || _class$1);
	var _dec, _class;

	/**
	 * Options for SpinnerView.
	 *
	 * Version Added:
	 *     0.5
	 */

	/**
	 * Component for showing a spinner.
	 *
	 * This will show a spinner indicating that an operation is taking place, such
	 * as content loading from a server.
	 *
	 * When using the spinner to represent content loading in a parent element,
	 * it's best to set ``aria-busy="true"`` on that element in order to inform
	 * screen readers that the content is still loading. It's very important to
	 * remove this attribute once the load has completed.
	 *
	 * This should be used along with ``aria-live=`` to indicate that the
	 * element will be updated.
	 *
	 * Alternatively, you might want to use ``aria-hidden="false"`` on this, if
	 * it should not be read or seen by the screen reader, or ``aria-label="..."``
	 * if it should (and does not otherwise have accompanying text).
	 *
	 * Version Added:
	 *     0.5
	 */
	let SpinnerView = (_dec = inkComponent('Ink.Spinner'), _dec(_class = spina(_class = class SpinnerView extends BaseView {
	  static tagName = 'span';
	  static className = 'ink-c-spinner';
	}) || _class) || _class);

	const Ink = /*#__PURE__*/Object.defineProperty({
		__proto__: null,
		AlertType,
		AlertView,
		BaseComponentView,
		BaseMenuHandleView,
		ButtonGroupView,
		ButtonType,
		ButtonView,
		ComponentRegistry,
		DialogActionType,
		DialogActionView,
		DialogSize,
		DialogView,
		KeyboardShortcutRegistry,
		KeyboardShortcutRegistryView,
		KeyboardShortcutView,
		MenuButtonView,
		MenuHandleOpenDirection,
		MenuItem,
		MenuItemType,
		MenuItemsCollection,
		MenuItemsRadioGroup,
		MenuLabelView,
		MenuView,
		Orientation,
		SpinnerView,
		TypeaheadBuffer,
		componentRegistry,
		craft,
		craftComponent,
		craftComponents,
		inkComponent,
		isSubcomponentInfo,
		paint,
		paintComponent,
		paintComponents,
		paintCraftedElements,
		renderInto,
		renderNodesInto,
		setProps,
		showConfirmDialog,
		showErrorDialog
	}, Symbol.toStringTag, { value: 'Module' });

	/* Load the jQuery-related modules */

	/* Export what's needed to the global namespace. */
	const _global = typeof globalThis !== 'undefined' ? globalThis : self;
	_global.Backbone = Backbone;
	_global.CodeMirror = CodeMirror;
	_global.Ink = Ink;
	_global.Spina = Spina;
	_global._ = _;
	_global.moment = moment;

	/* This module doesn't import correctly, so we help it out. */
	setupJQueryForm(_global, $);

}));
//# sourceMappingURL=index.js.map
