/* Minification failed. Returning unminified contents.
(64786,390912-390913): run-time error JS1010: Expected identifier: .
(64786,390912-390913): run-time error JS1195: Expected expression: .
 */
/*! jQuery UI - v1.10.3 - 2013-07-01
* http://jqueryui.com
* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.menu.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.spinner.js, jquery.ui.tabs.js, jquery.ui.tooltip.js, jquery.ui.effect.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js
* Copyright 2013 jQuery Foundation and other contributors Licensed MIT */

(function( $, undefined ) {

var uuid = 0,
	runiqueId = /^ui-id-\d+$/;

// $.ui might exist from components with no dependencies, e.g., $.ui.position
$.ui = $.ui || {};

$.extend( $.ui, {
	version: "1.10.3",

	keyCode: {
		BACKSPACE: 8,
		COMMA: 188,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		LEFT: 37,
		NUMPAD_ADD: 107,
		NUMPAD_DECIMAL: 110,
		NUMPAD_DIVIDE: 111,
		NUMPAD_ENTER: 108,
		NUMPAD_MULTIPLY: 106,
		NUMPAD_SUBTRACT: 109,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SPACE: 32,
		TAB: 9,
		UP: 38
	}
});

// plugins
$.fn.extend({
	focus: (function( orig ) {
		return function( delay, fn ) {
			return typeof delay === "number" ?
				this.each(function() {
					var elem = this;
					setTimeout(function() {
						$( elem ).focus();
						if ( fn ) {
							fn.call( elem );
						}
					}, delay );
				}) :
				orig.apply( this, arguments );
		};
	})( $.fn.focus ),

	scrollParent: function() {
		var scrollParent;
		if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
			}).eq(0);
		}

		return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent;
	},

	zIndex: function( zIndex ) {
		if ( zIndex !== undefined ) {
			return this.css( "zIndex", zIndex );
		}

		if ( this.length ) {
			var elem = $( this[ 0 ] ), 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;
	},

	uniqueId: function() {
		return this.each(function() {
			if ( !this.id ) {
				this.id = "ui-id-" + (++uuid);
			}
		});
	},

	removeUniqueId: function() {
		return this.each(function() {
			if ( runiqueId.test( this.id ) ) {
				$( this ).removeAttr( "id" );
			}
		});
	}
});

// selectors
function focusable( element, isTabIndexNotNaN ) {
	var map, mapName, img,
		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 + "]" )[0];
		return !!img && visible( img );
	}
	return ( /input|select|textarea|button|object/.test( nodeName ) ?
		!element.disabled :
		"a" === nodeName ?
			element.href || isTabIndexNotNaN :
			isTabIndexNotNaN) &&
		// the element and all of its ancestors must be visible
		visible( element );
}

function visible( element ) {
	return $.expr.filters.visible( element ) &&
		!$( element ).parents().addBack().filter(function() {
			return $.css( this, "visibility" ) === "hidden";
		}).length;
}

$.extend( $.expr[ ":" ], {
	data: $.expr.createPseudo ?
		$.expr.createPseudo(function( dataName ) {
			return function( elem ) {
				return !!$.data( elem, dataName );
			};
		}) :
		// support: jQuery <1.8
		function( elem, i, match ) {
			return !!$.data( elem, match[ 3 ] );
		},

	focusable: function( element ) {
		return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
	},

	tabbable: function( element ) {
		var tabIndex = $.attr( element, "tabindex" ),
			isTabIndexNaN = isNaN( tabIndex );
		return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
	}
});

// support: jQuery <1.8
if ( !$( "<a>" ).outerWidth( 1 ).jquery ) {
	$.each( [ "Width", "Height" ], function( i, name ) {
		var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
			type = name.toLowerCase(),
			orig = {
				innerWidth: $.fn.innerWidth,
				innerHeight: $.fn.innerHeight,
				outerWidth: $.fn.outerWidth,
				outerHeight: $.fn.outerHeight
			};

		function reduce( elem, size, border, margin ) {
			$.each( side, function() {
				size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
				if ( border ) {
					size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
				}
				if ( margin ) {
					size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
				}
			});
			return size;
		}

		$.fn[ "inner" + name ] = function( size ) {
			if ( size === undefined ) {
				return orig[ "inner" + name ].call( this );
			}

			return this.each(function() {
				$( this ).css( type, reduce( this, size ) + "px" );
			});
		};

		$.fn[ "outer" + name] = function( size, margin ) {
			if ( typeof size !== "number" ) {
				return orig[ "outer" + name ].call( this, size );
			}

			return this.each(function() {
				$( this).css( type, reduce( this, size, true, margin ) + "px" );
			});
		};
	});
}

// support: jQuery <1.8
if ( !$.fn.addBack ) {
	$.fn.addBack = function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter( selector )
		);
	};
}

// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
	$.fn.removeData = (function( removeData ) {
		return function( key ) {
			if ( arguments.length ) {
				return removeData.call( this, $.camelCase( key ) );
			} else {
				return removeData.call( this );
			}
		};
	})( $.fn.removeData );
}





// deprecated
$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );

$.support.selectstart = "onselectstart" in document.createElement( "div" );
$.fn.extend({
	disableSelection: function() {
		return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
			".ui-disableSelection", function( event ) {
				event.preventDefault();
			});
	},

	enableSelection: function() {
		return this.unbind( ".ui-disableSelection" );
	}
});

$.extend( $.ui, {
	// $.ui.plugin is deprecated. Use $.widget() extensions instead.
	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 ) {
			var i,
				set = instance.plugins[ name ];
			if ( !set || !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 );
				}
			}
		}
	},

	// only used by resizable
	hasScroll: function( el, a ) {

		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ( $( el ).css( "overflow" ) === "hidden") {
			return false;
		}

		var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
			has = false;

		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
		el[ scroll ] = 1;
		has = ( el[ scroll ] > 0 );
		el[ scroll ] = 0;
		return has;
	}
});

})( jQuery );
(function( $, undefined ) {

var uuid = 0,
	slice = Array.prototype.slice,
	_cleanData = $.cleanData;
$.cleanData = function( elems ) {
	for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
		try {
			$( elem ).triggerHandler( "remove" );
		// http://bugs.jquery.com/ticket/8235
		} catch( e ) {}
	}
	_cleanData( elems );
};

$.widget = function( name, base, prototype ) {
	var fullName, existingConstructor, constructor, basePrototype,
		// proxiedPrototype allows the provided prototype to remain unmodified
		// so that it can be used as a mixin for multiple widgets (#8876)
		proxiedPrototype = {},
		namespace = name.split( "." )[ 0 ];

	name = name.split( "." )[ 1 ];
	fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	// create selector for plugin
	$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
		return !!$.data( elem, fullName );
	};

	$[ namespace ] = $[ namespace ] || {};
	existingConstructor = $[ namespace ][ name ];
	constructor = $[ namespace ][ name ] = function( options, element ) {
		// allow instantiation without "new" keyword
		if ( !this._createWidget ) {
			return new constructor( options, element );
		}

		// allow instantiation without initializing for simple inheritance
		// must use "new" keyword (the code above always passes args)
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};
	// extend with the existing constructor to carry over any static properties
	$.extend( constructor, existingConstructor, {
		version: prototype.version,
		// copy the object used to create the prototype in case we need to
		// redefine the widget later
		_proto: $.extend( {}, prototype ),
		// track widgets that inherit from this widget in case this widget is
		// redefined after a widget inherits from it
		_childConstructors: []
	});

	basePrototype = new base();
	// we need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
	basePrototype.options = $.widget.extend( {}, basePrototype.options );
	$.each( prototype, function( prop, value ) {
		if ( !$.isFunction( value ) ) {
			proxiedPrototype[ prop ] = value;
			return;
		}
		proxiedPrototype[ prop ] = (function() {
			var _super = function() {
					return base.prototype[ prop ].apply( this, arguments );
				},
				_superApply = function( args ) {
					return base.prototype[ prop ].apply( this, args );
				};
			return function() {
				var __super = this._super,
					__superApply = this._superApply,
					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
	}, 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 );
};

$.widget.extend = function( target ) {
	var input = slice.call( arguments, 1 ),
		inputIndex = 0,
		inputLength = input.length,
		key,
		value;
	for ( ; inputIndex < inputLength; inputIndex++ ) {
		for ( key in input[ inputIndex ] ) {
			value = input[ inputIndex ][ key ];
			if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
				// Clone objects
				if ( $.isPlainObject( value ) ) {
					target[ key ] = $.isPlainObject( target[ key ] ) ?
						$.widget.extend( {}, target[ key ], value ) :
						// Don't extend strings, arrays, etc. with objects
						$.widget.extend( {}, value );
				// Copy everything else by reference
				} else {
					target[ key ] = value;
				}
			}
		}
	}
	return target;
};

$.widget.bridge = function( name, object ) {
	var fullName = object.prototype.widgetFullName || name;
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string",
			args = slice.call( arguments, 1 ),
			returnValue = this;

		// allow multiple hashes to be passed on init
		options = !isMethodCall && args.length ?
			$.widget.extend.apply( null, [ options ].concat(args) ) :
			options;

		if ( isMethodCall ) {
			this.each(function() {
				var methodValue,
					instance = $.data( this, fullName );
				if ( !instance ) {
					return $.error( "cannot call methods on " + name + " prior to initialization; " +
						"attempted to call method '" + options + "'" );
				}
				if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
					return $.error( "no such method '" + options + "' for " + name + " widget instance" );
				}
				methodValue = instance[ options ].apply( instance, args );
				if ( methodValue !== instance && methodValue !== undefined ) {
					returnValue = methodValue && methodValue.jquery ?
						returnValue.pushStack( methodValue.get() ) :
						methodValue;
					return false;
				}
			});
		} else {
			this.each(function() {
				var instance = $.data( this, fullName );
				if ( instance ) {
					instance.option( options || {} )._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: {
		disabled: false,

		// callbacks
		create: null
	},
	_createWidget: function( options, element ) {
		element = $( element || this.defaultElement || this )[ 0 ];
		this.element = $( element );
		this.uuid = uuid++;
		this.eventNamespace = "." + this.widgetName + this.uuid;
		this.options = $.widget.extend( {},
			this.options,
			this._getCreateOptions(),
			options );

		this.bindings = $();
		this.hoverable = $();
		this.focusable = $();

		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._create();
		this._trigger( "create", null, this._getCreateEventData() );
		this._init();
	},
	_getCreateOptions: $.noop,
	_getCreateEventData: $.noop,
	_create: $.noop,
	_init: $.noop,

	destroy: function() {
		this._destroy();
		// we can probably remove the unbind calls in 2.0
		// all event bindings should go through this._on()
		this.element
			.unbind( this.eventNamespace )
			// 1.9 BC for #7810
			// TODO remove dual storage
			.removeData( this.widgetName )
			.removeData( this.widgetFullName )
			// support: jquery <1.6.3
			// http://bugs.jquery.com/ticket/9413
			.removeData( $.camelCase( this.widgetFullName ) );
		this.widget()
			.unbind( this.eventNamespace )
			.removeAttr( "aria-disabled" )
			.removeClass(
				this.widgetFullName + "-disabled " +
				"ui-state-disabled" );

		// clean up events and states
		this.bindings.unbind( this.eventNamespace );
		this.hoverable.removeClass( "ui-state-hover" );
		this.focusable.removeClass( "ui-state-focus" );
	},
	_destroy: $.noop,

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key,
			parts,
			curOption,
			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 ( value === undefined ) {
					return curOption[ key ] === undefined ? null : curOption[ key ];
				}
				curOption[ key ] = value;
			} else {
				if ( value === undefined ) {
					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 ) {
		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this.widget()
				.toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
				.attr( "aria-disabled", value );
			this.hoverable.removeClass( "ui-state-hover" );
			this.focusable.removeClass( "ui-state-focus" );
		}

		return this;
	},

	enable: function() {
		return this._setOption( "disabled", false );
	},
	disable: function() {
		return this._setOption( "disabled", true );
	},

	_on: function( suppressDisabledCheck, element, handlers ) {
		var delegateElement,
			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 {
			// accept selectors, DOM elements
			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*(.*)$/ ),
				eventName = match[1] + instance.eventNamespace,
				selector = match[2];
			if ( selector ) {
				delegateElement.delegate( selector, eventName, handlerProxy );
			} else {
				element.bind( eventName, handlerProxy );
			}
		});
	},

	_off: function( element, eventName ) {
		eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
		element.unbind( eventName ).undelegate( eventName );
	},

	_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 ) {
				$( event.currentTarget ).addClass( "ui-state-hover" );
			},
			mouseleave: function( event ) {
				$( event.currentTarget ).removeClass( "ui-state-hover" );
			}
		});
	},

	_focusable: function( element ) {
		this.focusable = this.focusable.add( element );
		this._on( element, {
			focusin: function( event ) {
				$( event.currentTarget ).addClass( "ui-state-focus" );
			},
			focusout: function( event ) {
				$( event.currentTarget ).removeClass( "ui-state-focus" );
			}
		});
	},

	_trigger: function( type, event, data ) {
		var prop, orig,
			callback = this.options[ type ];

		data = data || {};
		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();
		// the original event may come from any element
		// so we need to reset the target on the new event
		event.target = this.element[ 0 ];

		// copy original event properties over to the new event
		orig = event.originalEvent;
		if ( orig ) {
			for ( prop in orig ) {
				if ( !( prop in event ) ) {
					event[ prop ] = orig[ prop ];
				}
			}
		}

		this.element.trigger( event, data );
		return !( $.isFunction( callback ) &&
			callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
			event.isDefaultPrevented() );
	}
};

$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
	$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
		if ( typeof options === "string" ) {
			options = { effect: options };
		}
		var hasOptions,
			effectName = !options ?
				method :
				options === true || typeof options === "number" ?
					defaultEffect :
					options.effect || defaultEffect;
		options = options || {};
		if ( typeof options === "number" ) {
			options = { duration: options };
		}
		hasOptions = !$.isEmptyObject( options );
		options.complete = callback;
		if ( options.delay ) {
			element.delay( options.delay );
		}
		if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
			element[ method ]( options );
		} else if ( effectName !== method && element[ effectName ] ) {
			element[ effectName ]( options.duration, options.easing, callback );
		} else {
			element.queue(function( next ) {
				$( this )[ method ]();
				if ( callback ) {
					callback.call( element[ 0 ] );
				}
				next();
			});
		}
	};
});

})( jQuery );
(function( $, undefined ) {

var mouseHandled = false;
$( document ).mouseup( function() {
	mouseHandled = false;
});

$.widget("ui.mouse", {
	version: "1.10.3",
	options: {
		cancel: "input,textarea,button,select,option",
		distance: 1,
		delay: 0
	},
	_mouseInit: function() {
		var that = this;

		this.element
			.bind("mousedown."+this.widgetName, function(event) {
				return that._mouseDown(event);
			})
			.bind("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.unbind("."+this.widgetName);
		if ( this._mouseMoveDelegate ) {
			$(document)
				.unbind("mousemove."+this.widgetName, this._mouseMoveDelegate)
				.unbind("mouseup."+this.widgetName, this._mouseUpDelegate);
		}
	},

	_mouseDown: function(event) {
		// don't let more than one widget handle mouseStart
		if( mouseHandled ) { return; }

		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var that = this,
			btnIsLeft = (event.which === 1),
			// event.target.nodeName works around a bug in IE 8 with
			// disabled inputs (#7620)
			elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				that.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// Click event may never have fired (Gecko & Opera)
		if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) {
			$.removeData(event.target, this.widgetName + ".preventClickEvent");
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return that._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return that._mouseUp(event);
		};
		$(document)
			.bind("mousemove."+this.widgetName, this._mouseMoveDelegate)
			.bind("mouseup."+this.widgetName, this._mouseUpDelegate);

		event.preventDefault();

		mouseHandled = true;
		return true;
	},

	_mouseMove: function(event) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) {
			return this._mouseUp(event);
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		$(document)
			.unbind("mousemove."+this.widgetName, this._mouseMoveDelegate)
			.unbind("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);
		}

		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(/* event */) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(/* event */) {},
	_mouseDrag: function(/* event */) {},
	_mouseStop: function(/* event */) {},
	_mouseCapture: function(/* event */) { return true; }
});

})(jQuery);
(function( $, undefined ) {

$.ui = $.ui || {};

var cachedScrollbarWidth,
	max = Math.max,
	abs = Math.abs,
	round = Math.round,
	rhorizontal = /left|center|right/,
	rvertical = /top|center|bottom/,
	roffset = /[\+\-]\d+(\.[\d]+)?%?/,
	rposition = /^\w+/,
	rpercent = /%$/,
	_position = $.fn.position;

function getOffsets( offsets, width, height ) {
	return [
		parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
		parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
	];
}

function parseCss( element, property ) {
	return parseInt( $.css( element, property ), 10 ) || 0;
}

function getDimensions( elem ) {
	var raw = elem[0];
	if ( raw.nodeType === 9 ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: 0, left: 0 }
		};
	}
	if ( $.isWindow( raw ) ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
		};
	}
	if ( raw.preventDefault ) {
		return {
			width: 0,
			height: 0,
			offset: { top: raw.pageY, left: raw.pageX }
		};
	}
	return {
		width: elem.outerWidth(),
		height: elem.outerHeight(),
		offset: elem.offset()
	};
}

$.position = {
	scrollbarWidth: function() {
		if ( cachedScrollbarWidth !== undefined ) {
			return cachedScrollbarWidth;
		}
		var w1, w2,
			div = $( "<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ),
			innerDiv = div.children()[0];

		$( "body" ).append( div );
		w1 = innerDiv.offsetWidth;
		div.css( "overflow", "scroll" );

		w2 = innerDiv.offsetWidth;

		if ( w1 === w2 ) {
			w2 = div[0].clientWidth;
		}

		div.remove();

		return (cachedScrollbarWidth = w1 - w2);
	},
	getScrollInfo: function( within ) {
		var overflowX = within.isWindow ? "" : within.element.css( "overflow-x" ),
			overflowY = within.isWindow ? "" : within.element.css( "overflow-y" ),
			hasOverflowX = overflowX === "scroll" ||
				( overflowX === "auto" && within.width < within.element[0].scrollWidth ),
			hasOverflowY = overflowY === "scroll" ||
				( overflowY === "auto" && within.height < within.element[0].scrollHeight );
		return {
			width: hasOverflowY ? $.position.scrollbarWidth() : 0,
			height: hasOverflowX ? $.position.scrollbarWidth() : 0
		};
	},
	getWithinInfo: function( element ) {
		var withinElement = $( element || window ),
			isWindow = $.isWindow( withinElement[0] );
		return {
			element: withinElement,
			isWindow: isWindow,
			offset: withinElement.offset() || { left: 0, top: 0 },
			scrollLeft: withinElement.scrollLeft(),
			scrollTop: withinElement.scrollTop(),
			width: isWindow ? withinElement.width() : withinElement.outerWidth(),
			height: isWindow ? withinElement.height() : withinElement.outerHeight()
		};
	}
};

$.fn.position = function( options ) {
	if ( !options || !options.of ) {
		return _position.apply( this, arguments );
	}

	// make a copy, we don't want to modify arguments
	options = $.extend( {}, options );

	var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
		target = $( options.of ),
		within = $.position.getWithinInfo( options.within ),
		scrollInfo = $.position.getScrollInfo( within ),
		collision = ( options.collision || "flip" ).split( " " ),
		offsets = {};

	dimensions = getDimensions( target );
	if ( target[0].preventDefault ) {
		// force left top to allow flipping
		options.at = "left top";
	}
	targetWidth = dimensions.width;
	targetHeight = dimensions.height;
	targetOffset = dimensions.offset;
	// clone to reuse original targetOffset later
	basePosition = $.extend( {}, targetOffset );

	// force my and at to have valid horizontal and vertical positions
	// if a value is missing or invalid, it will be converted to center
	$.each( [ "my", "at" ], function() {
		var pos = ( options[ this ] || "" ).split( " " ),
			horizontalOffset,
			verticalOffset;

		if ( pos.length === 1) {
			pos = rhorizontal.test( pos[ 0 ] ) ?
				pos.concat( [ "center" ] ) :
				rvertical.test( pos[ 0 ] ) ?
					[ "center" ].concat( pos ) :
					[ "center", "center" ];
		}
		pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
		pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";

		// calculate offsets
		horizontalOffset = roffset.exec( pos[ 0 ] );
		verticalOffset = roffset.exec( pos[ 1 ] );
		offsets[ this ] = [
			horizontalOffset ? horizontalOffset[ 0 ] : 0,
			verticalOffset ? verticalOffset[ 0 ] : 0
		];

		// reduce to just the positions without the offsets
		options[ this ] = [
			rposition.exec( pos[ 0 ] )[ 0 ],
			rposition.exec( pos[ 1 ] )[ 0 ]
		];
	});

	// normalize collision option
	if ( collision.length === 1 ) {
		collision[ 1 ] = collision[ 0 ];
	}

	if ( options.at[ 0 ] === "right" ) {
		basePosition.left += targetWidth;
	} else if ( options.at[ 0 ] === "center" ) {
		basePosition.left += targetWidth / 2;
	}

	if ( options.at[ 1 ] === "bottom" ) {
		basePosition.top += targetHeight;
	} else if ( options.at[ 1 ] === "center" ) {
		basePosition.top += targetHeight / 2;
	}

	atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
	basePosition.left += atOffset[ 0 ];
	basePosition.top += atOffset[ 1 ];

	return this.each(function() {
		var collisionPosition, using,
			elem = $( this ),
			elemWidth = elem.outerWidth(),
			elemHeight = elem.outerHeight(),
			marginLeft = parseCss( this, "marginLeft" ),
			marginTop = parseCss( this, "marginTop" ),
			collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width,
			collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height,
			position = $.extend( {}, basePosition ),
			myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );

		if ( options.my[ 0 ] === "right" ) {
			position.left -= elemWidth;
		} else if ( options.my[ 0 ] === "center" ) {
			position.left -= elemWidth / 2;
		}

		if ( options.my[ 1 ] === "bottom" ) {
			position.top -= elemHeight;
		} else if ( options.my[ 1 ] === "center" ) {
			position.top -= elemHeight / 2;
		}

		position.left += myOffset[ 0 ];
		position.top += myOffset[ 1 ];

		// if the browser doesn't support fractions, then round for consistent results
		if ( !$.support.offsetFractions ) {
			position.left = round( position.left );
			position.top = round( position.top );
		}

		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 ( ( position.top + myOffset + atOffset + offset) > overTop && ( 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 ( ( position.top + myOffset + atOffset + offset) > overBottom && ( 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 );
		}
	}
};

// fraction support test
(function () {
	var testElement, testElementParent, testElementStyle, offsetLeft, i,
		body = document.getElementsByTagName( "body" )[ 0 ],
		div = document.createElement( "div" );

	//Create a "fake body" for testing based on method used in jQuery.support
	testElement = document.createElement( body ? "div" : "body" );
	testElementStyle = {
		visibility: "hidden",
		width: 0,
		height: 0,
		border: 0,
		margin: 0,
		background: "none"
	};
	if ( body ) {
		$.extend( testElementStyle, {
			position: "absolute",
			left: "-1000px",
			top: "-1000px"
		});
	}
	for ( i in testElementStyle ) {
		testElement.style[ i ] = testElementStyle[ i ];
	}
	testElement.appendChild( div );
	testElementParent = body || document.documentElement;
	testElementParent.insertBefore( testElement, testElementParent.firstChild );

	div.style.cssText = "position: absolute; left: 10.7432222px;";

	offsetLeft = $( div ).offset().left;
	$.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11;

	testElement.innerHTML = "";
	testElementParent.removeChild( testElement );
})();

}( jQuery ) );
(function( $, undefined ) {

$.widget("ui.draggable", $.ui.mouse, {
	version: "1.10.3",
	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" && !(/^(?:r|a|f)/).test(this.element.css("position"))) {
			this.element[0].style.position = "relative";
		}
		if (this.options.addClasses){
			this.element.addClass("ui-draggable");
		}
		if (this.options.disabled){
			this.element.addClass("ui-draggable-disabled");
		}

		this._mouseInit();

	},

	_destroy: function() {
		this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" );
		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;
		}

		$(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() {
			$("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>")
			.css({
				width: this.offsetWidth+"px", height: this.offsetHeight+"px",
				position: "absolute", opacity: "0.001", zIndex: 1000
			})
			.css($(this).offset())
			.appendTo("body");
		});

		return true;

	},

	_mouseStart: function(event) {

		var o = this.options;

		//Create and append the visible helper
		this.helper = this._createHelper(event);

		this.helper.addClass("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();
		this.offsetParent = this.helper.offsetParent();
		this.offsetParentCssPosition = this.offsetParent.css( "position" );

		//The element's absolute position on the page minus margins
		this.offset = this.positionAbs = this.element.offset();
		this.offset = {
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};

		//Reset scroll cache
		this.offset.scroll = false;

		$.extend(this.offset, {
			click: { //Where the click happened, relative to the element
				left: event.pageX - this.offset.left,
				top: event.pageY - this.offset.top
			},
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
		});

		//Generate the original position
		this.originalPosition = this.position = this._generatePosition(event);
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
		(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);
		}


		this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position

		//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;
	},

	_mouseDrag: function(event, noPropagation) {
		// reset any necessary cached properties (see #5009)
		if ( this.offsetParentCssPosition === "fixed" ) {
			this.offset.parent = this._getParentOffset();
		}

		//Compute the helpers position
		this.position = this._generatePosition(event);
		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({});
				return false;
			}
			this.position = ui.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";
		}
		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 the original element is no longer in the DOM don't bother to continue (see #8269)
		if ( this.options.helper === "original" && !$.contains( this.element[ 0 ].ownerDocument, this.element[ 0 ] ) ) {
			return false;
		}

		if((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && 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) {
		//Remove frame helpers
		$("div.ui-draggable-iframeFix").each(function() {
			this.parentNode.removeChild(this);
		});

		//If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003)
		if( $.ui.ddmanager ) {
			$.ui.ddmanager.dragStop(this, event);
		}

		return $.ui.mouse.prototype._mouseUp.call(this, event);
	},

	cancel: function() {

		if(this.helper.is(".ui-draggable-dragging")) {
			this._mouseUp({});
		} else {
			this._clear();
		}

		return this;

	},

	_getHandle: function(event) {
		return this.options.handle ?
			!!$( event.target ).closest( this.element.find( this.options.handle ) ).length :
			true;
	},

	_createHelper: function(event) {

		var o = this.options,
			helper = $.isFunction(o.helper) ? $(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));
		}

		if(helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) {
			helper.css("position", "absolute");
		}

		return helper;

	},

	_adjustOffsetFromHelper: function(obj) {
		if (typeof obj === "string") {
			obj = obj.split(" ");
		}
		if ($.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
		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] !== document && $.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
		//Ugly IE fix
		if((this.offsetParent[0] === document.body) ||
			(this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
			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.element.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.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 over, c, ce,
			o = this.options;

		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;
		}

		over = c.css( "overflow" ) !== "hidden";

		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 ) ,
			( over ? 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,
			( over ? 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.relative_container = c;
	},

	_convertPositionTo: function(d, pos) {

		if(!pos) {
			pos = this.position;
		}

		var mod = d === "absolute" ? 1 : -1,
			scroll = this.cssPosition === "absolute" && !( this.scrollParent[ 0 ] !== document && $.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ? this.offsetParent : this.scrollParent;

		//Cache the scroll
		if (!this.offset.scroll) {
			this.offset.scroll = {top : scroll.scrollTop(), left : scroll.scrollLeft()};
		}

		return {
			top: (
				pos.top	+																// The absolute mouse position
				this.offset.relative.top * mod +										// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.top * mod -										// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : this.offset.scroll.top ) * mod )
			),
			left: (
				pos.left +																// The absolute mouse position
				this.offset.relative.left * mod +										// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.left * mod	-										// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : this.offset.scroll.left ) * mod )
			)
		};

	},

	_generatePosition: function(event) {

		var containment, co, top, left,
			o = this.options,
			scroll = this.cssPosition === "absolute" && !( this.scrollParent[ 0 ] !== document && $.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ? this.offsetParent : this.scrollParent,
			pageX = event.pageX,
			pageY = event.pageY;

		//Cache the scroll
		if (!this.offset.scroll) {
			this.offset.scroll = {top : scroll.scrollTop(), left : scroll.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 ( this.originalPosition ) {
			if ( this.containment ) {
				if ( this.relative_container ){
					co = this.relative_container.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;
			}

		}

		return {
			top: (
				pageY -																	// The absolute mouse position
				this.offset.click.top	-												// Click offset (relative to the element)
				this.offset.relative.top -												// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.top +												// The offsetParent's offset without borders (offset + border)
				( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : this.offset.scroll.top )
			),
			left: (
				pageX -																	// The absolute mouse position
				this.offset.click.left -												// Click offset (relative to the element)
				this.offset.relative.left -												// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.left +												// The offsetParent's offset without borders (offset + border)
				( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : this.offset.scroll.left )
			)
		};

	},

	_clear: function() {
		this.helper.removeClass("ui-draggable-dragging");
		if(this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) {
			this.helper.remove();
		}
		this.helper = null;
		this.cancelHelperRemoval = false;
	},

	// From now on bulk stuff - mainly helpers

	_trigger: function(type, event, ui) {
		ui = ui || this._uiHash();
		$.ui.plugin.call(this, type, [event, ui]);
		//The absolute position has to be recalculated after plugins
		if(type === "drag") {
			this.positionAbs = this._convertPositionTo("absolute");
		}
		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) {

		var inst = $(this).data("ui-draggable"), o = inst.options,
			uiSortable = $.extend({}, ui, { item: inst.element });
		inst.sortables = [];
		$(o.connectToSortable).each(function() {
			var sortable = $.data(this, "ui-sortable");
			if (sortable && !sortable.options.disabled) {
				inst.sortables.push({
					instance: sortable,
					shouldRevert: sortable.options.revert
				});
				sortable.refreshPositions();	// Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page).
				sortable._trigger("activate", event, uiSortable);
			}
		});

	},
	stop: function(event, ui) {

		//If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
		var inst = $(this).data("ui-draggable"),
			uiSortable = $.extend({}, ui, { item: inst.element });

		$.each(inst.sortables, function() {
			if(this.instance.isOver) {

				this.instance.isOver = 0;

				inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
				this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)

				//The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: "valid/invalid"
				if(this.shouldRevert) {
					this.instance.options.revert = this.shouldRevert;
				}

				//Trigger the stop of the sortable
				this.instance._mouseStop(event);

				this.instance.options.helper = this.instance.options._helper;

				//If the helper has been the original item, restore properties in the sortable
				if(inst.options.helper === "original") {
					this.instance.currentItem.css({ top: "auto", left: "auto" });
				}

			} else {
				this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
				this.instance._trigger("deactivate", event, uiSortable);
			}

		});

	},
	drag: function(event, ui) {

		var inst = $(this).data("ui-draggable"), that = this;

		$.each(inst.sortables, function() {

			var innermostIntersecting = false,
				thisSortable = this;

			//Copy over some variables to allow calling the sortable's native _intersectsWith
			this.instance.positionAbs = inst.positionAbs;
			this.instance.helperProportions = inst.helperProportions;
			this.instance.offset.click = inst.offset.click;

			if(this.instance._intersectsWith(this.instance.containerCache)) {
				innermostIntersecting = true;
				$.each(inst.sortables, function () {
					this.instance.positionAbs = inst.positionAbs;
					this.instance.helperProportions = inst.helperProportions;
					this.instance.offset.click = inst.offset.click;
					if (this !== thisSortable &&
						this.instance._intersectsWith(this.instance.containerCache) &&
						$.contains(thisSortable.instance.element[0], this.instance.element[0])
					) {
						innermostIntersecting = false;
					}
					return innermostIntersecting;
				});
			}


			if(innermostIntersecting) {
				//If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
				if(!this.instance.isOver) {

					this.instance.isOver = 1;
					//Now we fake the start of dragging for the sortable instance,
					//by cloning the list group item, appending it to the sortable and using it as inst.currentItem
					//We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
					this.instance.currentItem = $(that).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item", true);
					this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
					this.instance.options.helper = function() { return ui.helper[0]; };

					event.target = this.instance.currentItem[0];
					this.instance._mouseCapture(event, true);
					this.instance._mouseStart(event, true, true);

					//Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
					this.instance.offset.click.top = inst.offset.click.top;
					this.instance.offset.click.left = inst.offset.click.left;
					this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
					this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;

					inst._trigger("toSortable", event);
					inst.dropped = this.instance.element; //draggable revert needs that
					//hack so receive/update callbacks work (mostly)
					inst.currentItem = inst.element;
					this.instance.fromOutside = inst;

				}

				//Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
				if(this.instance.currentItem) {
					this.instance._mouseDrag(event);
				}

			} 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(this.instance.isOver) {

					this.instance.isOver = 0;
					this.instance.cancelHelperRemoval = true;

					//Prevent reverting on this forced stop
					this.instance.options.revert = false;

					// The out event needs to be triggered independently
					this.instance._trigger("out", event, this.instance._uiHash(this.instance));

					this.instance._mouseStop(event, true);
					this.instance.options.helper = this.instance.options._helper;

					//Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
					this.instance.currentItem.remove();
					if(this.instance.placeholder) {
						this.instance.placeholder.remove();
					}

					inst._trigger("fromSortable", event);
					inst.dropped = false; //draggable revert needs that
				}

			}

		});

	}
});

$.ui.plugin.add("draggable", "cursor", {
	start: function() {
		var t = $("body"), o = $(this).data("ui-draggable").options;
		if (t.css("cursor")) {
			o._cursor = t.css("cursor");
		}
		t.css("cursor", o.cursor);
	},
	stop: function() {
		var o = $(this).data("ui-draggable").options;
		if (o._cursor) {
			$("body").css("cursor", o._cursor);
		}
	}
});

$.ui.plugin.add("draggable", "opacity", {
	start: function(event, ui) {
		var t = $(ui.helper), o = $(this).data("ui-draggable").options;
		if(t.css("opacity")) {
			o._opacity = t.css("opacity");
		}
		t.css("opacity", o.opacity);
	},
	stop: function(event, ui) {
		var o = $(this).data("ui-draggable").options;
		if(o._opacity) {
			$(ui.helper).css("opacity", o._opacity);
		}
	}
});

$.ui.plugin.add("draggable", "scroll", {
	start: function() {
		var i = $(this).data("ui-draggable");
		if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") {
			i.overflowOffset = i.scrollParent.offset();
		}
	},
	drag: function( event ) {

		var i = $(this).data("ui-draggable"), o = i.options, scrolled = false;

		if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") {

			if(!o.axis || o.axis !== "x") {
				if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
					i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
				} else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity) {
					i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;
				}
			}

			if(!o.axis || o.axis !== "y") {
				if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
					i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
				} else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity) {
					i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].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() {

		var i = $(this).data("ui-draggable"),
			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) {

		var ts, bs, ls, rs, l, r, t, b, i, first,
			inst = $(this).data("ui-draggable"),
			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;
			r = l + inst.snapElements[i].width;
			t = inst.snapElements[i].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) {
					(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 - inst.margins.top;
				}
				if(bs) {
					ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
				}
				if(ls) {
					ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
				}
				if(rs) {
					ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.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 - inst.margins.top;
				}
				if(bs) {
					ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
				}
				if(ls) {
					ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left;
				}
				if(rs) {
					ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left;
				}
			}

			if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) {
				(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() {
		var min,
			o = this.data("ui-draggable").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) {
		var t = $(ui.helper), o = $(this).data("ui-draggable").options;
		if(t.css("zIndex")) {
			o._zIndex = t.css("zIndex");
		}
		t.css("zIndex", o.zIndex);
	},
	stop: function(event, ui) {
		var o = $(this).data("ui-draggable").options;
		if(o._zIndex) {
			$(ui.helper).css("zIndex", o._zIndex);
		}
	}
});

})(jQuery);
(function( $, undefined ) {

function isOverAxis( x, reference, size ) {
	return ( x > reference ) && ( x < ( reference + size ) );
}

$.widget("ui.droppable", {
	version: "1.10.3",
	widgetEventPrefix: "drop",
	options: {
		accept: "*",
		activeClass: false,
		addClasses: true,
		greedy: false,
		hoverClass: false,
		scope: "default",
		tolerance: "intersect",

		// callbacks
		activate: null,
		deactivate: null,
		drop: null,
		out: null,
		over: null
	},
	_create: function() {

		var o = this.options,
			accept = o.accept;

		this.isover = false;
		this.isout = true;

		this.accept = $.isFunction(accept) ? accept : function(d) {
			return d.is(accept);
		};

		//Store the droppable's proportions
		this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight };

		// Add the reference and positions to the manager
		$.ui.ddmanager.droppables[o.scope] = $.ui.ddmanager.droppables[o.scope] || [];
		$.ui.ddmanager.droppables[o.scope].push(this);

		(o.addClasses && this.element.addClass("ui-droppable"));

	},

	_destroy: function() {
		var i = 0,
			drop = $.ui.ddmanager.droppables[this.options.scope];

		for ( ; i < drop.length; i++ ) {
			if ( drop[i] === this ) {
				drop.splice(i, 1);
			}
		}

		this.element.removeClass("ui-droppable ui-droppable-disabled");
	},

	_setOption: function(key, value) {

		if(key === "accept") {
			this.accept = $.isFunction(value) ? value : function(d) {
				return d.is(value);
			};
		}
		$.Widget.prototype._setOption.apply(this, arguments);
	},

	_activate: function(event) {
		var draggable = $.ui.ddmanager.current;
		if(this.options.activeClass) {
			this.element.addClass(this.options.activeClass);
		}
		if(draggable){
			this._trigger("activate", event, this.ui(draggable));
		}
	},

	_deactivate: function(event) {
		var draggable = $.ui.ddmanager.current;
		if(this.options.activeClass) {
			this.element.removeClass(this.options.activeClass);
		}
		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))) {
			if(this.options.hoverClass) {
				this.element.addClass(this.options.hoverClass);
			}
			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))) {
			if(this.options.hoverClass) {
				this.element.removeClass(this.options.hoverClass);
			}
			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 = $.data(this, "ui-droppable");
			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)
			) { childrenIntersection = true; return false; }
		});
		if(childrenIntersection) {
			return false;
		}

		if(this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
			if(this.options.activeClass) {
				this.element.removeClass(this.options.activeClass);
			}
			if(this.options.hoverClass) {
				this.element.removeClass(this.options.hoverClass);
			}
			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
		};
	}

});

$.ui.intersect = function(draggable, droppable, toleranceMode) {

	if (!droppable.offset) {
		return false;
	}

	var draggableLeft, draggableTop,
		x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width,
		y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height,
		l = droppable.offset.left, r = l + droppable.proportions.width,
		t = droppable.offset.top, 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":
			draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left);
			draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top);
			return isOverAxis( draggableTop, t, droppable.proportions.height ) && isOverAxis( draggableLeft, 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)) {
				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" ).bind( "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),
				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 $.data(this, "ui-droppable").options.scope === scope;
				});

				if (parent.length) {
					parentInstance = $.data(parent[0], "ui-droppable");
					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" ).unbind( "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 );
		}
	}
};

})(jQuery);
(function( $, undefined ) {

function num(v) {
	return parseInt(v, 10) || 0;
}

function isNumber(value) {
	return !isNaN(parseInt(value, 10));
}

$.widget("ui.resizable", $.ui.mouse, {
	version: "1.10.3",
	widgetEventPrefix: "resize",
	options: {
		alsoResize: false,
		animate: false,
		animateDuration: "slow",
		animateEasing: "swing",
		aspectRatio: false,
		autoHide: false,
		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
	},
	_create: function() {

		var n, i, handle, axis, hname,
			that = this,
			o = this.options;
		this.element.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)) {

			//Create a wrapper element and set the wrapper to the new current internal element
			this.element.wrap(
				$("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({
					position: this.element.css("position"),
					width: this.element.outerWidth(),
					height: this.element.outerHeight(),
					top: this.element.css("top"),
					left: this.element.css("left")
				})
			);

			//Overwrite the original this.element
			this.element = this.element.parent().data(
				"ui-resizable", this.element.data("ui-resizable")
			);

			this.elementIsWrapper = true;

			//Move margins to the wrapper
			this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") });
			this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0});

			//Prevent Safari textarea resize
			this.originalResizeStyle = this.originalElement.css("resize");
			this.originalElement.css("resize", "none");

			//Push the actual element to our proportionallyResize internal array
			this._proportionallyResizeElements.push(this.originalElement.css({ position: "static", zoom: 1, display: "block" }));

			// avoid IE jump (hard set the margin)
			this.originalElement.css({ margin: this.originalElement.css("margin") });

			// fix handlers offset
			this._proportionallyResize();

		}

		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" });
		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 = $.trim(n[i]);
				hname = "ui-resizable-"+handle;
				axis = $("<div class='ui-resizable-handle " + hname + "'></div>");

				// Apply zIndex to all handles - see #7960
				axis.css({ zIndex: o.zIndex });

				//TODO : What's going on here?
				if ("se" === handle) {
					axis.addClass("ui-icon ui-icon-gripsmall-diagonal-se");
				}

				//Insert into internal handles object and append to element
				this.handles[handle] = ".ui-resizable-"+handle;
				this.element.append(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.handles[i], this.element).show();
				}

				//Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls)
				if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) {

					axis = $(this.handles[i], this.element);

					//Checking the correct pad and border
					padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth();

					//The padding type i have to apply...
					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();

				}

				//TODO: What's that good for? There's not anything to be executed left
				if(!$(this.handles[i]).length) {
					continue;
				}
			}
		};

		//TODO: make renderAxis a prototype function
		this._renderAxis(this.element);

		this._handles = $(".ui-resizable-handle", this.element)
			.disableSelection();

		//Matching axis name
		this._handles.mouseover(function() {
			if (!that.resizing) {
				if (this.className) {
					axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
				}
				//Axis, default = se
				that.axis = axis && axis[1] ? axis[1] : "se";
			}
		});

		//If we want to auto hide the elements
		if (o.autoHide) {
			this._handles.hide();
			$(this.element)
				.addClass("ui-resizable-autohide")
				.mouseenter(function() {
					if (o.disabled) {
						return;
					}
					$(this).removeClass("ui-resizable-autohide");
					that._handles.show();
				})
				.mouseleave(function(){
					if (o.disabled) {
						return;
					}
					if (!that.resizing) {
						$(this).addClass("ui-resizable-autohide");
						that._handles.hide();
					}
				});
		}

		//Initialize the mouse interaction
		this._mouseInit();

	},

	_destroy: function() {

		this._mouseDestroy();

		var wrapper,
			_destroy = function(exp) {
				$(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing")
					.removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove();
			};

		//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;
	},

	_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,
			o = this.options,
			iniPos = this.element.position(),
			el = this.element;

		this.resizing = true;

		// bugfix for http://dev.jquery.com/ticket/1749
		if ( (/absolute/).test( el.css("position") ) ) {
			el.css({ position: "absolute", top: el.css("top"), left: el.css("left") });
		} else if (el.is(".ui-draggable")) {
			el.css({ position: "absolute", top: iniPos.top, left: iniPos.left });
		}

		this._renderProxy();

		curleft = num(this.helper.css("left"));
		curtop = num(this.helper.css("top"));

		if (o.containment) {
			curleft += $(o.containment).scrollLeft() || 0;
			curtop += $(o.containment).scrollTop() || 0;
		}

		//Store needed variables
		this.offset = this.helper.offset();
		this.position = { left: curleft, top: curtop };
		this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
		this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
		this.originalPosition = { left: curleft, top: curtop };
		this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() };
		this.originalMousePosition = { left: event.pageX, top: event.pageY };

		//Aspect Ratio
		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);

		el.addClass("ui-resizable-resizing");
		this._propagate("start", event);
		return true;
	},

	_mouseDrag: function(event) {

		//Increase performance, avoid regex
		var data,
			el = this.helper, props = {},
			smp = this.originalMousePosition,
			a = this.axis,
			prevTop = this.position.top,
			prevLeft = this.position.left,
			prevWidth = this.size.width,
			prevHeight = this.size.height,
			dx = (event.pageX-smp.left)||0,
			dy = (event.pageY-smp.top)||0,
			trigger = this._change[a];

		if (!trigger) {
			return false;
		}

		// Calculate the attrs that will be change
		data = trigger.apply(this, [event, dx, dy]);

		// Put this in the mouseDrag handler since the user can start pressing shift while resizing
		this._updateVirtualBoundaries(event.shiftKey);
		if (this._aspectRatio || event.shiftKey) {
			data = this._updateRatio(data, event);
		}

		data = this._respectSize(data, event);

		this._updateCache(data);

		// plugins callbacks need to be called first
		this._propagate("resize", event);

		if (this.position.top !== prevTop) {
			props.top = this.position.top + "px";
		}
		if (this.position.left !== prevLeft) {
			props.left = this.position.left + "px";
		}
		if (this.size.width !== prevWidth) {
			props.width = this.size.width + "px";
		}
		if (this.size.height !== prevHeight) {
			props.height = this.size.height + "px";
		}
		el.css(props);

		if (!this._helper && this._proportionallyResizeElements.length) {
			this._proportionallyResize();
		}

		// Call the user callback if the element was resized
		if ( ! $.isEmptyObject(props) ) {
			this._trigger("resize", event, this.ui());
		}

		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 && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height;
			soffsetw = ista ? 0 : that.sizeDiff.width;

			s = { width: (that.helper.width()  - soffsetw), height: (that.helper.height() - soffseth) };
			left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null;
			top = (parseInt(that.element.css("top"), 10) + (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.element.removeClass("ui-resizable-resizing");

		this._propagate("stop", event);

		if (this._helper) {
			this.helper.remove();
		}

		return false;

	},

	_updateVirtualBoundaries: function(forceAspectRatio) {
		var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b,
			o = this.options;

		b = {
			minWidth: isNumber(o.minWidth) ? o.minWidth : 0,
			maxWidth: isNumber(o.maxWidth) ? o.maxWidth : Infinity,
			minHeight: isNumber(o.minHeight) ? o.minHeight : 0,
			maxHeight: isNumber(o.maxHeight) ? o.maxHeight : Infinity
		};

		if(this._aspectRatio || forceAspectRatio) {
			// We want to create an enclosing box whose aspect ration is the requested one
			// First, compute the "projected" size for each dimension based on the aspect ratio and other dimension
			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 (isNumber(data.left)) {
			this.position.left = data.left;
		}
		if (isNumber(data.top)) {
			this.position.top = data.top;
		}
		if (isNumber(data.height)) {
			this.size.height = data.height;
		}
		if (isNumber(data.width)) {
			this.size.width = data.width;
		}
	},

	_updateRatio: function( data ) {

		var cpos = this.position,
			csize = this.size,
			a = this.axis;

		if (isNumber(data.height)) {
			data.width = (data.height * this.aspectRatio);
		} else if (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 = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height),
			isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height),
			dw = this.originalPosition.left + this.originalSize.width,
			dh = this.position.top + this.size.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;
	},

	_proportionallyResize: function() {

		if (!this._proportionallyResizeElements.length) {
			return;
		}

		var i, j, borders, paddings, prel,
			element = this.helper || this.element;

		for ( i=0; i < this._proportionallyResizeElements.length; i++) {

			prel = this._proportionallyResizeElements[i];

			if (!this.borderDif) {
				this.borderDif = [];
				borders = [prel.css("borderTopWidth"), prel.css("borderRightWidth"), prel.css("borderBottomWidth"), prel.css("borderLeftWidth")];
				paddings = [prel.css("paddingTop"), prel.css("paddingRight"), prel.css("paddingBottom"), prel.css("paddingLeft")];

				for ( j = 0; j < borders.length; j++ ) {
					this.borderDif[ j ] = ( parseInt( borders[ j ], 10 ) || 0 ) + ( parseInt( paddings[ j ], 10 ) || 0 );
				}
			}

			prel.css({
				height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0,
				width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0
			});

		}

	},

	_renderProxy: function() {

		var el = this.element, o = this.options;
		this.elementOffset = el.offset();

		if(this._helper) {

			this.helper = this.helper || $("<div style='overflow:hidden;'></div>");

			this.helper.addClass(this._helper).css({
				width: this.element.outerWidth() - 1,
				height: this.element.outerHeight() - 1,
				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()]);
		(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).data("ui-resizable"),
			o = that.options,
			pr = that._proportionallyResizeElements,
			ista = pr.length && (/textarea/i).test(pr[0].nodeName),
			soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height,
			soffsetw = ista ? 0 : that.sizeDiff.width,
			style = { width: (that.size.width - soffsetw), height: (that.size.height - soffseth) },
			left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null,
			top = (parseInt(that.element.css("top"), 10) + (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: parseInt(that.element.css("width"), 10),
						height: parseInt(that.element.css("height"), 10),
						top: parseInt(that.element.css("top"), 10),
						left: parseInt(that.element.css("left"), 10)
					};

					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).data("ui-resizable"),
			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
			};
		}

		// i'm a node, so compute top, left, right, bottom
		else {
			element = $(ce);
			p = [];
			$([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = 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 = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw );
			height = ($.ui.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).data("ui-resizable"),
			o = that.options,
			co = that.containerOffset, cp = that.position,
			pRatio = that._aspectRatio || event.shiftKey,
			cop = { top:0, left:0 }, ce = that.containerElement;

		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;
			}
			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;
			}
			that.position.top = that._helper ? co.top : 0;
		}

		that.offset.left = that.parentData.left+that.position.left;
		that.offset.top = that.parentData.top+that.position.top;

		woset = Math.abs( (that._helper ? that.offset.left - cop.left : (that.offset.left - cop.left)) + that.sizeDiff.width );
		hoset = Math.abs( (that._helper ? that.offset.top - cop.top : (that.offset.top - co.top)) + that.sizeDiff.height );

		isParent = that.containerElement.get(0) === that.element.parent().get(0);
		isOffsetRelative = /relative|absolute/.test(that.containerElement.css("position"));

		if(isParent && isOffsetRelative) {
			woset -= that.parentData.left;
		}

		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;
			}
		}

		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;
			}
		}
	},

	stop: function(){
		var that = $(this).data("ui-resizable"),
			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).data("ui-resizable"),
			o = that.options,
			_store = function (exp) {
				$(exp).each(function() {
					var el = $(this);
					el.data("ui-resizable-alsoresize", {
						width: parseInt(el.width(), 10), height: parseInt(el.height(), 10),
						left: parseInt(el.css("left"), 10), top: parseInt(el.css("top"), 10)
					});
				});
			};

		if (typeof(o.alsoResize) === "object" && !o.alsoResize.parentNode) {
			if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); }
			else { $.each(o.alsoResize, function (exp) { _store(exp); }); }
		}else{
			_store(o.alsoResize);
		}
	},

	resize: function (event, ui) {
		var that = $(this).data("ui-resizable"),
			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
			},

			_alsoResize = function (exp, c) {
				$(exp).each(function() {
					var el = $(this), start = $(this).data("ui-resizable-alsoresize"), style = {},
						css = c && c.length ? c : 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);
				});
			};

		if (typeof(o.alsoResize) === "object" && !o.alsoResize.nodeType) {
			$.each(o.alsoResize, function (exp, c) { _alsoResize(exp, c); });
		}else{
			_alsoResize(o.alsoResize);
		}
	},

	stop: function () {
		$(this).removeData("resizable-alsoresize");
	}
});

$.ui.plugin.add("resizable", "ghost", {

	start: function() {

		var that = $(this).data("ui-resizable"), o = that.options, 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 })
			.addClass("ui-resizable-ghost")
			.addClass(typeof o.ghost === "string" ? o.ghost : "");

		that.ghost.appendTo(that.helper);

	},

	resize: function(){
		var that = $(this).data("ui-resizable");
		if (that.ghost) {
			that.ghost.css({ position: "relative", height: that.size.height, width: that.size.width });
		}
	},

	stop: function() {
		var that = $(this).data("ui-resizable");
		if (that.ghost && that.helper) {
			that.helper.get(0).removeChild(that.ghost.get(0));
		}
	}

});

$.ui.plugin.add("resizable", "grid", {

	resize: function() {
		var that = $(this).data("ui-resizable"),
			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 = newWidth + gridX;
		}
		if (isMinHeight) {
			newHeight = newHeight + gridY;
		}
		if (isMaxWidth) {
			newWidth = newWidth - gridX;
		}
		if (isMaxHeight) {
			newHeight = 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 {
			that.size.width = newWidth;
			that.size.height = newHeight;
			that.position.top = op.top - oy;
			that.position.left = op.left - ox;
		}
	}

});

})(jQuery);
(function( $, undefined ) {

$.widget("ui.selectable", $.ui.mouse, {
	version: "1.10.3",
	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 selectees,
			that = this;

		this.element.addClass("ui-selectable");

		this.dragged = false;

		// cache selectee children based on filter
		this.refresh = function() {
			selectees = $(that.options.filter, that.element[0]);
			selectees.addClass("ui-selectee");
			selectees.each(function() {
				var $this = $(this),
					pos = $this.offset();
				$.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.selectees = selectees.addClass("ui-selectee");

		this._mouseInit();

		this.helper = $("<div class='ui-selectable-helper'></div>");
	},

	_destroy: function() {
		this.selectees
			.removeClass("ui-selectee")
			.removeData("selectable-item");
		this.element
			.removeClass("ui-selectable ui-selectable-disabled");
		this._mouseDestroy();
	},

	_mouseStart: function(event) {
		var that = this,
			options = this.options;

		this.opos = [event.pageX, event.pageY];

		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) {
				selectee.$element.removeClass("ui-selected");
				selectee.selected = false;
				selectee.$element.addClass("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");
				selectee.$element
					.removeClass(doSelect ? "ui-unselecting" : "ui-selected")
					.addClass(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;

			//prevent helper from being selected if appendTo: selectable
			if (!selectee || selectee.element === that.element[0]) {
				return;
			}

			if (options.tolerance === "touch") {
				hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) );
			} else if (options.tolerance === "fit") {
				hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2);
			}

			if (hit) {
				// SELECT
				if (selectee.selected) {
					selectee.$element.removeClass("ui-selected");
					selectee.selected = false;
				}
				if (selectee.unselecting) {
					selectee.$element.removeClass("ui-unselecting");
					selectee.unselecting = false;
				}
				if (!selectee.selecting) {
					selectee.$element.addClass("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) {
						selectee.$element.removeClass("ui-selecting");
						selectee.selecting = false;
						selectee.$element.addClass("ui-selected");
						selectee.selected = true;
					} else {
						selectee.$element.removeClass("ui-selecting");
						selectee.selecting = false;
						if (selectee.startselected) {
							selectee.$element.addClass("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) {
						selectee.$element.removeClass("ui-selected");
						selectee.selected = false;

						selectee.$element.addClass("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");
			selectee.$element.removeClass("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");
			selectee.$element.removeClass("ui-selecting").addClass("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);
(function( $, undefined ) {

/*jshint loopfunc: true */

function isOverAxis( x, reference, size ) {
	return ( x > reference ) && ( x < ( reference + size ) );
}

function isFloating(item) {
	return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display"));
}

$.widget("ui.sortable", $.ui.mouse, {
	version: "1.10.3",
	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
	},
	_create: function() {

		var o = this.options;
		this.containerCache = {};
		this.element.addClass("ui-sortable");

		//Get the items
		this.refresh();

		//Let's determine if the items are being displayed horizontally
		this.floating = this.items.length ? o.axis === "x" || isFloating(this.items[0].item) : false;

		//Let's determine the parent's offset
		this.offset = this.element.offset();

		//Initialize mouse events for interaction
		this._mouseInit();

		//We're ready to go
		this.ready = true;

	},

	_destroy: function() {
		this.element
			.removeClass("ui-sortable ui-sortable-disabled");
		this._mouseDestroy();

		for ( var i = this.items.length - 1; i >= 0; i-- ) {
			this.items[i].item.removeData(this.widgetName + "-item");
		}

		return this;
	},

	_setOption: function(key, value){
		if ( key === "disabled" ) {
			this.options[ key ] = value;

			this.widget().toggleClass( "ui-sortable-disabled", !!value );
		} else {
			// Don't call widget base _setOption for disable as it adds ui-state-disabled class
			$.Widget.prototype._setOption.apply(this, arguments);
		}
	},

	_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();

		//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();

		//Get the next scrolling parent
		this.scrollParent = this.helper.scrollParent();

		//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
			},
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
		});

		// Only after we got the 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");

		//Generate the original position
		this.originalPosition = this._generatePosition(event);
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
		(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();

		//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" );

			// support: IE
			this.storedCursor = body.css( "cursor" );
			body.css( "cursor", o.cursor );

			this.storedStylesheet = $( "<style>*{ cursor: "+o.cursor+" !important; }</style>" ).appendTo( body );
		}

		if(o.opacity) { // opacity option
			if (this.helper.css("opacity")) {
				this._storedOpacity = this.helper.css("opacity");
			}
			this.helper.css("opacity", o.opacity);
		}

		if(o.zIndex) { // zIndex option
			if (this.helper.css("zIndex")) {
				this._storedZIndex = this.helper.css("zIndex");
			}
			this.helper.css("zIndex", o.zIndex);
		}

		//Prepare scrolling
		if(this.scrollParent[0] !== document && 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.helper.addClass("ui-sortable-helper");
		this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
		return true;

	},

	_mouseDrag: function(event) {
		var i, item, itemElement, intersection,
			o = this.options,
			scrolled = false;

		//Compute the helpers position
		this.position = this._generatePosition(event);
		this.positionAbs = this._convertPositionTo("absolute");

		if (!this.lastPositionAbs) {
			this.lastPositionAbs = this.positionAbs;
		}

		//Do scrolling
		if(this.options.scroll) {
			if(this.scrollParent[0] !== document && 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 - $(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(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(this, event);
			}
		}

		//Regenerate the absolute position used for position checks
		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";
		}

		//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 form 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
			// beetween 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] === document.body ? 0 : this.offsetParent[0].scrollLeft);
			}
			if ( !axis || axis === "y" ) {
				animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === document.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({ target: null });

			if(this.options.helper === "original") {
				this.currentItem.css(this._storedCSS).removeClass("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 isOverElementHeight = (this.options.axis === "x") || isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
			isOverElementWidth = (this.options.axis === "y") || isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
			isOverElement = isOverElementHeight && isOverElementWidth,
			verticalDirection = this._getDragVerticalDirection(),
			horizontalDirection = this._getDragHorizontalDirection();

		if (!isOverElement) {
			return false;
		}

		return this.floating ?
			( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 )
			: ( verticalDirection && (verticalDirection === "down" ? 2 : 1) );

	},

	_intersectsWithSides: function(item) {

		var isOverBottomHalf = isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
			isOverRightHalf = isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
			verticalDirection = this._getDragVerticalDirection(),
			horizontalDirection = this._getDragHorizontalDirection();

		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.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]);
				for ( j = cur.length - 1; j >= 0; j--){
					inst = $.data(cur[j], this.widgetFullName);
					if(inst && inst !== this && !inst.options.disabled) {
						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), inst]);
					}
				}
			}
		}

		queries.push([$.isFunction(this.options.items) ? 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]);

		for (i = queries.length - 1; i >= 0; i--){
			queries[i][0].each(function() {
				items.push(this);
			});
		}

		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 = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]],
			connectWith = this._connectWith();

		if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down
			for (i = connectWith.length - 1; i >= 0; i--){
				cur = $(connectWith[i]);
				for (j = cur.length - 1; j >= 0; j--){
					inst = $.data(cur[j], this.widgetFullName);
					if(inst && inst !== this && !inst.options.disabled) {
						queries.push([$.isFunction(inst.options.items) ? 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]);

				item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager)

				items.push({
					item: item,
					instance: targetData,
					width: 0, height: 0,
					left: 0, top: 0
				});
			}
		}

	},

	refreshPositions: function(fast) {

		//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();
		}

		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(item.instance !== this.currentContainer && 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;
		}

		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,
			o = that.options;

		if(!o.placeholder || o.placeholder.constructor === String) {
			className = o.placeholder;
			o.placeholder = {
				element: function() {

					var nodeName = that.currentItem[0].nodeName.toLowerCase(),
						element = $( "<" + nodeName + ">", that.document[0] )
							.addClass(className || that.currentItem[0].className+" ui-sortable-placeholder")
							.removeClass("ui-sortable-helper");

					if ( nodeName === "tr" ) {
						that.currentItem.children().each(function() {
							$( "<td>&#160;</td>", that.document[0] )
								.attr( "colspan", $( this ).attr( "colspan" ) || 1 )
								.appendTo( 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 by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
					if(!p.height()) { 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);

	},

	_contactContainers: function(event) {
		var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, base, cur, nearBottom, floating,
			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 || isFloating(this.currentItem);
			posProperty = floating ? "left" : "top";
			sizeProperty = floating ? "width" : "height";
			base = this.positionAbs[posProperty] + this.offset.click[posProperty];
			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;
				}
				if (floating && !isOverAxis(this.positionAbs.top + this.offset.click.top, this.items[j].top, this.items[j].height)) {
					continue;
				}
				cur = this.items[j].item.offset()[posProperty];
				nearBottom = false;
				if(Math.abs(cur - base) > Math.abs(cur + this.items[j][sizeProperty] - base)){
					nearBottom = true;
					cur += this.items[j][sizeProperty];
				}

				if(Math.abs(cur - base) < dist) {
					dist = Math.abs(cur - base); 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]) {
				return;
			}

			itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : 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);

			this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
			this.containers[innermostIndex].containerCache.over = 1;
		}


	},

	_createHelper: function(event) {

		var o = this.options,
			helper = $.isFunction(o.helper) ? $(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) {
			$(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[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 ($.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] !== document && $.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
		// with an ugly IE fix
		if( this.offsetParent[0] === document.body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
			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" ? document : window).width() - this.helperProportions.width - this.margins.left,
				($(o.containment === "document" ? document : window).height() || document.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] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent,
			scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		return {
			top: (
				pos.top	+																// The absolute mouse position
				this.offset.relative.top * mod +										// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.top * mod -											// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
			),
			left: (
				pos.left +																// The absolute mouse position
				this.offset.relative.left * mod +										// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.left * mod	-										// The offsetParent's offset without borders (offset + border)
				( ( 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] !== document && $.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] !== document && 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: (
				pageY -																// The absolute mouse position
				this.offset.click.top -													// Click offset (relative to the element)
				this.offset.relative.top	-											// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.top +												// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
			),
			left: (
				pageX -																// The absolute mouse position
				this.offset.click.left -												// Click offset (relative to the element)
				this.offset.relative.left	-											// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.left +												// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
			)
		};

	},

	_rearrange: function(event, i, a, hardRefresh) {

		a ? a[0].appendChild(this.placeholder[0]) : 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) {
				this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
			}
		});

	},

	_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).removeClass("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) {
			delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
		}

		// 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
		for (i = this.containers.length - 1; i >= 0; i--){
			if(!noPropagation) {
				delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
			}
			if(this.containers[i].containerCache.over) {
				delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
				this.containers[i].containerCache.over = 0;
			}
		}

		//Do what was originally in plugins
		if ( this.storedCursor ) {
			this.document.find( "body" ).css( "cursor", this.storedCursor );
			this.storedStylesheet.remove();
		}
		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(this.cancelHelperRemoval) {
			if(!noPropagation) {
				this._trigger("beforeStop", event, this._uiHash());
				for (i=0; i < delayedTriggers.length; i++) {
					delayedTriggers[i].call(this, event);
				} //Trigger all delayed events
				this._trigger("stop", event, this._uiHash());
			}

			this.fromOutside = false;
			return 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.helper[0] !== this.currentItem[0]) {
			this.helper.remove();
		}
		this.helper = null;

		if(!noPropagation) {
			for (i=0; i < delayedTriggers.length; i++) {
				delayedTriggers[i].call(this, event);
			} //Trigger all delayed events
			this._trigger("stop", event, this._uiHash());
		}

		this.fromOutside = false;
		return true;

	},

	_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);
(function( $, undefined ) {

var uid = 0,
	hideProps = {},
	showProps = {};

hideProps.height = hideProps.paddingTop = hideProps.paddingBottom =
	hideProps.borderTopWidth = hideProps.borderBottomWidth = "hide";
showProps.height = showProps.paddingTop = showProps.paddingBottom =
	showProps.borderTopWidth = showProps.borderBottomWidth = "show";

$.widget( "ui.accordion", {
	version: "1.10.3",
	options: {
		active: 0,
		animate: {},
		collapsible: false,
		event: "click",
		header: "> li > :first-child,> :not(li):even",
		heightStyle: "auto",
		icons: {
			activeHeader: "ui-icon-triangle-1-s",
			header: "ui-icon-triangle-1-e"
		},

		// callbacks
		activate: null,
		beforeActivate: null
	},

	_create: function() {
		var options = this.options;
		this.prevShow = this.prevHide = $();
		this.element.addClass( "ui-accordion ui-widget ui-helper-reset" )
			// ARIA
			.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(),
			content: !this.active.length ? $() : this.active.next()
		};
	},

	_createIcons: function() {
		var icons = this.options.icons;
		if ( icons ) {
			$( "<span>" )
				.addClass( "ui-accordion-header-icon ui-icon " + icons.header )
				.prependTo( this.headers );
			this.active.children( ".ui-accordion-header-icon" )
				.removeClass( icons.header )
				.addClass( icons.activeHeader );
			this.headers.addClass( "ui-accordion-icons" );
		}
	},

	_destroyIcons: function() {
		this.headers
			.removeClass( "ui-accordion-icons" )
			.children( ".ui-accordion-header-icon" )
				.remove();
	},

	_destroy: function() {
		var contents;

		// clean up main element
		this.element
			.removeClass( "ui-accordion ui-widget ui-helper-reset" )
			.removeAttr( "role" );

		// clean up headers
		this.headers
			.removeClass( "ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top" )
			.removeAttr( "role" )
			.removeAttr( "aria-selected" )
			.removeAttr( "aria-controls" )
			.removeAttr( "tabIndex" )
			.each(function() {
				if ( /^ui-accordion/.test( this.id ) ) {
					this.removeAttribute( "id" );
				}
			});
		this._destroyIcons();

		// clean up content panels
		contents = this.headers.next()
			.css( "display", "" )
			.removeAttr( "role" )
			.removeAttr( "aria-expanded" )
			.removeAttr( "aria-hidden" )
			.removeAttr( "aria-labelledby" )
			.removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled" )
			.each(function() {
				if ( /^ui-accordion/.test( this.id ) ) {
					this.removeAttribute( "id" );
				}
			});
		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();
			}
		}

		// #5332 - opacity doesn't cascade to positioned elements in IE
		// so we need to add the disabled class to the headers and panels
		if ( key === "disabled" ) {
			this.headers.add( this.headers.next() )
				.toggleClass( "ui-state-disabled", !!value );
		}
	},

	_keydown: function( event ) {
		/*jshint maxcomplexity:15*/
		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.focus();
			event.preventDefault();
		}
	},

	_panelKeyDown : function( event ) {
		if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) {
			$( event.currentTarget ).prev().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() {
		this.headers = this.element.find( this.options.header )
			.addClass( "ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" );

		this.headers.next()
			.addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" )
			.filter(":not(.ui-accordion-content-active)")
			.hide();
	},

	_refresh: function() {
		var maxHeight,
			options = this.options,
			heightStyle = options.heightStyle,
			parent = this.element.parent(),
			accordionId = this.accordionId = "ui-accordion-" +
				(this.element.attr( "id" ) || ++uid);

		this.active = this._findActive( options.active )
			.addClass( "ui-accordion-header-active ui-state-active ui-corner-top" )
			.removeClass( "ui-corner-all" );
		this.active.next()
			.addClass( "ui-accordion-content-active" )
			.show();

		this.headers
			.attr( "role", "tab" )
			.each(function( i ) {
				var header = $( this ),
					headerId = header.attr( "id" ),
					panel = header.next(),
					panelId = panel.attr( "id" );
				if ( !headerId ) {
					headerId = accordionId + "-header-" + i;
					header.attr( "id", headerId );
				}
				if ( !panelId ) {
					panelId = accordionId + "-panel-" + i;
					panel.attr( "id", panelId );
				}
				header.attr( "aria-controls", panelId );
				panel.attr( "aria-labelledby", headerId );
			})
			.next()
				.attr( "role", "tabpanel" );

		this.headers
			.not( this.active )
			.attr({
				"aria-selected": "false",
				tabIndex: -1
			})
			.next()
				.attr({
					"aria-expanded": "false",
					"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",
				tabIndex: 0
			})
			.next()
				.attr({
					"aria-expanded": "true",
					"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() {
					maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() );
				})
				.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 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
		active.removeClass( "ui-accordion-header-active ui-state-active" );
		if ( options.icons ) {
			active.children( ".ui-accordion-header-icon" )
				.removeClass( options.icons.activeHeader )
				.addClass( options.icons.header );
		}

		if ( !clickedIsActive ) {
			clicked
				.removeClass( "ui-corner-all" )
				.addClass( "ui-accordion-header-active ui-state-active ui-corner-top" );
			if ( options.icons ) {
				clicked.children( ".ui-accordion-header-icon" )
					.removeClass( options.icons.header )
					.addClass( options.icons.activeHeader );
			}

			clicked
				.next()
				.addClass( "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-expanded": "false",
			"aria-hidden": "true"
		});
		toHide.prev().attr( "aria-selected", "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 );
		} else if ( toShow.length ) {
			this.headers.filter(function() {
				return $( this ).attr( "tabIndex" ) === 0;
			})
			.attr( "tabIndex", -1 );
		}

		toShow
			.attr({
				"aria-expanded": "true",
				"aria-hidden": "false"
			})
			.prev()
				.attr({
					"aria-selected": "true",
					tabIndex: 0
				});
	},

	_animate: function( toShow, toHide, data ) {
		var total, easing, duration,
			that = this,
			adjust = 0,
			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( showProps, duration, easing, complete );
		}
		if ( !toShow.length ) {
			return toHide.animate( hideProps, duration, easing, complete );
		}

		total = toShow.show().outerHeight();
		toHide.animate( hideProps, {
			duration: duration,
			easing: easing,
			step: function( now, fx ) {
				fx.now = Math.round( now );
			}
		});
		toShow
			.hide()
			.animate( showProps, {
				duration: duration,
				easing: easing,
				complete: complete,
				step: function( now, fx ) {
					fx.now = Math.round( now );
					if ( fx.prop !== "height" ) {
						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;

		toHide
			.removeClass( "ui-accordion-content-active" )
			.prev()
				.removeClass( "ui-corner-top" )
				.addClass( "ui-corner-all" );

		// Work around for rendering bug in IE (#5421)
		if ( toHide.length ) {
			toHide.parent()[0].className = toHide.parent()[0].className;
		}

		this._trigger( "activate", null, data );
	}
});

})( jQuery );
(function( $, undefined ) {

// used to prevent race conditions with remote data sources
var requestIndex = 0;

$.widget( "ui.autocomplete", {
	version: "1.10.3",
	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
	},

	pending: 0,

	_create: function() {
		// Some browsers only repeat keydown events, not keypress events,
		// so we use the suppressKeyPress flag to determine if we've already
		// handled the keydown event. #7269
		// Unfortunately the code for & 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";

		this.isMultiLine =
			// Textareas are always multi-line
			isTextarea ? true :
			// Inputs are always single-line, even if inside a contentEditable element
			// IE also treats inputs as contentEditable
			isInput ? false :
			// All other element types are determined by whether or not they're contentEditable
			this.element.prop( "isContentEditable" );

		this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
		this.isNewMenu = true;

		this.element
			.addClass( "ui-autocomplete-input" )
			.attr( "autocomplete", "off" );

		this._on( this.element, {
			keydown: function( event ) {
				/*jshint maxcomplexity:15*/
				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:
				case keyCode.NUMPAD_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" ) ) {
						this._value( this.term );
						this.close( event );
						// Different browsers have different default behavior for escape
						// Single press can mean undo or clear
						// Double press in IE means clear the whole form
						event.preventDefault();
					}
					break;
				default:
					suppressKeyPressRepeat = true;
					// search timeout should be triggered before the input value is changed
					this._searchTimeout( event );
					break;
				}
			},
			keypress: function( event ) {
				if ( suppressKeyPress ) {
					suppressKeyPress = false;
					if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
						event.preventDefault();
					}
					return;
				}
				if ( suppressKeyPressRepeat ) {
					return;
				}

				// replicate some key handlers to allow them to repeat in Firefox and Opera
				var keyCode = $.ui.keyCode;
				switch( event.keyCode ) {
				case keyCode.PAGE_UP:
					this._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					this._move( "nextPage", event );
					break;
				case keyCode.UP:
					this._keyEvent( "previous", event );
					break;
				case keyCode.DOWN:
					this._keyEvent( "next", event );
					break;
				}
			},
			input: function( event ) {
				if ( suppressInput ) {
					suppressInput = false;
					event.preventDefault();
					return;
				}
				this._searchTimeout( event );
			},
			focus: function() {
				this.selectedItem = null;
				this.previous = this._value();
			},
			blur: function( event ) {
				if ( this.cancelBlur ) {
					delete this.cancelBlur;
					return;
				}

				clearTimeout( this.searching );
				this.close( event );
				this._change( event );
			}
		});

		this._initSource();
		this.menu = $( "<ul>" )
			.addClass( "ui-autocomplete ui-front" )
			.appendTo( this._appendTo() )
			.menu({
				// disable ARIA support, the live region takes care of that
				role: null
			})
			.hide()
			.data( "ui-menu" );

		this._on( this.menu.element, {
			mousedown: function( event ) {
				// prevent moving focus out of the text field
				event.preventDefault();

				// IE doesn't prevent moving focus even with event.preventDefault()
				// so we set a flag to know when we should ignore the blur event
				this.cancelBlur = true;
				this._delay(function() {
					delete this.cancelBlur;
				});

				// clicking on the scrollbar causes focus to shift to the body
				// but we can't detect a mouseup or a click immediately afterward
				// so we have to track the next mousedown and close the menu if
				// the user clicks somewhere outside of the autocomplete
				var menuElement = this.menu.element[ 0 ];
				if ( !$( event.target ).closest( ".ui-menu-item" ).length ) {
					this._delay(function() {
						var that = this;
						this.document.one( "mousedown", function( event ) {
							if ( event.target !== that.element[ 0 ] &&
									event.target !== menuElement &&
									!$.contains( menuElement, event.target ) ) {
								that.close();
							}
						});
					});
				}
			},
			menufocus: function( event, ui ) {
				// 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;
					}
				}

				var 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 );
					}
				} else {
					// Normally the input is populated with the item's value as the
					// menu is navigated, causing screen readers to notice a change and
					// announce the item. Since the focus event was canceled, this doesn't
					// happen, so we update the live region so that screen readers can
					// still notice the change and announce it.
					this.liveRegion.text( item.value );
				}
			},
			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.focus();
					this.previous = previous;
					// #6109 - IE triggers two focus events and the second
					// is asynchronous, so we need to reset the previous
					// term synchronously and asynchronously :-(
					this._delay(function() {
						this.previous = previous;
						this.selectedItem = item;
					});
				}

				if ( false !== this._trigger( "select", event, { item: item } ) ) {
					this._value( item.value );
				}
				// reset the term after the select event
				// this allows custom select handling to work properly
				this.term = this._value();

				this.close( event );
				this.selectedItem = item;
			}
		});

		this.liveRegion = $( "<span>", {
				role: "status",
				"aria-live": "polite"
			})
			.addClass( "ui-helper-hidden-accessible" )
			.insertBefore( this.element );

		// 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
			.removeClass( "ui-autocomplete-input" )
			.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();
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;

		if ( element ) {
			element = element.jquery || element.nodeType ?
				$( element ) :
				this.document.find( element ).eq( 0 );
		}

		if ( !element ) {
			element = this.element.closest( ".ui-front" );
		}

		if ( !element.length ) {
			element = this.document[0].body;
		}

		return element;
	},

	_initSource: function() {
		var array, url,
			that = this;
		if ( $.isArray(this.options.source) ) {
			array = this.options.source;
			this.source = function( request, response ) {
				response( $.ui.autocomplete.filter( array, request.term ) );
			};
		} else if ( typeof this.options.source === "string" ) {
			url = this.options.source;
			this.source = function( request, response ) {
				if ( that.xhr ) {
					that.xhr.abort();
				}
				that.xhr = $.ajax({
					url: url,
					data: request,
					dataType: "json",
					success: function( data ) {
						response( data );
					},
					error: function() {
						response( [] );
					}
				});
			};
		} else {
			this.source = this.options.source;
		}
	},

	_searchTimeout: function( event ) {
		clearTimeout( this.searching );
		this.searching = this._delay(function() {
			// only search if the value has changed
			if ( this.term !== this._value() ) {
				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.element.addClass( "ui-autocomplete-loading" );
		this.cancelSearch = false;

		this.source( { term: value }, this._response() );
	},

	_response: function() {
		var that = this,
			index = ++requestIndex;

		return function( content ) {
			if ( index === requestIndex ) {
				that.__response( content );
			}

			that.pending--;
			if ( !that.pending ) {
				that.element.removeClass( "ui-autocomplete-loading" );
			}
		};
	},

	__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 ) {
		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({
				label: item.label || item.value,
				value: item.value || item.label
			}, item );
		});
	},

	_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();
		}
	},

	_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( $( "<a>" ).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 ) ) {
			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;
		}
		this.liveRegion.text( message );
	}
});

}( jQuery ));
(function( $, undefined ) {

var lastActive, startXPos, startYPos, clickDragged,
	baseClasses = "ui-button ui-widget ui-state-default ui-corner-all",
	stateClasses = "ui-state-hover ui-state-active ",
	typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",
	formResetHandler = function() {
		var form = $( this );
		setTimeout(function() {
			form.find( ":ui-button" ).button( "refresh" );
		}, 1 );
	},
	radioGroup = function( radio ) {
		var name = radio.name,
			form = radio.form,
			radios = $( [] );
		if ( name ) {
			name = name.replace( /'/g, "\\'" );
			if ( form ) {
				radios = $( form ).find( "[name='" + name + "']" );
			} else {
				radios = $( "[name='" + name + "']", radio.ownerDocument )
					.filter(function() {
						return !this.form;
					});
			}
		}
		return radios;
	};

$.widget( "ui.button", {
	version: "1.10.3",
	defaultElement: "<button>",
	options: {
		disabled: null,
		text: true,
		label: null,
		icons: {
			primary: null,
			secondary: null
		}
	},
	_create: function() {
		this.element.closest( "form" )
			.unbind( "reset" + this.eventNamespace )
			.bind( "reset" + this.eventNamespace, formResetHandler );

		if ( typeof this.options.disabled !== "boolean" ) {
			this.options.disabled = !!this.element.prop( "disabled" );
		} else {
			this.element.prop( "disabled", this.options.disabled );
		}

		this._determineButtonType();
		this.hasTitle = !!this.buttonElement.attr( "title" );

		var that = this,
			options = this.options,
			toggleButton = this.type === "checkbox" || this.type === "radio",
			activeClass = !toggleButton ? "ui-state-active" : "",
			focusClass = "ui-state-focus";

		if ( options.label === null ) {
			options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html());
		}

		this._hoverable( this.buttonElement );

		this.buttonElement
			.addClass( baseClasses )
			.attr( "role", "button" )
			.bind( "mouseenter" + this.eventNamespace, function() {
				if ( options.disabled ) {
					return;
				}
				if ( this === lastActive ) {
					$( this ).addClass( "ui-state-active" );
				}
			})
			.bind( "mouseleave" + this.eventNamespace, function() {
				if ( options.disabled ) {
					return;
				}
				$( this ).removeClass( activeClass );
			})
			.bind( "click" + this.eventNamespace, function( event ) {
				if ( options.disabled ) {
					event.preventDefault();
					event.stopImmediatePropagation();
				}
			});

		this.element
			.bind( "focus" + this.eventNamespace, function() {
				// no need to check disabled, focus won't be triggered anyway
				that.buttonElement.addClass( focusClass );
			})
			.bind( "blur" + this.eventNamespace, function() {
				that.buttonElement.removeClass( focusClass );
			});

		if ( toggleButton ) {
			this.element.bind( "change" + this.eventNamespace, function() {
				if ( clickDragged ) {
					return;
				}
				that.refresh();
			});
			// if mouse moves between mousedown and mouseup (drag) set clickDragged flag
			// prevents issue where button state changes but checkbox/radio checked state
			// does not in Firefox (see ticket #6970)
			this.buttonElement
				.bind( "mousedown" + this.eventNamespace, function( event ) {
					if ( options.disabled ) {
						return;
					}
					clickDragged = false;
					startXPos = event.pageX;
					startYPos = event.pageY;
				})
				.bind( "mouseup" + this.eventNamespace, function( event ) {
					if ( options.disabled ) {
						return;
					}
					if ( startXPos !== event.pageX || startYPos !== event.pageY ) {
						clickDragged = true;
					}
			});
		}

		if ( this.type === "checkbox" ) {
			this.buttonElement.bind( "click" + this.eventNamespace, function() {
				if ( options.disabled || clickDragged ) {
					return false;
				}
			});
		} else if ( this.type === "radio" ) {
			this.buttonElement.bind( "click" + this.eventNamespace, function() {
				if ( options.disabled || clickDragged ) {
					return false;
				}
				$( this ).addClass( "ui-state-active" );
				that.buttonElement.attr( "aria-pressed", "true" );

				var radio = that.element[ 0 ];
				radioGroup( radio )
					.not( radio )
					.map(function() {
						return $( this ).button( "widget" )[ 0 ];
					})
					.removeClass( "ui-state-active" )
					.attr( "aria-pressed", "false" );
			});
		} else {
			this.buttonElement
				.bind( "mousedown" + this.eventNamespace, function() {
					if ( options.disabled ) {
						return false;
					}
					$( this ).addClass( "ui-state-active" );
					lastActive = this;
					that.document.one( "mouseup", function() {
						lastActive = null;
					});
				})
				.bind( "mouseup" + this.eventNamespace, function() {
					if ( options.disabled ) {
						return false;
					}
					$( this ).removeClass( "ui-state-active" );
				})
				.bind( "keydown" + this.eventNamespace, function(event) {
					if ( options.disabled ) {
						return false;
					}
					if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) {
						$( this ).addClass( "ui-state-active" );
					}
				})
				// see #8559, we bind to blur here in case the button element loses
				// focus between keydown and keyup, it would be left in an "active" state
				.bind( "keyup" + this.eventNamespace + " blur" + this.eventNamespace, function() {
					$( this ).removeClass( "ui-state-active" );
				});

			if ( this.buttonElement.is("a") ) {
				this.buttonElement.keyup(function(event) {
					if ( event.keyCode === $.ui.keyCode.SPACE ) {
						// TODO pass through original event correctly (just as 2nd argument doesn't work)
						$( this ).click();
					}
				});
			}
		}

		// TODO: pull out $.Widget's handling for the disabled option into
		// $.Widget.prototype._setOptionDisabled so it's easy to proxy and can
		// be overridden by individual plugins
		this._setOption( "disabled", options.disabled );
		this._resetButton();
	},

	_determineButtonType: function() {
		var ancestor, labelSelector, checked;

		if ( this.element.is("[type=checkbox]") ) {
			this.type = "checkbox";
		} else if ( this.element.is("[type=radio]") ) {
			this.type = "radio";
		} else if ( this.element.is("input") ) {
			this.type = "input";
		} else {
			this.type = "button";
		}

		if ( this.type === "checkbox" || this.type === "radio" ) {
			// we don't search against the document in case the element
			// is disconnected from the DOM
			ancestor = this.element.parents().last();
			labelSelector = "label[for='" + this.element.attr("id") + "']";
			this.buttonElement = ancestor.find( labelSelector );
			if ( !this.buttonElement.length ) {
				ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings();
				this.buttonElement = ancestor.filter( labelSelector );
				if ( !this.buttonElement.length ) {
					this.buttonElement = ancestor.find( labelSelector );
				}
			}
			this.element.addClass( "ui-helper-hidden-accessible" );

			checked = this.element.is( ":checked" );
			if ( checked ) {
				this.buttonElement.addClass( "ui-state-active" );
			}
			this.buttonElement.prop( "aria-pressed", checked );
		} else {
			this.buttonElement = this.element;
		}
	},

	widget: function() {
		return this.buttonElement;
	},

	_destroy: function() {
		this.element
			.removeClass( "ui-helper-hidden-accessible" );
		this.buttonElement
			.removeClass( baseClasses + " " + stateClasses + " " + typeClasses )
			.removeAttr( "role" )
			.removeAttr( "aria-pressed" )
			.html( this.buttonElement.find(".ui-button-text").html() );

		if ( !this.hasTitle ) {
			this.buttonElement.removeAttr( "title" );
		}
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "disabled" ) {
			if ( value ) {
				this.element.prop( "disabled", true );
			} else {
				this.element.prop( "disabled", false );
			}
			return;
		}
		this._resetButton();
	},

	refresh: function() {
		//See #8237 & #8828
		var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "ui-button-disabled" );

		if ( isDisabled !== this.options.disabled ) {
			this._setOption( "disabled", isDisabled );
		}
		if ( this.type === "radio" ) {
			radioGroup( this.element[0] ).each(function() {
				if ( $( this ).is( ":checked" ) ) {
					$( this ).button( "widget" )
						.addClass( "ui-state-active" )
						.attr( "aria-pressed", "true" );
				} else {
					$( this ).button( "widget" )
						.removeClass( "ui-state-active" )
						.attr( "aria-pressed", "false" );
				}
			});
		} else if ( this.type === "checkbox" ) {
			if ( this.element.is( ":checked" ) ) {
				this.buttonElement
					.addClass( "ui-state-active" )
					.attr( "aria-pressed", "true" );
			} else {
				this.buttonElement
					.removeClass( "ui-state-active" )
					.attr( "aria-pressed", "false" );
			}
		}
	},

	_resetButton: function() {
		if ( this.type === "input" ) {
			if ( this.options.label ) {
				this.element.val( this.options.label );
			}
			return;
		}
		var buttonElement = this.buttonElement.removeClass( typeClasses ),
			buttonText = $( "<span></span>", this.document[0] )
				.addClass( "ui-button-text" )
				.html( this.options.label )
				.appendTo( buttonElement.empty() )
				.text(),
			icons = this.options.icons,
			multipleIcons = icons.primary && icons.secondary,
			buttonClasses = [];

		if ( icons.primary || icons.secondary ) {
			if ( this.options.text ) {
				buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) );
			}

			if ( icons.primary ) {
				buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" );
			}

			if ( icons.secondary ) {
				buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" );
			}

			if ( !this.options.text ) {
				buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" );

				if ( !this.hasTitle ) {
					buttonElement.attr( "title", $.trim( buttonText ) );
				}
			}
		} else {
			buttonClasses.push( "ui-button-text-only" );
		}
		buttonElement.addClass( buttonClasses.join( " " ) );
	}
});

$.widget( "ui.buttonset", {
	version: "1.10.3",
	options: {
		items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"
	},

	_create: function() {
		this.element.addClass( "ui-buttonset" );
	},

	_init: function() {
		this.refresh();
	},

	_setOption: function( key, value ) {
		if ( key === "disabled" ) {
			this.buttons.button( "option", key, value );
		}

		this._super( key, value );
	},

	refresh: function() {
		var rtl = this.element.css( "direction" ) === "rtl";

		this.buttons = this.element.find( this.options.items )
			.filter( ":ui-button" )
				.button( "refresh" )
			.end()
			.not( ":ui-button" )
				.button()
			.end()
			.map(function() {
				return $( this ).button( "widget" )[ 0 ];
			})
				.removeClass( "ui-corner-all ui-corner-left ui-corner-right" )
				.filter( ":first" )
					.addClass( rtl ? "ui-corner-right" : "ui-corner-left" )
				.end()
				.filter( ":last" )
					.addClass( rtl ? "ui-corner-left" : "ui-corner-right" )
				.end()
			.end();
	},

	_destroy: function() {
		this.element.removeClass( "ui-buttonset" );
		this.buttons
			.map(function() {
				return $( this ).button( "widget" )[ 0 ];
			})
				.removeClass( "ui-corner-left ui-corner-right" )
			.end()
			.button( "destroy" );
	}
});

}( jQuery ) );
(function( $, undefined ) {

$.extend($.ui, { datepicker: { version: "1.10.3" } });

var PROP_NAME = "datepicker",
	instActive;

/* 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
	};
	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
		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.dpDiv = 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) {
		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
			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).keydown(this._doKeyDown).
			keypress(this._doKeyPress).keyup(this._doKeyUp);
		this._autoSize(inst);
		$.data(target, PROP_NAME, 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 class='" + this._appendClass + "'>" + appendText + "</span>");
			input[isRTL ? "before" : "after"](inst.append);
		}

		input.unbind("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.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");
			inst.trigger = $(this._get(inst, "buttonImageOnly") ?
				$("<img/>").addClass(this._triggerClass).
					attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
				$("<button type='button'></button>").addClass(this._triggerClass).
					html(!buttonImage ? buttonText : $("<img/>").attr(
					{ src:buttonImage, alt:buttonText, title:buttonText })));
			input[isRTL ? "before" : "after"](inst.trigger);
			inst.trigger.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, PROP_NAME, 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
		// http://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.keydown(this._doKeyDown);
			$("body").append(this._dialogInput);
			inst = this._dialogInst = this._newInst(this._dialogInput, false);
			inst.settings = {};
			$.data(this._dialogInput[0], PROP_NAME, inst);
		}
		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], PROP_NAME, 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, PROP_NAME);

		if (!$target.hasClass(this.markerClassName)) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		$.removeData(target, PROP_NAME);
		if (nodeName === "input") {
			inst.append.remove();
			inst.trigger.remove();
			$target.removeClass(this.markerClassName).
				unbind("focus", this._showDatepicker).
				unbind("keydown", this._doKeyDown).
				unbind("keypress", this._doKeyPress).
				unbind("keyup", this._doKeyUp);
		} else if (nodeName === "div" || nodeName === "span") {
			$target.removeClass(this.markerClassName).empty();
		}
	},

	/* 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, PROP_NAME);

		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,
			function(value) { return (value === target ? null : value); }); // delete entry
	},

	/* 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, PROP_NAME);

		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,
			function(value) { return (value === target ? null : value); }); // delete entry
		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, PROP_NAME);
		}
		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");
			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;
		}
		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.zIndex($(input).zIndex()+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.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)
		instActive = inst; // for delegate hover events
		inst.dpDiv.empty().append(this._generateHTML(inst));
		this._attachHandlers(inst);
		inst.dpDiv.find("." + this._dayOverClass + " a").mouseover();

		var origyearshtml,
			numMonths = this._getNumberOfMonths(inst),
			cols = numMonths[1],
			width = 17;

		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.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);
		}
	},

	// #6694 - don't focus the input if it's already focused
	// this breaks the change event in IE
	// Support: IE and jQuery <1.9
	_shouldFocusInput: function( inst ) {
		return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" );
	},

	/* 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.filters.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, PROP_NAME))) {
			return;
		}

		if (this._datepickerShowing) {
			showAnim = this._get(inst, "showAnim");
			duration = this._get(inst, "duration");
			postProcess = function() {
				$.datepicker._tidyDialog(inst);
			};

			// DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
			if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ 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).unbind(".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 === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning
			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 = $("a", td).html();
		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.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));
			$(altField).each(function() { $(this).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)))),
					digits = new RegExp("^\\d{1," + 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.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 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 (event) {
			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).bind(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)));

		prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
			"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" +
			" title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" :
			(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>"));

		nextText = this._get(inst, "nextText");
		nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
			this._getFormatConfig(inst)));

		next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
			"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" +
			" title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" :
			(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>"));

		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 = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" +
			this._get(inst, "closeText") + "</button>" : "");

		buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") +
			(this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" +
			">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : "";

		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 = "";
		dow;
		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" + ((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='#'>" + 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"),
			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' 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' 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.drawYear + (period === "Y" ? offset : 0),
			month = inst.drawMonth + (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 instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
 */
function bindHover(dpDiv) {
	var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
	return dpDiv.delegate(selector, "mouseout", 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");
			}
		})
		.delegate(selector, "mouseover", function(){
			if (!$.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : 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 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).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() {
		typeof options === "string" ?
			$.datepicker["_" + options + "Datepicker"].
				apply($.datepicker, [this].concat(otherArgs)) :
			$.datepicker._attachDatepicker(this, options);
	});
};

$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.10.3";

})(jQuery);
(function( $, undefined ) {

var sizeRelatedOptions = {
		buttons: true,
		height: true,
		maxHeight: true,
		maxWidth: true,
		minHeight: true,
		minWidth: true,
		width: true
	},
	resizableRelatedOptions = {
		maxHeight: true,
		maxWidth: true,
		minHeight: true,
		minWidth: true
	};

$.widget( "ui.dialog", {
	version: "1.10.3",
	options: {
		appendTo: "body",
		autoOpen: true,
		buttons: [],
		closeOnEscape: true,
		closeText: "close",
		dialogClass: "",
		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,
		width: 300,

		// callbacks
		beforeClose: null,
		close: null,
		drag: null,
		dragStart: null,
		dragStop: null,
		focus: null,
		open: null,
		resize: null,
		resizeStart: null,
		resizeStop: null
	},

	_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");
		this.options.title = this.options.title || this.originalTitle;

		this._createWrapper();

		this.element
			.show()
			.removeAttr("title")
			.addClass("ui-dialog-content ui-widget-content")
			.appendTo( this.uiDialog );

		this._createTitlebar();
		this._createButtonPane();

		if ( this.options.draggable && $.fn.draggable ) {
			this._makeDraggable();
		}
		if ( this.options.resizable && $.fn.resizable ) {
			this._makeResizable();
		}

		this._isOpen = false;
	},

	_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._destroyOverlay();

		this.element
			.removeUniqueId()
			.removeClass("ui-dialog-content ui-widget-content")
			.css( this.originalCss )
			// Without detaching first, the following becomes really slow
			.detach();

		this.uiDialog.stop( true, true ).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._destroyOverlay();

		if ( !this.opener.filter(":focusable").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 ).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 = !!this.uiDialog.nextAll(":visible").insertBefore( this.uiDialog ).length;
		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 );
		this._show( this.uiDialog, this.options.show, function() {
			that._focusTabbable();
			that._trigger("focus");
		});

		this._trigger("open");
	},

	_focusTabbable: function() {
		// Set focus to the first match:
		// 1. First element inside the dialog matching [autofocus]
		// 2. Tabbable element inside the content element
		// 3. Tabbable element inside the buttonpane
		// 4. The close button
		// 5. The dialog itself
		var 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 ).focus();
	},

	_keepFocus: function( event ) {
		function checkFocus() {
			var activeElement = this.document[0].activeElement,
				isActive = this.uiDialog[0] === activeElement ||
					$.contains( this.uiDialog[0], activeElement );
			if ( !isActive ) {
				this._focusTabbable();
			}
		}
		event.preventDefault();
		checkFocus.call( this );
		// support: IE
		// IE <= 8 doesn't prevent moving focus even with event.preventDefault()
		// so we check again later
		this._delay( checkFocus );
	},

	_createWrapper: function() {
		this.uiDialog = $("<div>")
			.addClass( "ui-dialog ui-widget ui-widget-content ui-corner-all ui-front " +
				this.options.dialogClass )
			.hide()
			.attr({
				// Setting tabIndex makes the div focusable
				tabIndex: -1,
				role: "dialog"
			})
			.appendTo( this._appendTo() );

		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 ) {
					return;
				}
				var tabbables = this.uiDialog.find(":tabbable"),
					first = tabbables.filter(":first"),
					last  = tabbables.filter(":last");

				if ( ( event.target === last[0] || event.target === this.uiDialog[0] ) && !event.shiftKey ) {
					first.focus( 1 );
					event.preventDefault();
				} else if ( ( event.target === first[0] || event.target === this.uiDialog[0] ) && event.shiftKey ) {
					last.focus( 1 );
					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>")
			.addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix")
			.prependTo( this.uiDialog );
		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.focus();
				}
			}
		});

		this.uiDialogTitlebarClose = $("<button></button>")
			.button({
				label: this.options.closeText,
				icons: {
					primary: "ui-icon-closethick"
				},
				text: false
			})
			.addClass("ui-dialog-titlebar-close")
			.appendTo( this.uiDialogTitlebar );
		this._on( this.uiDialogTitlebarClose, {
			click: function( event ) {
				event.preventDefault();
				this.close( event );
			}
		});

		uiDialogTitle = $("<span>")
			.uniqueId()
			.addClass("ui-dialog-title")
			.prependTo( this.uiDialogTitlebar );
		this._title( uiDialogTitle );

		this.uiDialog.attr({
			"aria-labelledby": uiDialogTitle.attr("id")
		});
	},

	_title: function( title ) {
		if ( !this.options.title ) {
			title.html("&#160;");
		}
		title.text( this.options.title );
	},

	_createButtonPane: function() {
		this.uiDialogButtonPane = $("<div>")
			.addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix");

		this.uiButtonSet = $("<div>")
			.addClass("ui-dialog-buttonset")
			.appendTo( this.uiDialogButtonPane );

		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 ) || ($.isArray( buttons ) && !buttons.length) ) {
			this.uiDialog.removeClass("ui-dialog-buttons");
			return;
		}

		$.each( buttons, function( name, props ) {
			var click, buttonOptions;
			props = $.isFunction( props ) ?
				{ 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;
			props.click = function() {
				click.apply( that.element[0], arguments );
			};
			buttonOptions = {
				icons: props.icons,
				text: props.showText
			};
			delete props.icons;
			delete props.showText;
			$( "<button></button>", props )
				.button( buttonOptions )
				.appendTo( that.uiButtonSet );
		});
		this.uiDialog.addClass("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 ) {
				$( this ).addClass("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 ) {
				options.position = [
					ui.position.left - that.document.scrollLeft(),
					ui.position.top - that.document.scrollTop()
				];
				$( this ).removeClass("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 ) {
				$( this ).addClass("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 ) {
				options.height = $( this ).height();
				options.width = $( this ).width();
				$( this ).removeClass("ui-dialog-resizing");
				that._unblockFrames();
				that._trigger( "resizeStop", event, filteredUi( ui ) );
			}
		})
		.css( "position", position );
	},

	_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 sizeRelatedOptions ) {
				resize = true;
			}
			if ( key in 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 ) {
		/*jshint maxcomplexity:15*/
		var isDraggable, isResizable,
			uiDialog = this.uiDialog;

		if ( key === "dialogClass" ) {
			uiDialog
				.removeClass( this.options.dialogClass )
				.addClass( value );
		}

		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: "" + value
			});
		}

		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") );
		}
	},

	_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;
		}

		var that = this,
			widgetFullName = this.widgetFullName;
		if ( !$.ui.dialog.overlayInstances ) {
			// Prevent use of anchors and inputs.
			// We use a delay in case the overlay is created from an
			// event that we're going to be cancelling. (#2804)
			this._delay(function() {
				// Handle .dialog().dialog("close") (#4065)
				if ( $.ui.dialog.overlayInstances ) {
					this.document.bind( "focusin.dialog", function( event ) {
						if ( !that._allowInteraction( event ) ) {
							event.preventDefault();
							$(".ui-dialog:visible:last .ui-dialog-content")
								.data( widgetFullName )._focusTabbable();
						}
					});
				}
			});
		}

		this.overlay = $("<div>")
			.addClass("ui-widget-overlay ui-front")
			.appendTo( this._appendTo() );
		this._on( this.overlay, {
			mousedown: "_keepFocus"
		});
		$.ui.dialog.overlayInstances++;
	},

	_destroyOverlay: function() {
		if ( !this.options.modal ) {
			return;
		}

		if ( this.overlay ) {
			$.ui.dialog.overlayInstances--;

			if ( !$.ui.dialog.overlayInstances ) {
				this.document.unbind( "focusin.dialog" );
			}
			this.overlay.remove();
			this.overlay = null;
		}
	}
});

$.ui.dialog.overlayInstances = 0;

// DEPRECATED
if ( $.uiBackCompat !== false ) {
	// position option with array notation
	// just override with old implementation
	$.widget( "ui.dialog", $.ui.dialog, {
		_position: function() {
			var position = this.options.position,
				myAt = [],
				offset = [ 0, 0 ],
				isVisible;

			if ( position ) {
				if ( typeof position === "string" || (typeof position === "object" && "0" in position ) ) {
					myAt = position.split ? position.split(" ") : [ position[0], position[1] ];
					if ( myAt.length === 1 ) {
						myAt[1] = myAt[0];
					}

					$.each( [ "left", "top" ], function( i, offsetPosition ) {
						if ( +myAt[ i ] === myAt[ i ] ) {
							offset[ i ] = myAt[ i ];
							myAt[ i ] = offsetPosition;
						}
					});

					position = {
						my: myAt[0] + (offset[0] < 0 ? offset[0] : "+" + offset[0]) + " " +
							myAt[1] + (offset[1] < 0 ? offset[1] : "+" + offset[1]),
						at: myAt.join(" ")
					};
				}

				position = $.extend( {}, $.ui.dialog.prototype.options.position, position );
			} else {
				position = $.ui.dialog.prototype.options.position;
			}

			// need to show the dialog to get the actual offset in the position plugin
			isVisible = this.uiDialog.is(":visible");
			if ( !isVisible ) {
				this.uiDialog.show();
			}
			this.uiDialog.position( position );
			if ( !isVisible ) {
				this.uiDialog.hide();
			}
		}
	});
}

}( jQuery ) );
(function( $, undefined ) {

$.widget( "ui.menu", {
	version: "1.10.3",
	defaultElement: "<ul>",
	delay: 300,
	options: {
		icons: {
			submenu: "ui-icon-carat-1-e"
		},
		menus: "ul",
		position: {
			my: "left top",
			at: "right top"
		},
		role: "menu",

		// callbacks
		blur: null,
		focus: null,
		select: null
	},

	_create: function() {
		this.activeMenu = this.element;
		// flag used to prevent firing of the click handler
		// as the event bubbles up through nested menus
		this.mouseHandled = false;
		this.element
			.uniqueId()
			.addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
			.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length )
			.attr({
				role: this.options.role,
				tabIndex: 0
			})
			// need to catch all clicks on disabled menu
			// not possible through _on
			.bind( "click" + this.eventNamespace, $.proxy(function( event ) {
				if ( this.options.disabled ) {
					event.preventDefault();
				}
			}, this ));

		if ( this.options.disabled ) {
			this.element
				.addClass( "ui-state-disabled" )
				.attr( "aria-disabled", "true" );
		}

		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 > a": function( event ) {
				event.preventDefault();
			},
			"click .ui-state-disabled > a": function( event ) {
				event.preventDefault();
			},
			"click .ui-menu-item:has(a)": function( event ) {
				var target = $( event.target ).closest( ".ui-menu-item" );
				if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) {
					this.mouseHandled = true;

					this.select( event );
					// Open submenu on click
					if ( target.has( ".ui-menu" ).length ) {
						this.expand( event );
					} else if ( !this.element.is( ":focus" ) ) {
						// Redirect focus to the menu
						this.element.trigger( "focus", [ true ] );

						// If the active item is on the top level, let it stay active.
						// Otherwise, blur the active item since it is no longer visible.
						if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) {
							clearTimeout( this.timer );
						}
					}
				}
			},
			"mouseenter .ui-menu-item": function( event ) {
				var target = $( event.currentTarget );
				// 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
				target.siblings().children( ".ui-state-active" ).removeClass( "ui-state-active" );
				this.focus( event, target );
			},
			mouseleave: "collapseAll",
			"mouseleave .ui-menu": "collapseAll",
			focus: function( event, keepActiveItem ) {
				// If there's already an active item, keep it active
				// If not, activate the first item
				var item = this.active || this.element.children( ".ui-menu-item" ).eq( 0 );

				if ( !keepActiveItem ) {
					this.focus( event, item );
				}
			},
			blur: function( event ) {
				this._delay(function() {
					if ( !$.contains( this.element[0], this.document[0].activeElement ) ) {
						this.collapseAll( event );
					}
				});
			},
			keydown: "_keydown"
		});

		this.refresh();

		// Clicks outside of a menu collapse any open menus
		this._on( this.document, {
			click: function( event ) {
				if ( !$( event.target ).closest( ".ui-menu" ).length ) {
					this.collapseAll( event );
				}

				// Reset the mouseHandled flag
				this.mouseHandled = false;
			}
		});
	},

	_destroy: function() {
		// Destroy (sub)menus
		this.element
			.removeAttr( "aria-activedescendant" )
			.find( ".ui-menu" ).addBack()
				.removeClass( "ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons" )
				.removeAttr( "role" )
				.removeAttr( "tabIndex" )
				.removeAttr( "aria-labelledby" )
				.removeAttr( "aria-expanded" )
				.removeAttr( "aria-hidden" )
				.removeAttr( "aria-disabled" )
				.removeUniqueId()
				.show();

		// Destroy menu items
		this.element.find( ".ui-menu-item" )
			.removeClass( "ui-menu-item" )
			.removeAttr( "role" )
			.removeAttr( "aria-disabled" )
			.children( "a" )
				.removeUniqueId()
				.removeClass( "ui-corner-all ui-state-hover" )
				.removeAttr( "tabIndex" )
				.removeAttr( "role" )
				.removeAttr( "aria-haspopup" )
				.children().each( function() {
					var elem = $( this );
					if ( elem.data( "ui-menu-submenu-carat" ) ) {
						elem.remove();
					}
				});

		// Destroy menu dividers
		this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" );
	},

	_keydown: function( event ) {
		/*jshint maxcomplexity:20*/
		var match, prev, character, skip, regex,
			preventDefault = true;

		function escape( value ) {
			return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
		}

		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 || "";
			character = String.fromCharCode( event.keyCode );
			skip = false;

			clearTimeout( this.filterTimer );

			if ( character === prev ) {
				skip = true;
			} else {
				character = prev + character;
			}

			regex = new RegExp( "^" + escape( character ), "i" );
			match = this.activeMenu.children( ".ui-menu-item" ).filter(function() {
				return regex.test( $( this ).children( "a" ).text() );
			});
			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 );
				regex = new RegExp( "^" + escape( character ), "i" );
				match = this.activeMenu.children( ".ui-menu-item" ).filter(function() {
					return regex.test( $( this ).children( "a" ).text() );
				});
			}

			if ( match.length ) {
				this.focus( event, match );
				if ( match.length > 1 ) {
					this.previousFilter = character;
					this.filterTimer = this._delay(function() {
						delete this.previousFilter;
					}, 1000 );
				} else {
					delete this.previousFilter;
				}
			} else {
				delete this.previousFilter;
			}
		}

		if ( preventDefault ) {
			event.preventDefault();
		}
	},

	_activate: function( event ) {
		if ( !this.active.is( ".ui-state-disabled" ) ) {
			if ( this.active.children( "a[aria-haspopup='true']" ).length ) {
				this.expand( event );
			} else {
				this.select( event );
			}
		}
	},

	refresh: function() {
		var menus,
			icon = this.options.icons.submenu,
			submenus = this.element.find( this.options.menus );

		// Initialize nested menus
		submenus.filter( ":not(.ui-menu)" )
			.addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
			.hide()
			.attr({
				role: this.options.role,
				"aria-hidden": "true",
				"aria-expanded": "false"
			})
			.each(function() {
				var menu = $( this ),
					item = menu.prev( "a" ),
					submenuCarat = $( "<span>" )
						.addClass( "ui-menu-icon ui-icon " + icon )
						.data( "ui-menu-submenu-carat", true );

				item
					.attr( "aria-haspopup", "true" )
					.prepend( submenuCarat );
				menu.attr( "aria-labelledby", item.attr( "id" ) );
			});

		menus = submenus.add( this.element );

		// Don't refresh list items that are already adapted
		menus.children( ":not(.ui-menu-item):has(a)" )
			.addClass( "ui-menu-item" )
			.attr( "role", "presentation" )
			.children( "a" )
				.uniqueId()
				.addClass( "ui-corner-all" )
				.attr({
					tabIndex: -1,
					role: this._itemRole()
				});

		// Initialize unlinked menu-items containing spaces and/or dashes only as dividers
		menus.children( ":not(.ui-menu-item)" ).each(function() {
			var item = $( this );
			// hyphen, em dash, en dash
			if ( !/[^\-\u2014\u2013\s]/.test( item.text() ) ) {
				item.addClass( "ui-widget-content ui-menu-divider" );
			}
		});

		// Add aria-disabled attribute to any disabled menu item
		menus.children( ".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" ) {
			this.element.find( ".ui-menu-icon" )
				.removeClass( this.options.icons.submenu )
				.addClass( value.submenu );
		}
		this._super( key, value );
	},

	focus: function( event, item ) {
		var nested, focused;
		this.blur( event, event && event.type === "focus" );

		this._scrollIntoView( item );

		this.active = item.first();
		focused = this.active.children( "a" ).addClass( "ui-state-focus" );
		// 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
		this.active
			.parent()
			.closest( ".ui-menu-item" )
			.children( "a:first" )
			.addClass( "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 && ( /^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.height();

			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.active.children( "a" ).removeClass( "ui-state-focus" );
		this.active = null;

		this._trigger( "blur", event, { item: this.active } );
	},

	_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 carat 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 );
			this.activeMenu = currentMenu;
		}, this.delay );
	},

	// With no arguments, closes the currently active menu - if nothing is active
	// it closes all menus.  If passed an argument, it will search for menus BELOW
	_close: function( startMenu ) {
		if ( !startMenu ) {
			startMenu = this.active ? this.active.parent() : this.element;
		}

		startMenu
			.find( ".ui-menu" )
				.hide()
				.attr( "aria-hidden", "true" )
				.attr( "aria-expanded", "false" )
			.end()
			.find( "a.ui-state-active" )
				.removeClass( "ui-state-active" );
	},

	collapse: function( event ) {
		var newItem = this.active &&
			this.active.parent().closest( ".ui-menu-item", this.element );
		if ( newItem && newItem.length ) {
			this._close();
			this.focus( event, newItem );
		}
	},

	expand: function( event ) {
		var newItem = this.active &&
			this.active
				.children( ".ui-menu " )
				.children( ".ui-menu-item" )
				.first();

		if ( newItem && newItem.length ) {
			this._open( newItem.parent() );

			// Delay so Firefox will not hide activedescendant change in expanding submenu from AT
			this._delay(function() {
				this.focus( event, newItem );
			});
		}
	},

	next: function( event ) {
		this._move( "next", "first", event );
	},

	previous: function( event ) {
		this._move( "prev", "last", event );
	},

	isFirstItem: function() {
		return this.active && !this.active.prevAll( ".ui-menu-item" ).length;
	},

	isLastItem: function() {
		return this.active && !this.active.nextAll( ".ui-menu-item" ).length;
	},

	_move: function( direction, filter, event ) {
		var next;
		if ( this.active ) {
			if ( direction === "first" || direction === "last" ) {
				next = this.active
					[ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" )
					.eq( -1 );
			} else {
				next = this.active
					[ direction + "All" ]( ".ui-menu-item" )
					.eq( 0 );
			}
		}
		if ( !next || !next.length || !this.active ) {
			next = this.activeMenu.children( ".ui-menu-item" )[ filter ]();
		}

		this.focus( event, next );
	},

	nextPage: function( event ) {
		var item, base, height;

		if ( !this.active ) {
			this.next( event );
			return;
		}
		if ( this.isLastItem() ) {
			return;
		}
		if ( this._hasScroll() ) {
			base = this.active.offset().top;
			height = this.element.height();
			this.active.nextAll( ".ui-menu-item" ).each(function() {
				item = $( this );
				return item.offset().top - base - height < 0;
			});

			this.focus( event, item );
		} else {
			this.focus( event, this.activeMenu.children( ".ui-menu-item" )
				[ !this.active ? "first" : "last" ]() );
		}
	},

	previousPage: function( event ) {
		var item, base, height;
		if ( !this.active ) {
			this.next( event );
			return;
		}
		if ( this.isFirstItem() ) {
			return;
		}
		if ( this._hasScroll() ) {
			base = this.active.offset().top;
			height = this.element.height();
			this.active.prevAll( ".ui-menu-item" ).each(function() {
				item = $( this );
				return item.offset().top - base + height > 0;
			});

			this.focus( event, item );
		} else {
			this.focus( event, this.activeMenu.children( ".ui-menu-item" ).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 );
	}
});

}( jQuery ));
(function( $, undefined ) {

$.widget( "ui.progressbar", {
	version: "1.10.3",
	options: {
		max: 100,
		value: 0,

		change: null,
		complete: null
	},

	min: 0,

	_create: function() {
		// Constrain initial value
		this.oldValue = this.options.value = this._constrainedValue();

		this.element
			.addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
			.attr({
				// Only set static values, aria-valuenow and aria-valuemax are
				// set inside _refreshValue()
				role: "progressbar",
				"aria-valuemin": this.min
			});

		this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" )
			.appendTo( this.element );

		this._refreshValue();
	},

	_destroy: function() {
		this.element
			.removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
			.removeAttr( "role" )
			.removeAttr( "aria-valuemin" )
			.removeAttr( "aria-valuemax" )
			.removeAttr( "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 );
	},

	_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 )
			.toggleClass( "ui-corner-right", value === this.options.max )
			.width( percentage.toFixed(0) + "%" );

		this.element.toggleClass( "ui-progressbar-indeterminate", this.indeterminate );

		if ( this.indeterminate ) {
			this.element.removeAttr( "aria-valuenow" );
			if ( !this.overlayDiv ) {
				this.overlayDiv = $( "<div class='ui-progressbar-overlay'></div>" ).appendTo( this.valueDiv );
			}
		} 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 );
(function( $, undefined ) {

// number of pages in a slider
// (how many times can you page up/down to go through the whole range)
var numPages = 5;

$.widget( "ui.slider", $.ui.mouse, {
	version: "1.10.3",
	widgetEventPrefix: "slide",

	options: {
		animate: false,
		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
	},

	_create: function() {
		this._keySliding = false;
		this._mouseSliding = false;
		this._animateOff = true;
		this._handleIndex = null;
		this._detectOrientation();
		this._mouseInit();

		this.element
			.addClass( "ui-slider" +
				" ui-slider-" + this.orientation +
				" ui-widget" +
				" ui-widget-content" +
				" ui-corner-all");

		this._refresh();
		this._setOption( "disabled", this.options.disabled );

		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" ).addClass( "ui-state-default ui-corner-all" ),
			handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",
			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.handle = this.handles.eq( 0 );

		this.handles.each(function( i ) {
			$( this ).data( "ui-slider-handle-index", i );
		});
	},

	_createRange: function() {
		var options = this.options,
			classes = "";

		if ( options.range ) {
			if ( options.range === true ) {
				if ( !options.values ) {
					options.values = [ this._valueMin(), this._valueMin() ];
				} else if ( options.values.length && options.values.length !== 2 ) {
					options.values = [ options.values[0], options.values[0] ];
				} else if ( $.isArray( options.values ) ) {
					options.values = options.values.slice(0);
				}
			}

			if ( !this.range || !this.range.length ) {
				this.range = $( "<div></div>" )
					.appendTo( this.element );

				classes = "ui-slider-range" +
				// note: this isn't the most fittingly semantic framework class for this element,
				// but worked best visually with a variety of themes
				" ui-widget-header ui-corner-all";
			} else {
				this.range.removeClass( "ui-slider-range-min ui-slider-range-max" )
					// Handle range switching from true to min/max
					.css({
						"left": "",
						"bottom": ""
					});
			}

			this.range.addClass( classes +
				( ( options.range === "min" || options.range === "max" ) ? " ui-slider-range-" + options.range : "" ) );
		} else {
			this.range = $([]);
		}
	},

	_setupEvents: function() {
		var elements = this.handles.add( this.range ).filter( "a" );
		this._off( elements );
		this._on( elements, this._handleEvents );
		this._hoverable( elements );
		this._focusable( elements );
	},

	_destroy: function() {
		this.handles.remove();
		this.range.remove();

		this.element
			.removeClass( "ui-slider" +
				" ui-slider-horizontal" +
				" ui-slider-vertical" +
				" ui-widget" +
				" ui-widget-content" +
				" ui-corner-all" );

		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;

		closestHandle
			.addClass( "ui-state-active" )
			.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.handles.removeClass( "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 );
	},

	_start: function( event, index ) {
		var uiHash = {
			handle: this.handles[ index ],
			value: this.value()
		};
		if ( this.options.values && this.options.values.length ) {
			uiHash.value = this.values( index );
			uiHash.values = this.values();
		}
		return this._trigger( "start", event, uiHash );
	},

	_slide: function( event, index, newVal ) {
		var otherVal,
			newValues,
			allowed;

		if ( this.options.values && this.options.values.length ) {
			otherVal = this.values( index ? 0 : 1 );

			if ( ( this.options.values.length === 2 && this.options.range === true ) &&
					( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) )
				) {
				newVal = otherVal;
			}

			if ( newVal !== this.values( index ) ) {
				newValues = this.values();
				newValues[ index ] = newVal;
				// A slide can be canceled by returning false from the slide callback
				allowed = this._trigger( "slide", event, {
					handle: this.handles[ index ],
					value: newVal,
					values: newValues
				} );
				otherVal = this.values( index ? 0 : 1 );
				if ( allowed !== false ) {
					this.values( index, newVal, true );
				}
			}
		} else {
			if ( newVal !== this.value() ) {
				// A slide can be canceled by returning false from the slide callback
				allowed = this._trigger( "slide", event, {
					handle: this.handles[ index ],
					value: newVal
				} );
				if ( allowed !== false ) {
					this.value( newVal );
				}
			}
		}
	},

	_stop: function( event, index ) {
		var uiHash = {
			handle: this.handles[ index ],
			value: this.value()
		};
		if ( this.options.values && this.options.values.length ) {
			uiHash.value = this.values( index );
			uiHash.values = this.values();
		}

		this._trigger( "stop", event, uiHash );
	},

	_change: function( event, index ) {
		if ( !this._keySliding && !this._mouseSliding ) {
			var uiHash = {
				handle: this.handles[ index ],
				value: this.value()
			};
			if ( this.options.values && this.options.values.length ) {
				uiHash.value = this.values( index );
				uiHash.values = this.values();
			}

			//store the last changed value index for reference when handles overlap
			this._lastChangedValue = index;

			this._trigger( "change", event, uiHash );
		}
	},

	value: function( newValue ) {
		if ( arguments.length ) {
			this.options.value = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, 0 );
			return;
		}

		return this._value();
	},

	values: function( index, newValue ) {
		var vals,
			newValues,
			i;

		if ( arguments.length > 1 ) {
			this.options.values[ index ] = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, index );
			return;
		}

		if ( arguments.length ) {
			if ( $.isArray( arguments[ 0 ] ) ) {
				vals = this.options.values;
				newValues = arguments[ 0 ];
				for ( i = 0; i < vals.length; i += 1 ) {
					vals[ i ] = this._trimAlignValue( newValues[ i ] );
					this._change( null, i );
				}
				this._refreshValue();
			} else {
				if ( this.options.values && this.options.values.length ) {
					return this._values( index );
				} else {
					return this.value();
				}
			}
		} else {
			return this._values();
		}
	},

	_setOption: function( key, value ) {
		var i,
			valsLength = 0;

		if ( key === "range" && this.options.range === true ) {
			if ( value === "min" ) {
				this.options.value = this._values( 0 );
				this.options.values = null;
			} else if ( value === "max" ) {
				this.options.value = this._values( this.options.values.length-1 );
				this.options.values = null;
			}
		}

		if ( $.isArray( this.options.values ) ) {
			valsLength = this.options.values.length;
		}

		$.Widget.prototype._setOption.apply( this, arguments );

		switch ( key ) {
			case "orientation":
				this._detectOrientation();
				this.element
					.removeClass( "ui-slider-horizontal ui-slider-vertical" )
					.addClass( "ui-slider-" + this.orientation );
				this._refreshValue();
				break;
			case "value":
				this._animateOff = true;
				this._refreshValue();
				this._change( null, 0 );
				this._animateOff = false;
				break;
			case "values":
				this._animateOff = true;
				this._refreshValue();
				for ( i = 0; i < valsLength; i += 1 ) {
					this._change( null, i );
				}
				this._animateOff = false;
				break;
			case "min":
			case "max":
				this._animateOff = true;
				this._refreshValue();
				this._animateOff = false;
				break;
			case "range":
				this._animateOff = true;
				this._refresh();
				this._animateOff = false;
				break;
		}
	},

	//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.options.values && this.options.values.length ) {
			// .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) );
	},

	_valueMin: function() {
		return this.options.min;
	},

	_valueMax: function() {
		return this.options.max;
	},

	_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.options.values && this.options.values.length ) {
			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[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: 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[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
			}
		}
	},

	_handleEvents: {
		keydown: function( event ) {
			/*jshint maxcomplexity:25*/
			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;
						$( event.target ).addClass( "ui-state-active" );
						allowed = this._start( event, index );
						if ( allowed === false ) {
							return;
						}
					}
					break;
			}

			step = this.options.step;
			if ( this.options.values && this.options.values.length ) {
				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()) / numPages ) );
					break;
				case $.ui.keyCode.PAGE_DOWN:
					newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / 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 );
		},
		click: function( event ) {
			event.preventDefault();
		},
		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 );
				$( event.target ).removeClass( "ui-state-active" );
			}
		}
	}

});

}(jQuery));
(function( $ ) {

function modifier( 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.10.3",
	defaultElement: "<input>",
	widgetEventPrefix: "spin",
	options: {
		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 );

		// 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 = {},
			element = this.element;

		$.each( [ "min", "max", "step" ], function( i, option ) {
			var value = element.attr( option );
			if ( value !== undefined && 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 ) {
			if ( this.cancelBlur ) {
				delete this.cancelBlur;
				return;
			}

			this._stop();
			this._refresh();
			if ( this.previous !== this.element.val() ) {
				this._trigger( "change", event );
			}
		},
		mousewheel: function( event, delta ) {
			if ( !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();
		},
		"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.focus();
					this.previous = previous;
					// support: IE
					// IE sets focus asynchronously, so we need to check if focus
					// moved off of the input because the user clicked on the button.
					this._delay(function() {
						this.previous = previous;
					});
				}
			}

			// ensure focus is on (or stays on) the text field
			event.preventDefault();
			checkFocus.call( this );

			// support: IE
			// IE doesn't prevent moving focus even with event.preventDefault()
			// so we set a flag to know when we should ignore the blur event
			// and check (again) if focus moved off of the input.
			this.cancelBlur = true;
			this._delay(function() {
				delete this.cancelBlur;
				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"
	},

	_draw: function() {
		var uiSpinner = this.uiSpinner = this.element
			.addClass( "ui-spinner-input" )
			.attr( "autocomplete", "off" )
			.wrap( this._uiSpinnerHtml() )
			.parent()
				// add buttons
				.append( this._buttonHtml() );

		this.element.attr( "role", "spinbutton" );

		// button bindings
		this.buttons = uiSpinner.find( ".ui-spinner-button" )
			.attr( "tabIndex", -1 )
			.button()
			.removeClass( "ui-corner-all" );

		// IE 6 doesn't understand height: 50% for the buttons
		// unless the wrapper has an explicit height
		if ( this.buttons.height() > Math.ceil( uiSpinner.height() * 0.5 ) &&
				uiSpinner.height() > 0 ) {
			uiSpinner.height( uiSpinner.height() );
		}

		// disable spinner if element was already disabled
		if ( this.options.disabled ) {
			this.disable();
		}
	},

	_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;
	},

	_uiSpinnerHtml: function() {
		return "<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>";
	},

	_buttonHtml: function() {
		return "" +
			"<a class='ui-spinner-button ui-spinner-up ui-corner-tr'>" +
				"<span class='ui-icon " + this.options.icons.up + "'>&#9650;</span>" +
			"</a>" +
			"<a class='ui-spinner-button ui-spinner-down ui-corner-br'>" +
				"<span class='ui-icon " + this.options.icons.down + "'>&#9660;</span>" +
			"</a>";
	},

	_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 $.isFunction( incremental ) ?
				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 ) {
		if ( key === "culture" || key === "numberFormat" ) {
			var 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" ) {
			this.buttons.first().find( ".ui-icon" )
				.removeClass( this.options.icons.up )
				.addClass( value.up );
			this.buttons.last().find( ".ui-icon" )
				.removeClass( this.options.icons.down )
				.addClass( value.down );
		}

		this._super( key, value );

		if ( key === "disabled" ) {
			if ( value ) {
				this.element.prop( "disabled", true );
				this.buttons.button( "disable" );
			} else {
				this.element.prop( "disabled", false );
				this.buttons.button( "enable" );
			}
		}
	},

	_setOptions: modifier(function( options ) {
		this._super( options );
		this._value( this.element.val() );
	}),

	_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() )
		});
	},

	// 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
			.removeClass( "ui-spinner-input" )
			.prop( "disabled", false )
			.removeAttr( "autocomplete" )
			.removeAttr( "role" )
			.removeAttr( "aria-valuemin" )
			.removeAttr( "aria-valuemax" )
			.removeAttr( "aria-valuenow" );
		this.uiSpinner.replaceWith( this.element );
	},

	stepUp: modifier(function( steps ) {
		this._stepUp( steps );
	}),
	_stepUp: function( steps ) {
		if ( this._start() ) {
			this._spin( (steps || 1) * this.options.step );
			this._stop();
		}
	},

	stepDown: modifier(function( steps ) {
		this._stepDown( steps );
	}),
	_stepDown: function( steps ) {
		if ( this._start() ) {
			this._spin( (steps || 1) * -this.options.step );
			this._stop();
		}
	},

	pageUp: modifier(function( pages ) {
		this._stepUp( (pages || 1) * this.options.page );
	}),

	pageDown: modifier(function( pages ) {
		this._stepDown( (pages || 1) * this.options.page );
	}),

	value: function( newVal ) {
		if ( !arguments.length ) {
			return this._parse( this.element.val() );
		}
		modifier( this._value ).call( this, newVal );
	},

	widget: function() {
		return this.uiSpinner;
	}
});

}( jQuery ) );
(function( $, undefined ) {

var tabId = 0,
	rhash = /#.*$/;

function getNextTabId() {
	return ++tabId;
}

function isLocal( anchor ) {
	return anchor.hash.length > 1 &&
		decodeURIComponent( anchor.href.replace( rhash, "" ) ) ===
			decodeURIComponent( location.href.replace( rhash, "" ) );
}

$.widget( "ui.tabs", {
	version: "1.10.3",
	delay: 300,
	options: {
		active: null,
		collapsible: false,
		event: "click",
		heightStyle: "content",
		hide: null,
		show: null,

		// callbacks
		activate: null,
		beforeActivate: null,
		beforeLoad: null,
		load: null
	},

	_create: function() {
		var that = this,
			options = this.options;

		this.running = false;

		this.element
			.addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" )
			.toggleClass( "ui-tabs-collapsible", options.collapsible )
			// Prevent users from focusing disabled tabs via click
			.delegate( ".ui-tabs-nav > li", "mousedown" + this.eventNamespace, function( event ) {
				if ( $( this ).is( ".ui-state-disabled" ) ) {
					event.preventDefault();
				}
			})
			// support: IE <9
			// Preventing the default action in mousedown doesn't prevent IE
			// from focusing the element, so if the anchor gets focused, blur.
			// We don't have to worry about focusing the previously focused
			// element since clicking on a non-focusable element should focus
			// the body anyway.
			.delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() {
				if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) {
					this.blur();
				}
			});

		this._processTabs();
		options.active = this._initialActive();

		// Take disabling tabs via class attribute from HTML
		// into account and update option properly.
		if ( $.isArray( options.disabled ) ) {
			options.disabled = $.unique( 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 );

		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;
					}
				});
			}

			// 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 ) {
		/*jshint maxcomplexity:15*/
		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 key will prevent automatic activation
		if ( !event.ctrlKey ) {
			// 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.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 ).focus();
		return index;
	},

	_setOption: function( key, value ) {
		if ( key === "active" ) {
			// _activate() will handle invalid values and update this.options
			this._activate( value );
			return;
		}

		if ( key === "disabled" ) {
			// don't use the widget factory's disabled handling
			this._setupDisabled( value );
			return;
		}

		this._super( key, value);

		if ( key === "collapsible" ) {
			this.element.toggleClass( "ui-tabs-collapsible", 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 );
		}
	},

	_tabId: function( tab ) {
		return tab.attr( "aria-controls" ) || "ui-tabs-" + getNextTabId();
	},

	_sanitizeSelector: function( hash ) {
		return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : "";
	},

	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._setupDisabled( this.options.disabled );
		this._setupEvents( this.options.event );
		this._setupHeightStyle( this.options.heightStyle );

		this.tabs.not( this.active ).attr({
			"aria-selected": "false",
			tabIndex: -1
		});
		this.panels.not( this._getPanelForTab( this.active ) )
			.hide()
			.attr({
				"aria-expanded": "false",
				"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
				.addClass( "ui-tabs-active ui-state-active" )
				.attr({
					"aria-selected": "true",
					tabIndex: 0
				});
			this._getPanelForTab( this.active )
				.show()
				.attr({
					"aria-expanded": "true",
					"aria-hidden": "false"
				});
		}
	},

	_processTabs: function() {
		var that = this;

		this.tablist = this._getList()
			.addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" )
			.attr( "role", "tablist" );

		this.tabs = this.tablist.find( "> li:has(a[href])" )
			.addClass( "ui-state-default ui-corner-top" )
			.attr({
				role: "tab",
				tabIndex: -1
			});

		this.anchors = this.tabs.map(function() {
				return $( "a", this )[ 0 ];
			})
			.addClass( "ui-tabs-anchor" )
			.attr({
				role: "presentation",
				tabIndex: -1
			});

		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 ( isLocal( anchor ) ) {
				selector = anchor.hash;
				panel = that.element.find( that._sanitizeSelector( selector ) );
			// remote tab
			} else {
				panelId = that._tabId( tab );
				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": selector.substring( 1 ),
				"aria-labelledby": anchorId
			});
			panel.attr( "aria-labelledby", anchorId );
		});

		this.panels
			.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
			.attr( "role", "tabpanel" );
	},

	// allow overriding how to find the list for rare usage scenarios (#7715)
	_getList: function() {
		return this.element.find( "ol,ul" ).eq( 0 );
	},

	_createPanel: function( id ) {
		return $( "<div>" )
			.attr( "id", id )
			.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
			.data( "ui-tabs-destroy", true );
	},

	_setupDisabled: function( disabled ) {
		if ( $.isArray( disabled ) ) {
			if ( !disabled.length ) {
				disabled = false;
			} else if ( disabled.length === this.anchors.length ) {
				disabled = true;
			}
		}

		// disable tabs
		for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) {
			if ( disabled === true || $.inArray( i, disabled ) !== -1 ) {
				$( li )
					.addClass( "ui-state-disabled" )
					.attr( "aria-disabled", "true" );
			} else {
				$( li )
					.removeClass( "ui-state-disabled" )
					.removeAttr( "aria-disabled" );
			}
		}

		this.options.disabled = disabled;
	},

	_setupEvents: function( event ) {
		var events = {
			click: function( event ) {
				event.preventDefault();
			}
		};
		if ( event ) {
			$.each( event.split(" "), function( index, eventName ) {
				events[ eventName ] = "_eventHandler";
			});
		}

		this._off( this.anchors.add( this.tabs ).add( this.panels ) );
		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() {
			eventData.newTab.closest( "li" ).addClass( "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() {
				eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
				show();
			});
		} else {
			eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
			toHide.hide();
			show();
		}

		toHide.attr({
			"aria-expanded": "false",
			"aria-hidden": "true"
		});
		eventData.oldTab.attr( "aria-selected", "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-expanded": "true",
			"aria-hidden": "false"
		});
		eventData.newTab.attr({
			"aria-selected": "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$='" + index + "']" ) );
		}

		return index;
	},

	_destroy: function() {
		if ( this.xhr ) {
			this.xhr.abort();
		}

		this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" );

		this.tablist
			.removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" )
			.removeAttr( "role" );

		this.anchors
			.removeClass( "ui-tabs-anchor" )
			.removeAttr( "role" )
			.removeAttr( "tabIndex" )
			.removeUniqueId();

		this.tabs.add( this.panels ).each(function() {
			if ( $.data( this, "ui-tabs-destroy" ) ) {
				$( this ).remove();
			} else {
				$( this )
					.removeClass( "ui-state-default ui-state-active ui-state-disabled " +
						"ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" )
					.removeAttr( "tabIndex" )
					.removeAttr( "aria-live" )
					.removeAttr( "aria-busy" )
					.removeAttr( "aria-selected" )
					.removeAttr( "aria-labelledby" )
					.removeAttr( "aria-hidden" )
					.removeAttr( "aria-expanded" )
					.removeAttr( "role" );
			}
		});

		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 ( $.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._setupDisabled( 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 ( $.isArray( disabled ) ) {
				disabled = $.merge( [ index ], disabled ).sort();
			} else {
				disabled = [ index ];
			}
		}
		this._setupDisabled( 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
			};

		// not remote
		if ( isLocal( anchor[ 0 ] ) ) {
			return;
		}

		this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) );

		// support: jQuery <1.8
		// jQuery <1.8 returns false if the request is canceled in beforeSend,
		// but as of 1.8, $.ajax() always returns a jqXHR object.
		if ( this.xhr && this.xhr.statusText !== "canceled" ) {
			tab.addClass( "ui-tabs-loading" );
			panel.attr( "aria-busy", "true" );

			this.xhr
				.success(function( response ) {
					// support: jQuery <1.8
					// http://bugs.jquery.com/ticket/11778
					setTimeout(function() {
						panel.html( response );
						that._trigger( "load", event, eventData );
					}, 1 );
				})
				.complete(function( jqXHR, status ) {
					// support: jQuery <1.8
					// http://bugs.jquery.com/ticket/11778
					setTimeout(function() {
						if ( status === "abort" ) {
							that.panels.stop( false, true );
						}

						tab.removeClass( "ui-tabs-loading" );
						panel.removeAttr( "aria-busy" );

						if ( jqXHR === that.xhr ) {
							delete that.xhr;
						}
					}, 1 );
				});
		}
	},

	_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( this._sanitizeSelector( "#" + id ) );
	}
});

})( jQuery );
(function( $ ) {

var increments = 0;

function addDescribedBy( elem, id ) {
	var describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ );
	describedby.push( id );
	elem
		.data( "ui-tooltip-id", id )
		.attr( "aria-describedby", $.trim( describedby.join( " " ) ) );
}

function removeDescribedBy( elem ) {
	var id = elem.data( "ui-tooltip-id" ),
		describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ),
		index = $.inArray( id, describedby );
	if ( index !== -1 ) {
		describedby.splice( index, 1 );
	}

	elem.removeData( "ui-tooltip-id" );
	describedby = $.trim( describedby.join( " " ) );
	if ( describedby ) {
		elem.attr( "aria-describedby", describedby );
	} else {
		elem.removeAttr( "aria-describedby" );
	}
}

$.widget( "ui.tooltip", {
	version: "1.10.3",
	options: {
		content: function() {
			// support: IE<9, Opera in jQuery <1.7
			// .text() can't accept undefined, so coerce to a string
			var title = $( this ).attr( "title" ) || "";
			// Escape title, since we're going from an attribute to raw HTML
			return $( "<a>" ).text( title ).html();
		},
		hide: true,
		// Disabled elements have inconsistent behavior across browsers (#8661)
		items: "[title]:not([disabled])",
		position: {
			my: "left top+15",
			at: "left bottom",
			collision: "flipfit flip"
		},
		show: true,
		tooltipClass: null,
		track: false,

		// callbacks
		close: null,
		open: null
	},

	_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 = {};

		if ( this.options.disabled ) {
			this._disable();
		}
	},

	_setOption: function( key, value ) {
		var that = this;

		if ( key === "disabled" ) {
			this[ value ? "_disable" : "_enable" ]();
			this.options[ key ] = value;
			// disable element style changes
			return;
		}

		this._super( key, value );

		if ( key === "content" ) {
			$.each( this.tooltips, function( id, element ) {
				that._updateContent( element );
			});
		}
	},

	_disable: function() {
		var that = this;

		// close open tooltips
		$.each( this.tooltips, function( id, element ) {
			var event = $.Event( "blur" );
			event.target = event.currentTarget = element[0];
			that.close( event, true );
		});

		// remove title attributes to prevent native tooltips
		this.element.find( this.options.items ).addBack().each(function() {
			var element = $( this );
			if ( element.is( "[title]" ) ) {
				element
					.data( "ui-tooltip-title", element.attr( "title" ) )
					.attr( "title", "" );
			}
		});
	},

	_enable: function() {
		// restore title attributes
		this.element.find( this.options.items ).addBack().each(function() {
			var element = $( this );
			if ( element.data( "ui-tooltip-title" ) ) {
				element.attr( "title", element.data( "ui-tooltip-title" ) );
			}
		});
	},

	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._updateContent( target, event );
	},

	_updateContent: function( target, event ) {
		var content,
			contentOption = this.options.content,
			that = this,
			eventType = event ? event.type : null;

		if ( typeof contentOption === "string" ) {
			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;
			}
			// IE may instantly serve a cached response for ajax requests
			// delay this call to _open so the other call to _open runs first
			that._delay(function() {
				// jQuery creates a special event for focusin when it doesn't
				// exist natively. To improve performance, the native event
				// object is reused and the type is changed. Therefore, we can't
				// rely on the type being correct after the event finished
				// bubbling, so we set it back to the previous value. (#8740)
				if ( event ) {
					event.type = eventType;
				}
				this._open( event, target, response );
			});
		});
		if ( content ) {
			this._open( event, target, content );
		}
	},

	_open: function( event, target, content ) {
		var tooltip, events, delayedShow,
			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.
		tooltip = this._find( target );
		if ( tooltip.length ) {
			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" );
			}
		}

		tooltip = this._tooltip( target );
		addDescribedBy( target, tooltip.attr( "id" ) );
		tooltip.find( ".ui-tooltip-content" ).html( content );

		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.
		if ( this.options.show && this.options.show.delay ) {
			delayedShow = this.delayedShow = setInterval(function() {
				if ( tooltip.is( ":visible" ) ) {
					position( positionOption.of );
					clearInterval( delayedShow );
				}
			}, $.fx.interval );
		}

		this._trigger( "open", event, { tooltip: tooltip } );

		events = {
			keyup: function( event ) {
				if ( event.keyCode === $.ui.keyCode.ESCAPE ) {
					var fakeEvent = $.Event(event);
					fakeEvent.currentTarget = target[0];
					this.close( fakeEvent, true );
				}
			},
			remove: function() {
				this._removeTooltip( 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 that = this,
			target = $( event ? event.currentTarget : this.element ),
			tooltip = this._find( target );

		// 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 ( this.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 ( target.data( "ui-tooltip-title" ) ) {
			target.attr( "title", target.data( "ui-tooltip-title" ) );
		}

		removeDescribedBy( target );

		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 ];
			});
		}

		this.closing = true;
		this._trigger( "close", event, { tooltip: tooltip } );
		this.closing = false;
	},

	_tooltip: function( element ) {
		var id = "ui-tooltip-" + increments++,
			tooltip = $( "<div>" )
				.attr({
					id: id,
					role: "tooltip"
				})
				.addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content " +
					( this.options.tooltipClass || "" ) );
		$( "<div>" )
			.addClass( "ui-tooltip-content" )
			.appendTo( tooltip );
		tooltip.appendTo( this.document[0].body );
		this.tooltips[ id ] = element;
		return tooltip;
	},

	_find: function( target ) {
		var id = target.data( "ui-tooltip-id" );
		return id ? $( "#" + id ) : $();
	},

	_removeTooltip: function( tooltip ) {
		tooltip.remove();
		delete this.tooltips[ tooltip.attr( "id" ) ];
	},

	_destroy: function() {
		var that = this;

		// close open tooltips
		$.each( this.tooltips, function( id, element ) {
			// Delegate to close method to handle common cleanup
			var event = $.Event( "blur" );
			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" ) ) {
				element.attr( "title", element.data( "ui-tooltip-title" ) );
				element.removeData( "ui-tooltip-title" );
			}
		});
	}
});

}( jQuery ) );
(function($, undefined) {

var dataSpace = "ui-effects-";

$.effects = {
	effect: {}
};

/*!
 * jQuery Color Animations v2.1.2
 * https://github.com/jquery/jquery-color
 *
 * Copyright 2013 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * Date: Wed Jan 16 08:47:09 2013 -0600
 */
(function( jQuery, undefined ) {

	var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",

	// plusequals test for += 100 -= 100
	rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,
	// a set of RE's that can match strings and generate color tuples.
	stringParsers = [{
			re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			parse: function( execResult ) {
				return [
					execResult[ 1 ],
					execResult[ 2 ],
					execResult[ 3 ],
					execResult[ 4 ]
				];
			}
		}, {
			re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			parse: function( execResult ) {
				return [
					execResult[ 1 ] * 2.55,
					execResult[ 2 ] * 2.55,
					execResult[ 3 ] * 2.55,
					execResult[ 4 ]
				];
			}
		}, {
			// this regex ignores A-F because it's compared against an already lowercased string
			re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,
			parse: function( execResult ) {
				return [
					parseInt( execResult[ 1 ], 16 ),
					parseInt( execResult[ 2 ], 16 ),
					parseInt( execResult[ 3 ], 16 )
				];
			}
		}, {
			// this regex ignores A-F because it's compared against an already lowercased string
			re: /#([a-f0-9])([a-f0-9])([a-f0-9])/,
			parse: function( execResult ) {
				return [
					parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ),
					parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ),
					parseInt( execResult[ 3 ] + execResult[ 3 ], 16 )
				];
			}
		}, {
			re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			space: "hsla",
			parse: function( execResult ) {
				return [
					execResult[ 1 ],
					execResult[ 2 ] / 100,
					execResult[ 3 ] / 100,
					execResult[ 4 ]
				];
			}
		}],

	// jQuery.Color( )
	color = jQuery.Color = function( color, green, blue, alpha ) {
		return new jQuery.Color.fn.parse( color, green, blue, alpha );
	},
	spaces = {
		rgba: {
			props: {
				red: {
					idx: 0,
					type: "byte"
				},
				green: {
					idx: 1,
					type: "byte"
				},
				blue: {
					idx: 2,
					type: "byte"
				}
			}
		},

		hsla: {
			props: {
				hue: {
					idx: 0,
					type: "degrees"
				},
				saturation: {
					idx: 1,
					type: "percent"
				},
				lightness: {
					idx: 2,
					type: "percent"
				}
			}
		}
	},
	propTypes = {
		"byte": {
			floor: true,
			max: 255
		},
		"percent": {
			max: 1
		},
		"degrees": {
			mod: 360,
			floor: true
		}
	},
	support = color.support = {},

	// element for support tests
	supportElem = jQuery( "<p>" )[ 0 ],

	// colors = jQuery.Color.names
	colors,

	// local aliases of functions called often
	each = jQuery.each;

// determine rgba support immediately
supportElem.style.cssText = "background-color:rgba(1,1,1,.5)";
support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1;

// define cache name and alpha properties
// for rgba and hsla spaces
each( spaces, function( spaceName, space ) {
	space.cache = "_" + spaceName;
	space.props.alpha = {
		idx: 3,
		type: "percent",
		def: 1
	};
});

function clamp( value, prop, allowEmpty ) {
	var type = propTypes[ prop.type ] || {};

	if ( value == null ) {
		return (allowEmpty || !prop.def) ? null : prop.def;
	}

	// ~~ is an short way of doing floor for positive numbers
	value = type.floor ? ~~value : parseFloat( value );

	// IE will pass in empty strings as value for alpha,
	// which will hit this case
	if ( isNaN( value ) ) {
		return prop.def;
	}

	if ( type.mod ) {
		// we add mod before modding to make sure that negatives values
		// get converted properly: -10 -> 350
		return (value + type.mod) % type.mod;
	}

	// for now all property types without mod have min and max
	return 0 > value ? 0 : type.max < value ? type.max : value;
}

function stringParse( string ) {
	var inst = color(),
		rgba = inst._rgba = [];

	string = string.toLowerCase();

	each( stringParsers, function( i, parser ) {
		var parsed,
			match = parser.re.exec( string ),
			values = match && parser.parse( match ),
			spaceName = parser.space || "rgba";

		if ( values ) {
			parsed = inst[ spaceName ]( values );

			// if this was an rgba parse the assignment might happen twice
			// oh well....
			inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ];
			rgba = inst._rgba = parsed._rgba;

			// exit each( stringParsers ) here because we matched
			return false;
		}
	});

	// Found a stringParser that handled it
	if ( rgba.length ) {

		// if this came from a parsed string, force "transparent" when alpha is 0
		// chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
		if ( rgba.join() === "0,0,0,0" ) {
			jQuery.extend( rgba, colors.transparent );
		}
		return inst;
	}

	// named colors
	return colors[ string ];
}

color.fn = jQuery.extend( color.prototype, {
	parse: function( red, green, blue, alpha ) {
		if ( red === undefined ) {
			this._rgba = [ null, null, null, null ];
			return this;
		}
		if ( red.jquery || red.nodeType ) {
			red = jQuery( red ).css( green );
			green = undefined;
		}

		var inst = this,
			type = jQuery.type( red ),
			rgba = this._rgba = [];

		// more than 1 argument specified - assume ( red, green, blue, alpha )
		if ( green !== undefined ) {
			red = [ red, green, blue, alpha ];
			type = "array";
		}

		if ( type === "string" ) {
			return this.parse( stringParse( red ) || colors._default );
		}

		if ( type === "array" ) {
			each( spaces.rgba.props, function( key, prop ) {
				rgba[ prop.idx ] = clamp( red[ prop.idx ], prop );
			});
			return this;
		}

		if ( type === "object" ) {
			if ( red instanceof color ) {
				each( spaces, function( spaceName, space ) {
					if ( red[ space.cache ] ) {
						inst[ space.cache ] = red[ space.cache ].slice();
					}
				});
			} else {
				each( spaces, function( spaceName, space ) {
					var cache = space.cache;
					each( space.props, function( key, prop ) {

						// if the cache doesn't exist, and we know how to convert
						if ( !inst[ cache ] && space.to ) {

							// if the value was null, we don't need to copy it
							// if the key was alpha, we don't need to copy it either
							if ( key === "alpha" || red[ key ] == null ) {
								return;
							}
							inst[ cache ] = space.to( inst._rgba );
						}

						// this is the only case where we allow nulls for ALL properties.
						// call clamp with alwaysAllowEmpty
						inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true );
					});

					// everything defined but alpha?
					if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) {
						// use the default of 1
						inst[ cache ][ 3 ] = 1;
						if ( space.from ) {
							inst._rgba = space.from( inst[ cache ] );
						}
					}
				});
			}
			return this;
		}
	},
	is: function( compare ) {
		var is = color( compare ),
			same = true,
			inst = this;

		each( spaces, function( _, space ) {
			var localCache,
				isCache = is[ space.cache ];
			if (isCache) {
				localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || [];
				each( space.props, function( _, prop ) {
					if ( isCache[ prop.idx ] != null ) {
						same = ( isCache[ prop.idx ] === localCache[ prop.idx ] );
						return same;
					}
				});
			}
			return same;
		});
		return same;
	},
	_space: function() {
		var used = [],
			inst = this;
		each( spaces, function( spaceName, space ) {
			if ( inst[ space.cache ] ) {
				used.push( spaceName );
			}
		});
		return used.pop();
	},
	transition: function( other, distance ) {
		var end = color( other ),
			spaceName = end._space(),
			space = spaces[ spaceName ],
			startColor = this.alpha() === 0 ? color( "transparent" ) : this,
			start = startColor[ space.cache ] || space.to( startColor._rgba ),
			result = start.slice();

		end = end[ space.cache ];
		each( space.props, function( key, prop ) {
			var index = prop.idx,
				startValue = start[ index ],
				endValue = end[ index ],
				type = propTypes[ prop.type ] || {};

			// if null, don't override start value
			if ( endValue === null ) {
				return;
			}
			// if null - use end
			if ( startValue === null ) {
				result[ index ] = endValue;
			} else {
				if ( type.mod ) {
					if ( endValue - startValue > type.mod / 2 ) {
						startValue += type.mod;
					} else if ( startValue - endValue > type.mod / 2 ) {
						startValue -= type.mod;
					}
				}
				result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop );
			}
		});
		return this[ spaceName ]( result );
	},
	blend: function( opaque ) {
		// if we are already opaque - return ourself
		if ( this._rgba[ 3 ] === 1 ) {
			return this;
		}

		var rgb = this._rgba.slice(),
			a = rgb.pop(),
			blend = color( opaque )._rgba;

		return color( jQuery.map( rgb, function( v, i ) {
			return ( 1 - a ) * blend[ i ] + a * v;
		}));
	},
	toRgbaString: function() {
		var prefix = "rgba(",
			rgba = jQuery.map( this._rgba, function( v, i ) {
				return v == null ? ( i > 2 ? 1 : 0 ) : v;
			});

		if ( rgba[ 3 ] === 1 ) {
			rgba.pop();
			prefix = "rgb(";
		}

		return prefix + rgba.join() + ")";
	},
	toHslaString: function() {
		var prefix = "hsla(",
			hsla = jQuery.map( this.hsla(), function( v, i ) {
				if ( v == null ) {
					v = i > 2 ? 1 : 0;
				}

				// catch 1 and 2
				if ( i && i < 3 ) {
					v = Math.round( v * 100 ) + "%";
				}
				return v;
			});

		if ( hsla[ 3 ] === 1 ) {
			hsla.pop();
			prefix = "hsl(";
		}
		return prefix + hsla.join() + ")";
	},
	toHexString: function( includeAlpha ) {
		var rgba = this._rgba.slice(),
			alpha = rgba.pop();

		if ( includeAlpha ) {
			rgba.push( ~~( alpha * 255 ) );
		}

		return "#" + jQuery.map( rgba, function( v ) {

			// default to 0 when nulls exist
			v = ( v || 0 ).toString( 16 );
			return v.length === 1 ? "0" + v : v;
		}).join("");
	},
	toString: function() {
		return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString();
	}
});
color.fn.parse.prototype = color.fn;

// hsla conversions adapted from:
// https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021

function hue2rgb( p, q, h ) {
	h = ( h + 1 ) % 1;
	if ( h * 6 < 1 ) {
		return p + (q - p) * h * 6;
	}
	if ( h * 2 < 1) {
		return q;
	}
	if ( h * 3 < 2 ) {
		return p + (q - p) * ((2/3) - h) * 6;
	}
	return p;
}

spaces.hsla.to = function ( rgba ) {
	if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) {
		return [ null, null, null, rgba[ 3 ] ];
	}
	var r = rgba[ 0 ] / 255,
		g = rgba[ 1 ] / 255,
		b = rgba[ 2 ] / 255,
		a = rgba[ 3 ],
		max = Math.max( r, g, b ),
		min = Math.min( r, g, b ),
		diff = max - min,
		add = max + min,
		l = add * 0.5,
		h, s;

	if ( min === max ) {
		h = 0;
	} else if ( r === max ) {
		h = ( 60 * ( g - b ) / diff ) + 360;
	} else if ( g === max ) {
		h = ( 60 * ( b - r ) / diff ) + 120;
	} else {
		h = ( 60 * ( r - g ) / diff ) + 240;
	}

	// chroma (diff) == 0 means greyscale which, by definition, saturation = 0%
	// otherwise, saturation is based on the ratio of chroma (diff) to lightness (add)
	if ( diff === 0 ) {
		s = 0;
	} else if ( l <= 0.5 ) {
		s = diff / add;
	} else {
		s = diff / ( 2 - add );
	}
	return [ Math.round(h) % 360, s, l, a == null ? 1 : a ];
};

spaces.hsla.from = function ( hsla ) {
	if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) {
		return [ null, null, null, hsla[ 3 ] ];
	}
	var h = hsla[ 0 ] / 360,
		s = hsla[ 1 ],
		l = hsla[ 2 ],
		a = hsla[ 3 ],
		q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s,
		p = 2 * l - q;

	return [
		Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ),
		Math.round( hue2rgb( p, q, h ) * 255 ),
		Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ),
		a
	];
};


each( spaces, function( spaceName, space ) {
	var props = space.props,
		cache = space.cache,
		to = space.to,
		from = space.from;

	// makes rgba() and hsla()
	color.fn[ spaceName ] = function( value ) {

		// generate a cache for this space if it doesn't exist
		if ( to && !this[ cache ] ) {
			this[ cache ] = to( this._rgba );
		}
		if ( value === undefined ) {
			return this[ cache ].slice();
		}

		var ret,
			type = jQuery.type( value ),
			arr = ( type === "array" || type === "object" ) ? value : arguments,
			local = this[ cache ].slice();

		each( props, function( key, prop ) {
			var val = arr[ type === "object" ? key : prop.idx ];
			if ( val == null ) {
				val = local[ prop.idx ];
			}
			local[ prop.idx ] = clamp( val, prop );
		});

		if ( from ) {
			ret = color( from( local ) );
			ret[ cache ] = local;
			return ret;
		} else {
			return color( local );
		}
	};

	// makes red() green() blue() alpha() hue() saturation() lightness()
	each( props, function( key, prop ) {
		// alpha is included in more than one space
		if ( color.fn[ key ] ) {
			return;
		}
		color.fn[ key ] = function( value ) {
			var vtype = jQuery.type( value ),
				fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ),
				local = this[ fn ](),
				cur = local[ prop.idx ],
				match;

			if ( vtype === "undefined" ) {
				return cur;
			}

			if ( vtype === "function" ) {
				value = value.call( this, cur );
				vtype = jQuery.type( value );
			}
			if ( value == null && prop.empty ) {
				return this;
			}
			if ( vtype === "string" ) {
				match = rplusequals.exec( value );
				if ( match ) {
					value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 );
				}
			}
			local[ prop.idx ] = value;
			return this[ fn ]( local );
		};
	});
});

// add cssHook and .fx.step function for each named hook.
// accept a space separated string of properties
color.hook = function( hook ) {
	var hooks = hook.split( " " );
	each( hooks, function( i, hook ) {
		jQuery.cssHooks[ hook ] = {
			set: function( elem, value ) {
				var parsed, curElem,
					backgroundColor = "";

				if ( value !== "transparent" && ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) ) {
					value = color( parsed || value );
					if ( !support.rgba && value._rgba[ 3 ] !== 1 ) {
						curElem = hook === "backgroundColor" ? elem.parentNode : elem;
						while (
							(backgroundColor === "" || backgroundColor === "transparent") &&
							curElem && curElem.style
						) {
							try {
								backgroundColor = jQuery.css( curElem, "backgroundColor" );
								curElem = curElem.parentNode;
							} catch ( e ) {
							}
						}

						value = value.blend( backgroundColor && backgroundColor !== "transparent" ?
							backgroundColor :
							"_default" );
					}

					value = value.toRgbaString();
				}
				try {
					elem.style[ hook ] = value;
				} catch( e ) {
					// wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit'
				}
			}
		};
		jQuery.fx.step[ hook ] = function( fx ) {
			if ( !fx.colorInit ) {
				fx.start = color( fx.elem, hook );
				fx.end = color( fx.end );
				fx.colorInit = true;
			}
			jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) );
		};
	});

};

color.hook( stepHooks );

jQuery.cssHooks.borderColor = {
	expand: function( value ) {
		var expanded = {};

		each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) {
			expanded[ "border" + part + "Color" ] = value;
		});
		return expanded;
	}
};

// Basic color names only.
// Usage of any of the other color names requires adding yourself or including
// jquery.color.svg-names.js.
colors = jQuery.Color.names = {
	// 4.1. Basic color keywords
	aqua: "#00ffff",
	black: "#000000",
	blue: "#0000ff",
	fuchsia: "#ff00ff",
	gray: "#808080",
	green: "#008000",
	lime: "#00ff00",
	maroon: "#800000",
	navy: "#000080",
	olive: "#808000",
	purple: "#800080",
	red: "#ff0000",
	silver: "#c0c0c0",
	teal: "#008080",
	white: "#ffffff",
	yellow: "#ffff00",

	// 4.2.3. "transparent" color keyword
	transparent: [ null, null, null, 0 ],

	_default: "#ffffff"
};

})( jQuery );


/******************************************************************************/
/****************************** CLASS ANIMATIONS ******************************/
/******************************************************************************/
(function() {

var classAnimationActions = [ "add", "remove", "toggle" ],
	shorthandStyles = {
		border: 1,
		borderBottom: 1,
		borderColor: 1,
		borderLeft: 1,
		borderRight: 1,
		borderTop: 1,
		borderWidth: 1,
		margin: 1,
		padding: 1
	};

$.each([ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) {
	$.fx.step[ prop ] = function( fx ) {
		if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) {
			jQuery.style( fx.elem, prop, fx.end );
			fx.setAttr = true;
		}
	};
});

function getElementStyles( elem ) {
	var key, len,
		style = elem.ownerDocument.defaultView ?
			elem.ownerDocument.defaultView.getComputedStyle( elem, null ) :
			elem.currentStyle,
		styles = {};

	if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) {
		len = style.length;
		while ( len-- ) {
			key = style[ len ];
			if ( typeof style[ key ] === "string" ) {
				styles[ $.camelCase( key ) ] = style[ key ];
			}
		}
	// support: Opera, IE <9
	} else {
		for ( key in style ) {
			if ( typeof style[ key ] === "string" ) {
				styles[ key ] = style[ key ];
			}
		}
	}

	return styles;
}


function styleDifference( oldStyle, newStyle ) {
	var diff = {},
		name, value;

	for ( name in newStyle ) {
		value = newStyle[ name ];
		if ( oldStyle[ name ] !== value ) {
			if ( !shorthandStyles[ name ] ) {
				if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) {
					diff[ name ] = value;
				}
			}
		}
	}

	return diff;
}

// support: jQuery <1.8
if ( !$.fn.addBack ) {
	$.fn.addBack = function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter( selector )
		);
	};
}

$.effects.animateClass = function( value, duration, easing, callback ) {
	var o = $.speed( duration, easing, callback );

	return this.queue( function() {
		var animated = $( this ),
			baseClass = animated.attr( "class" ) || "",
			applyClassChange,
			allAnimations = o.children ? animated.find( "*" ).addBack() : animated;

		// map the animated objects to store the original styles.
		allAnimations = allAnimations.map(function() {
			var el = $( this );
			return {
				el: el,
				start: getElementStyles( this )
			};
		});

		// apply class change
		applyClassChange = function() {
			$.each( classAnimationActions, function(i, action) {
				if ( value[ action ] ) {
					animated[ action + "Class" ]( value[ action ] );
				}
			});
		};
		applyClassChange();

		// map all animated objects again - calculate new styles and diff
		allAnimations = allAnimations.map(function() {
			this.end = getElementStyles( this.el[ 0 ] );
			this.diff = styleDifference( this.start, this.end );
			return this;
		});

		// apply original class
		animated.attr( "class", baseClass );

		// map all animated objects again - this time collecting a promise
		allAnimations = allAnimations.map(function() {
			var styleInfo = this,
				dfd = $.Deferred(),
				opts = $.extend({}, o, {
					queue: false,
					complete: function() {
						dfd.resolve( styleInfo );
					}
				});

			this.el.animate( this.diff, opts );
			return dfd.promise();
		});

		// once all animations have completed:
		$.when.apply( $, allAnimations.get() ).done(function() {

			// set the final class
			applyClassChange();

			// for each animated element,
			// clear all css properties that were animated
			$.each( arguments, function() {
				var el = this.el;
				$.each( this.diff, function(key) {
					el.css( key, "" );
				});
			});

			// this is guarnteed to be there if you use jQuery.speed()
			// it also handles dequeuing the next anim...
			o.complete.call( animated[ 0 ] );
		});
	});
};

$.fn.extend({
	addClass: (function( orig ) {
		return function( classNames, speed, easing, callback ) {
			return speed ?
				$.effects.animateClass.call( this,
					{ add: classNames }, speed, easing, callback ) :
				orig.apply( this, arguments );
		};
	})( $.fn.addClass ),

	removeClass: (function( orig ) {
		return function( classNames, speed, easing, callback ) {
			return arguments.length > 1 ?
				$.effects.animateClass.call( this,
					{ remove: classNames }, speed, easing, callback ) :
				orig.apply( this, arguments );
		};
	})( $.fn.removeClass ),

	toggleClass: (function( orig ) {
		return function( classNames, force, speed, easing, callback ) {
			if ( typeof force === "boolean" || force === undefined ) {
				if ( !speed ) {
					// without speed parameter
					return orig.apply( this, arguments );
				} else {
					return $.effects.animateClass.call( this,
						(force ? { add: classNames } : { remove: classNames }),
						speed, easing, callback );
				}
			} else {
				// without force parameter
				return $.effects.animateClass.call( this,
					{ toggle: classNames }, force, speed, easing );
			}
		};
	})( $.fn.toggleClass ),

	switchClass: function( remove, add, speed, easing, callback) {
		return $.effects.animateClass.call( this, {
			add: add,
			remove: remove
		}, speed, easing, callback );
	}
});

})();

/******************************************************************************/
/*********************************** EFFECTS **********************************/
/******************************************************************************/

(function() {

$.extend( $.effects, {
	version: "1.10.3",

	// Saves a set of properties in a data storage
	save: function( element, set ) {
		for( var i=0; i < set.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;
		for( i=0; i < set.length; i++ ) {
			if ( set[ i ] !== null ) {
				val = element.data( dataSpace + set[ i ] );
				// support: jQuery 1.6.2
				// http://bugs.jquery.com/ticket/9917
				// jQuery 1.6.2 incorrectly returns undefined for any falsy value.
				// We can't differentiate between "" and 0 here, so we just assume
				// empty string since it's likely to be a more common value...
				if ( val === undefined ) {
					val = "";
				}
				element.css( set[ i ], val );
			}
		}
	},

	setMode: function( el, mode ) {
		if (mode === "toggle") {
			mode = el.is( ":hidden" ) ? "show" : "hide";
		}
		return mode;
	},

	// Translates a [top,left] array into a baseline value
	// this should be a little more flexible in the future to handle a string & hash
	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
		};
	},

	// Wraps the element around a wrapper that copies position properties
	createWrapper: function( element ) {

		// if the element is already wrapped, return it
		if ( element.parent().is( ".ui-effects-wrapper" )) {
			return element.parent();
		}

		// wrap the element
		var props = {
				width: element.outerWidth(true),
				height: element.outerHeight(true),
				"float": element.css( "float" )
			},
			wrapper = $( "<div></div>" )
				.addClass( "ui-effects-wrapper" )
				.css({
					fontSize: "100%",
					background: "transparent",
					border: "none",
					margin: 0,
					padding: 0
				}),
			// Store the size in case width/height are defined in % - Fixes #5245
			size = {
				width: element.width(),
				height: element.height()
			},
			active = document.activeElement;

		// support: Firefox
		// Firefox incorrectly exposes anonymous content
		// https://bugzilla.mozilla.org/show_bug.cgi?id=561664
		try {
			active.id;
		} catch( e ) {
			active = document.body;
		}

		element.wrap( wrapper );

		// Fixes #7595 - Elements lose focus when wrapped.
		if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
			$( active ).focus();
		}

		wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element

		// 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 ).focus();
			}
		}


		return element;
	},

	setTransition: function( element, list, factor, value ) {
		value = value || {};
		$.each( list, function( i, x ) {
			var unit = element.cssUnit( x );
			if ( unit[ 0 ] > 0 ) {
				value[ x ] = unit[ 0 ] * factor + unit[ 1 ];
			}
		});
		return value;
	}
});

// return an effect options object for the given parameters:
function _normalizeArguments( effect, options, speed, callback ) {

	// allow passing all options as the first parameter
	if ( $.isPlainObject( effect ) ) {
		options = effect;
		effect = effect.effect;
	}

	// convert to an object
	effect = { effect: effect };

	// catch (effect, null, ...)
	if ( options == null ) {
		options = {};
	}

	// catch (effect, callback)
	if ( $.isFunction( options ) ) {
		callback = options;
		speed = null;
		options = {};
	}

	// catch (effect, speed, ?)
	if ( typeof options === "number" || $.fx.speeds[ options ] ) {
		callback = speed;
		speed = options;
		options = {};
	}

	// catch (effect, options, callback)
	if ( $.isFunction( speed ) ) {
		callback = speed;
		speed = null;
	}

	// add options to effect
	if ( options ) {
		$.extend( effect, options );
	}

	speed = speed || options.duration;
	effect.duration = $.fx.off ? 0 :
		typeof speed === "number" ? speed :
		speed in $.fx.speeds ? $.fx.speeds[ speed ] :
		$.fx.speeds._default;

	effect.complete = callback || options.complete;

	return effect;
}

function standardAnimationOption( option ) {
	// Valid standard speeds (nothing, number, named speed)
	if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) {
		return true;
	}

	// Invalid strings - treat as "normal" speed
	if ( typeof option === "string" && !$.effects.effect[ option ] ) {
		return true;
	}

	// Complete callback
	if ( $.isFunction( option ) ) {
		return true;
	}

	// Options hash (but not naming an effect)
	if ( typeof option === "object" && !option.effect ) {
		return true;
	}

	// Didn't match any standard API
	return false;
}

$.fn.extend({
	effect: function( /* effect, options, speed, callback */ ) {
		var args = _normalizeArguments.apply( this, arguments ),
			mode = args.mode,
			queue = args.queue,
			effectMethod = $.effects.effect[ args.effect ];

		if ( $.fx.off || !effectMethod ) {
			// delegate to the original method (e.g., .show()) if possible
			if ( mode ) {
				return this[ mode ]( args.duration, args.complete );
			} else {
				return this.each( function() {
					if ( args.complete ) {
						args.complete.call( this );
					}
				});
			}
		}

		function run( next ) {
			var elem = $( this ),
				complete = args.complete,
				mode = args.mode;

			function done() {
				if ( $.isFunction( complete ) ) {
					complete.call( elem[0] );
				}
				if ( $.isFunction( next ) ) {
					next();
				}
			}

			// If the element already has the correct final state, delegate to
			// the core methods so the internal tracking of "olddisplay" works.
			if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) {
				elem[ mode ]();
				done();
			} else {
				effectMethod.call( elem[0], args, done );
			}
		}

		return queue === false ? this.each( run ) : this.queue( queue || "fx", 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 ),

	// helper functions
	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;
	}
});

})();

/******************************************************************************/
/*********************************** EASING ***********************************/
/******************************************************************************/

(function() {

// based on easing equations from Robert Penner (http://www.robertpenner.com/easing)

var baseEasings = {};

$.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) {
	baseEasings[ name ] = function( p ) {
		return Math.pow( p, i + 2 );
	};
});

$.extend( baseEasings, {
	Sine: function ( p ) {
		return 1 - Math.cos( p * Math.PI / 2 );
	},
	Circ: function ( p ) {
		return 1 - Math.sqrt( 1 - p * p );
	},
	Elastic: function( p ) {
		return p === 0 || p === 1 ? p :
			-Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 );
	},
	Back: function( p ) {
		return p * p * ( 3 * p - 2 );
	},
	Bounce: function ( p ) {
		var pow2,
			bounce = 4;

		while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {}
		return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 );
	}
});

$.each( baseEasings, function( name, easeIn ) {
	$.easing[ "easeIn" + name ] = easeIn;
	$.easing[ "easeOut" + name ] = function( p ) {
		return 1 - easeIn( 1 - p );
	};
	$.easing[ "easeInOut" + name ] = function( p ) {
		return p < 0.5 ?
			easeIn( p * 2 ) / 2 :
			1 - easeIn( p * -2 + 2 ) / 2;
	};
});

})();

})(jQuery);
(function( $, undefined ) {

var rvertical = /up|down|vertical/,
	rpositivemotion = /up|left|vertical|horizontal/;

$.effects.effect.blind = function( o, done ) {
	// Create element
	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
		mode = $.effects.setMode( el, o.mode || "hide" ),
		direction = o.direction || "up",
		vertical = rvertical.test( direction ),
		ref = vertical ? "height" : "width",
		ref2 = vertical ? "top" : "left",
		motion = rpositivemotion.test( direction ),
		animation = {},
		show = mode === "show",
		wrapper, distance, margin;

	// if already wrapped, the wrapper's properties are my property. #6245
	if ( el.parent().is( ".ui-effects-wrapper" ) ) {
		$.effects.save( el.parent(), props );
	} else {
		$.effects.save( el, props );
	}
	el.show();
	wrapper = $.effects.createWrapper( el ).css({
		overflow: "hidden"
	});

	distance = wrapper[ ref ]();
	margin = parseFloat( wrapper.css( ref2 ) ) || 0;

	animation[ ref ] = show ? distance : 0;
	if ( !motion ) {
		el
			.css( vertical ? "bottom" : "right", 0 )
			.css( vertical ? "top" : "left", "auto" )
			.css({ position: "absolute" });

		animation[ ref2 ] = show ? margin : distance + margin;
	}

	// start at 0 if we are showing
	if ( show ) {
		wrapper.css( ref, 0 );
		if ( ! motion ) {
			wrapper.css( ref2, margin + distance );
		}
	}

	// Animate
	wrapper.animate( animation, {
		duration: o.duration,
		easing: o.easing,
		queue: false,
		complete: function() {
			if ( mode === "hide" ) {
				el.hide();
			}
			$.effects.restore( el, props );
			$.effects.removeWrapper( el );
			done();
		}
	});

};

})(jQuery);
(function( $, undefined ) {

$.effects.effect.bounce = function( o, done ) {
	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],

		// defaults:
		mode = $.effects.setMode( el, o.mode || "effect" ),
		hide = mode === "hide",
		show = mode === "show",
		direction = o.direction || "up",
		distance = o.distance,
		times = o.times || 5,

		// number of internal animations
		anims = times * 2 + ( show || hide ? 1 : 0 ),
		speed = o.duration / anims,
		easing = o.easing,

		// utility:
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		motion = ( direction === "up" || direction === "left" ),
		i,
		upAnim,
		downAnim,

		// we will need to re-assemble the queue to stack our animations in place
		queue = el.queue(),
		queuelen = queue.length;

	// Avoid touching opacity to prevent clearType and PNG issues in IE
	if ( show || hide ) {
		props.push( "opacity" );
	}

	$.effects.save( el, props );
	el.show();
	$.effects.createWrapper( el ); // Create Wrapper

	// default distance for the BIGGEST bounce is the outer Distance / 3
	if ( !distance ) {
		distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3;
	}

	if ( show ) {
		downAnim = { opacity: 1 };
		downAnim[ ref ] = 0;

		// if we are showing, force opacity 0 and set the initial position
		// then do the "first" animation
		el.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 ] = 0;
	// Bounces up/down/left/right then back to 0 -- times * 2 animations happen here
	for ( i = 0; i < times; i++ ) {
		upAnim = {};
		upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;

		el.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;

		el.animate( upAnim, speed, easing );
	}

	el.queue(function() {
		if ( hide ) {
			el.hide();
		}
		$.effects.restore( el, props );
		$.effects.removeWrapper( el );
		done();
	});

	// inject all the animations we just queued to be first in line (after "inprogress")
	if ( queuelen > 1) {
		queue.splice.apply( queue,
			[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
	}
	el.dequeue();

};

})(jQuery);
(function( $, undefined ) {

$.effects.effect.clip = function( o, done ) {
	// Create element
	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
		mode = $.effects.setMode( el, o.mode || "hide" ),
		show = mode === "show",
		direction = o.direction || "vertical",
		vert = direction === "vertical",
		size = vert ? "height" : "width",
		position = vert ? "top" : "left",
		animation = {},
		wrapper, animate, distance;

	// Save & Show
	$.effects.save( el, props );
	el.show();

	// Create Wrapper
	wrapper = $.effects.createWrapper( el ).css({
		overflow: "hidden"
	});
	animate = ( el[0].tagName === "IMG" ) ? wrapper : el;
	distance = animate[ size ]();

	// Shift
	if ( show ) {
		animate.css( size, 0 );
		animate.css( position, distance / 2 );
	}

	// Create Animation Object:
	animation[ size ] = show ? distance : 0;
	animation[ position ] = show ? 0 : distance / 2;

	// Animate
	animate.animate( animation, {
		queue: false,
		duration: o.duration,
		easing: o.easing,
		complete: function() {
			if ( !show ) {
				el.hide();
			}
			$.effects.restore( el, props );
			$.effects.removeWrapper( el );
			done();
		}
	});

};

})(jQuery);
(function( $, undefined ) {

$.effects.effect.drop = function( o, done ) {

	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "opacity", "height", "width" ],
		mode = $.effects.setMode( el, o.mode || "hide" ),
		show = mode === "show",
		direction = o.direction || "left",
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		motion = ( direction === "up" || direction === "left" ) ? "pos" : "neg",
		animation = {
			opacity: show ? 1 : 0
		},
		distance;

	// Adjust
	$.effects.save( el, props );
	el.show();
	$.effects.createWrapper( el );

	distance = o.distance || el[ ref === "top" ? "outerHeight": "outerWidth" ]( true ) / 2;

	if ( show ) {
		el
			.css( "opacity", 0 )
			.css( ref, motion === "pos" ? -distance : distance );
	}

	// Animation
	animation[ ref ] = ( show ?
		( motion === "pos" ? "+=" : "-=" ) :
		( motion === "pos" ? "-=" : "+=" ) ) +
		distance;

	// Animate
	el.animate( animation, {
		queue: false,
		duration: o.duration,
		easing: o.easing,
		complete: function() {
			if ( mode === "hide" ) {
				el.hide();
			}
			$.effects.restore( el, props );
			$.effects.removeWrapper( el );
			done();
		}
	});
};

})(jQuery);
(function( $, undefined ) {

$.effects.effect.explode = function( o, done ) {

	var rows = o.pieces ? Math.round( Math.sqrt( o.pieces ) ) : 3,
		cells = rows,
		el = $( this ),
		mode = $.effects.setMode( el, o.mode || "hide" ),
		show = mode === "show",

		// show and then visibility:hidden the element before calculating offset
		offset = el.show().css( "visibility", "hidden" ).offset(),

		// width and height of a piece
		width = Math.ceil( el.outerWidth() / cells ),
		height = Math.ceil( el.outerHeight() / rows ),
		pieces = [],

		// loop
		i, j, left, top, mx, my;

	// 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
			el
				.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
				}, o.duration || 500, o.easing, childComplete );
		}
	}

	function animComplete() {
		el.css({
			visibility: "visible"
		});
		$( pieces ).remove();
		if ( !show ) {
			el.hide();
		}
		done();
	}
};

})(jQuery);
(function( $, undefined ) {

$.effects.effect.fade = function( o, done ) {
	var el = $( this ),
		mode = $.effects.setMode( el, o.mode || "toggle" );

	el.animate({
		opacity: mode
	}, {
		queue: false,
		duration: o.duration,
		easing: o.easing,
		complete: done
	});
};

})( jQuery );
(function( $, undefined ) {

$.effects.effect.fold = function( o, done ) {

	// Create element
	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
		mode = $.effects.setMode( el, o.mode || "hide" ),
		show = mode === "show",
		hide = mode === "hide",
		size = o.size || 15,
		percent = /([0-9]+)%/.exec( size ),
		horizFirst = !!o.horizFirst,
		widthFirst = show !== horizFirst,
		ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ],
		duration = o.duration / 2,
		wrapper, distance,
		animation1 = {},
		animation2 = {};

	$.effects.save( el, props );
	el.show();

	// Create Wrapper
	wrapper = $.effects.createWrapper( el ).css({
		overflow: "hidden"
	});
	distance = widthFirst ?
		[ wrapper.width(), wrapper.height() ] :
		[ wrapper.height(), wrapper.width() ];

	if ( percent ) {
		size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ];
	}
	if ( show ) {
		wrapper.css( horizFirst ? {
			height: 0,
			width: size
		} : {
			height: size,
			width: 0
		});
	}

	// Animation
	animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size;
	animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0;

	// Animate
	wrapper
		.animate( animation1, duration, o.easing )
		.animate( animation2, duration, o.easing, function() {
			if ( hide ) {
				el.hide();
			}
			$.effects.restore( el, props );
			$.effects.removeWrapper( el );
			done();
		});

};

})(jQuery);
(function( $, undefined ) {

$.effects.effect.highlight = function( o, done ) {
	var elem = $( this ),
		props = [ "backgroundImage", "backgroundColor", "opacity" ],
		mode = $.effects.setMode( elem, o.mode || "show" ),
		animation = {
			backgroundColor: elem.css( "backgroundColor" )
		};

	if (mode === "hide") {
		animation.opacity = 0;
	}

	$.effects.save( elem, props );

	elem
		.show()
		.css({
			backgroundImage: "none",
			backgroundColor: o.color || "#ffff99"
		})
		.animate( animation, {
			queue: false,
			duration: o.duration,
			easing: o.easing,
			complete: function() {
				if ( mode === "hide" ) {
					elem.hide();
				}
				$.effects.restore( elem, props );
				done();
			}
		});
};

})(jQuery);
(function( $, undefined ) {

$.effects.effect.pulsate = function( o, done ) {
	var elem = $( this ),
		mode = $.effects.setMode( elem, o.mode || "show" ),
		show = mode === "show",
		hide = mode === "hide",
		showhide = ( show || mode === "hide" ),

		// showing or hiding leaves of the "last" animation
		anims = ( ( o.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ),
		duration = o.duration / anims,
		animateTo = 0,
		queue = elem.queue(),
		queuelen = queue.length,
		i;

	if ( show || !elem.is(":visible")) {
		elem.css( "opacity", 0 ).show();
		animateTo = 1;
	}

	// anims - 1 opacity "toggles"
	for ( i = 1; i < anims; i++ ) {
		elem.animate({
			opacity: animateTo
		}, duration, o.easing );
		animateTo = 1 - animateTo;
	}

	elem.animate({
		opacity: animateTo
	}, duration, o.easing);

	elem.queue(function() {
		if ( hide ) {
			elem.hide();
		}
		done();
	});

	// We just queued up "anims" animations, we need to put them next in the queue
	if ( queuelen > 1 ) {
		queue.splice.apply( queue,
			[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
	}
	elem.dequeue();
};

})(jQuery);
(function( $, undefined ) {

$.effects.effect.puff = function( o, done ) {
	var elem = $( this ),
		mode = $.effects.setMode( elem, o.mode || "hide" ),
		hide = mode === "hide",
		percent = parseInt( o.percent, 10 ) || 150,
		factor = percent / 100,
		original = {
			height: elem.height(),
			width: elem.width(),
			outerHeight: elem.outerHeight(),
			outerWidth: elem.outerWidth()
		};

	$.extend( o, {
		effect: "scale",
		queue: false,
		fade: true,
		mode: mode,
		complete: done,
		percent: hide ? percent : 100,
		from: hide ?
			original :
			{
				height: original.height * factor,
				width: original.width * factor,
				outerHeight: original.outerHeight * factor,
				outerWidth: original.outerWidth * factor
			}
	});

	elem.effect( o );
};

$.effects.effect.scale = function( o, done ) {

	// Create element
	var el = $( this ),
		options = $.extend( true, {}, o ),
		mode = $.effects.setMode( el, o.mode || "effect" ),
		percent = parseInt( o.percent, 10 ) ||
			( parseInt( o.percent, 10 ) === 0 ? 0 : ( mode === "hide" ? 0 : 100 ) ),
		direction = o.direction || "both",
		origin = o.origin,
		original = {
			height: el.height(),
			width: el.width(),
			outerHeight: el.outerHeight(),
			outerWidth: el.outerWidth()
		},
		factor = {
			y: direction !== "horizontal" ? (percent / 100) : 1,
			x: direction !== "vertical" ? (percent / 100) : 1
		};

	// We are going to pass this effect to the size effect:
	options.effect = "size";
	options.queue = false;
	options.complete = done;

	// Set default origin and restore for show/hide
	if ( mode !== "effect" ) {
		options.origin = origin || ["middle","center"];
		options.restore = true;
	}

	options.from = o.from || ( mode === "show" ? {
		height: 0,
		width: 0,
		outerHeight: 0,
		outerWidth: 0
	} : original );
	options.to = {
		height: original.height * factor.y,
		width: original.width * factor.x,
		outerHeight: original.outerHeight * factor.y,
		outerWidth: original.outerWidth * factor.x
	};

	// Fade option to support puff
	if ( options.fade ) {
		if ( mode === "show" ) {
			options.from.opacity = 0;
			options.to.opacity = 1;
		}
		if ( mode === "hide" ) {
			options.from.opacity = 1;
			options.to.opacity = 0;
		}
	}

	// Animate
	el.effect( options );

};

$.effects.effect.size = function( o, done ) {

	// Create element
	var original, baseline, factor,
		el = $( this ),
		props0 = [ "position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity" ],

		// Always restore
		props1 = [ "position", "top", "bottom", "left", "right", "overflow", "opacity" ],

		// Copy for children
		props2 = [ "width", "height", "overflow" ],
		cProps = [ "fontSize" ],
		vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ],
		hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ],

		// Set options
		mode = $.effects.setMode( el, o.mode || "effect" ),
		restore = o.restore || mode !== "effect",
		scale = o.scale || "both",
		origin = o.origin || [ "middle", "center" ],
		position = el.css( "position" ),
		props = restore ? props0 : props1,
		zero = {
			height: 0,
			width: 0,
			outerHeight: 0,
			outerWidth: 0
		};

	if ( mode === "show" ) {
		el.show();
	}
	original = {
		height: el.height(),
		width: el.width(),
		outerHeight: el.outerHeight(),
		outerWidth: el.outerWidth()
	};

	if ( o.mode === "toggle" && mode === "show" ) {
		el.from = o.to || zero;
		el.to = o.from || original;
	} else {
		el.from = o.from || ( mode === "show" ? zero : original );
		el.to = o.to || ( mode === "hide" ? zero : original );
	}

	// Set scaling factor
	factor = {
		from: {
			y: el.from.height / original.height,
			x: el.from.width / original.width
		},
		to: {
			y: el.to.height / original.height,
			x: el.to.width / original.width
		}
	};

	// Scale the css box
	if ( scale === "box" || scale === "both" ) {

		// Vertical props scaling
		if ( factor.from.y !== factor.to.y ) {
			props = props.concat( vProps );
			el.from = $.effects.setTransition( el, vProps, factor.from.y, el.from );
			el.to = $.effects.setTransition( el, vProps, factor.to.y, el.to );
		}

		// Horizontal props scaling
		if ( factor.from.x !== factor.to.x ) {
			props = props.concat( hProps );
			el.from = $.effects.setTransition( el, hProps, factor.from.x, el.from );
			el.to = $.effects.setTransition( el, hProps, factor.to.x, el.to );
		}
	}

	// Scale the content
	if ( scale === "content" || scale === "both" ) {

		// Vertical props scaling
		if ( factor.from.y !== factor.to.y ) {
			props = props.concat( cProps ).concat( props2 );
			el.from = $.effects.setTransition( el, cProps, factor.from.y, el.from );
			el.to = $.effects.setTransition( el, cProps, factor.to.y, el.to );
		}
	}

	$.effects.save( el, props );
	el.show();
	$.effects.createWrapper( el );
	el.css( "overflow", "hidden" ).css( el.from );

	// Adjust
	if (origin) { // Calculate baseline shifts
		baseline = $.effects.getBaseline( origin, original );
		el.from.top = ( original.outerHeight - el.outerHeight() ) * baseline.y;
		el.from.left = ( original.outerWidth - el.outerWidth() ) * baseline.x;
		el.to.top = ( original.outerHeight - el.to.outerHeight ) * baseline.y;
		el.to.left = ( original.outerWidth - el.to.outerWidth ) * baseline.x;
	}
	el.css( el.from ); // set top & left

	// Animate
	if ( scale === "content" || scale === "both" ) { // Scale the children

		// Add margins/font-size
		vProps = vProps.concat([ "marginTop", "marginBottom" ]).concat(cProps);
		hProps = hProps.concat([ "marginLeft", "marginRight" ]);
		props2 = props0.concat(vProps).concat(hProps);

		el.find( "*[width]" ).each( function(){
			var child = $( this ),
				c_original = {
					height: child.height(),
					width: child.width(),
					outerHeight: child.outerHeight(),
					outerWidth: child.outerWidth()
				};
			if (restore) {
				$.effects.save(child, props2);
			}

			child.from = {
				height: c_original.height * factor.from.y,
				width: c_original.width * factor.from.x,
				outerHeight: c_original.outerHeight * factor.from.y,
				outerWidth: c_original.outerWidth * factor.from.x
			};
			child.to = {
				height: c_original.height * factor.to.y,
				width: c_original.width * factor.to.x,
				outerHeight: c_original.height * factor.to.y,
				outerWidth: c_original.width * factor.to.x
			};

			// Vertical props scaling
			if ( factor.from.y !== factor.to.y ) {
				child.from = $.effects.setTransition( child, vProps, factor.from.y, child.from );
				child.to = $.effects.setTransition( child, vProps, factor.to.y, child.to );
			}

			// Horizontal props scaling
			if ( factor.from.x !== factor.to.x ) {
				child.from = $.effects.setTransition( child, hProps, factor.from.x, child.from );
				child.to = $.effects.setTransition( child, hProps, factor.to.x, child.to );
			}

			// Animate children
			child.css( child.from );
			child.animate( child.to, o.duration, o.easing, function() {

				// Restore children
				if ( restore ) {
					$.effects.restore( child, props2 );
				}
			});
		});
	}

	// Animate
	el.animate( el.to, {
		queue: false,
		duration: o.duration,
		easing: o.easing,
		complete: function() {
			if ( el.to.opacity === 0 ) {
				el.css( "opacity", el.from.opacity );
			}
			if( mode === "hide" ) {
				el.hide();
			}
			$.effects.restore( el, props );
			if ( !restore ) {

				// we need to calculate our new positioning based on the scaling
				if ( position === "static" ) {
					el.css({
						position: "relative",
						top: el.to.top,
						left: el.to.left
					});
				} else {
					$.each([ "top", "left" ], function( idx, pos ) {
						el.css( pos, function( _, str ) {
							var val = parseInt( str, 10 ),
								toRef = idx ? el.to.left : el.to.top;

							// if original was "auto", recalculate the new value from wrapper
							if ( str === "auto" ) {
								return toRef + "px";
							}

							return val + toRef + "px";
						});
					});
				}
			}

			$.effects.removeWrapper( el );
			done();
		}
	});

};

})(jQuery);
(function( $, undefined ) {

$.effects.effect.shake = function( o, done ) {

	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
		mode = $.effects.setMode( el, o.mode || "effect" ),
		direction = o.direction || "left",
		distance = o.distance || 20,
		times = o.times || 3,
		anims = times * 2 + 1,
		speed = Math.round(o.duration/anims),
		ref = (direction === "up" || direction === "down") ? "top" : "left",
		positiveMotion = (direction === "up" || direction === "left"),
		animation = {},
		animation1 = {},
		animation2 = {},
		i,

		// we will need to re-assemble the queue to stack our animations in place
		queue = el.queue(),
		queuelen = queue.length;

	$.effects.save( el, props );
	el.show();
	$.effects.createWrapper( el );

	// Animation
	animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance;
	animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2;
	animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2;

	// Animate
	el.animate( animation, speed, o.easing );

	// Shakes
	for ( i = 1; i < times; i++ ) {
		el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing );
	}
	el
		.animate( animation1, speed, o.easing )
		.animate( animation, speed / 2, o.easing )
		.queue(function() {
			if ( mode === "hide" ) {
				el.hide();
			}
			$.effects.restore( el, props );
			$.effects.removeWrapper( el );
			done();
		});

	// inject all the animations we just queued to be first in line (after "inprogress")
	if ( queuelen > 1) {
		queue.splice.apply( queue,
			[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
	}
	el.dequeue();

};

})(jQuery);
(function( $, undefined ) {

$.effects.effect.slide = function( o, done ) {

	// Create element
	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "width", "height" ],
		mode = $.effects.setMode( el, o.mode || "show" ),
		show = mode === "show",
		direction = o.direction || "left",
		ref = (direction === "up" || direction === "down") ? "top" : "left",
		positiveMotion = (direction === "up" || direction === "left"),
		distance,
		animation = {};

	// Adjust
	$.effects.save( el, props );
	el.show();
	distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true );

	$.effects.createWrapper( el ).css({
		overflow: "hidden"
	});

	if ( show ) {
		el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance );
	}

	// Animation
	animation[ ref ] = ( show ?
		( positiveMotion ? "+=" : "-=") :
		( positiveMotion ? "-=" : "+=")) +
		distance;

	// Animate
	el.animate( animation, {
		queue: false,
		duration: o.duration,
		easing: o.easing,
		complete: function() {
			if ( mode === "hide" ) {
				el.hide();
			}
			$.effects.restore( el, props );
			$.effects.removeWrapper( el );
			done();
		}
	});
};

})(jQuery);
(function( $, undefined ) {

$.effects.effect.transfer = function( o, done ) {
	var elem = $( this ),
		target = $( o.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 = elem.offset(),
		transfer = $( "<div class='ui-effects-transfer'></div>" )
			.appendTo( document.body )
			.addClass( o.className )
			.css({
				top: startPosition.top - fixTop ,
				left: startPosition.left - fixLeft ,
				height: elem.innerHeight(),
				width: elem.innerWidth(),
				position: targetFixed ? "fixed" : "absolute"
			})
			.animate( animation, o.duration, o.easing, function() {
				transfer.remove();
				done();
			});
};

})(jQuery);
;
/**
 * jQuery Plugin for creating collapsible fieldset.
 *
 * Copyright (c) 2013 Mirza Busatlic
 */

(function ($) {

    $.fn.collapsible = function (options) {

        var settings = $.extend({
            collapsed: false,
            animation: true,
            speed: "medium"
        }, options);

        this.each(function () {
            var $fieldset = $(this);
            var $legend = $fieldset.children("legend");
            var isCollapsed = $fieldset.hasClass("collapsed");

            $legend.click(function () {
                collapse($fieldset, settings, !isCollapsed);
                isCollapsed = !isCollapsed;
            });

            // Perform initial collapse.
            // Don't use animation to close for initial collapse.
            if (isCollapsed) {
                collapse($fieldset, { animation: false }, isCollapsed);
            } else {
                collapse($fieldset, settings, isCollapsed);
            }
          
           
        });
    };

	/**
	 * Collapse/uncollapse the specified fieldset.
	 * @param {object} $fieldset
	 * @param {object} options
	 * @param {boolean} collapse
	 */
    function collapse($fieldset, options, doCollapse) {
        $container = $fieldset.find("div");
        if (doCollapse) {
            if (options.animation) {
                $container.slideUp(options.speed);
            } else {
                $container.hide();
            }
            $fieldset.removeClass("expanded").addClass("collapsed");
        } else {
            if (options.animation) {
                $container.slideDown(options.speed);
            } else {
                $container.show();
            }
            $fieldset.removeClass("collapsed").addClass("expanded");
        }
       
        $('#errors').toggle();
        $("#confirmationErrors").toggle();
    };

})(jQuery);;
//https://rawgit.com/RickStrahl/jquery-resizable/master/dist/jquery-resizable.min.js

!function (e, t) { "function" == typeof define && define.amd ? define(["jquery"], e) : "object" == typeof module && "object" == typeof module.exports ? module.exports = e(require("jquery")) : e(jQuery) }(function (e, t) { e.fn.resizable || (e.fn.resizable = function (t) { var n = { handleSelector: null, resizeWidth: !0, resizeHeight: !0, resizeWidthFrom: "right", resizeHeightFrom: "bottom", onDragStart: null, onDragEnd: null, onDrag: null, touchActionNone: !0, instanceId: null }; return "object" == typeof t && (n = e.extend(n, t)), this.each(function () { function o(e) { e.stopPropagation(), e.preventDefault() } function i(t) { t.preventDefault && t.preventDefault(), d = c(t), d.width = parseInt(l.width(), 10), d.height = parseInt(l.height(), 10), h = l.css("transition"), l.css("transition", "none"), u.onDragStart && u.onDragStart(t, l, u) === !1 || (e(document).on("mousemove." + u.instanceId, r), e(document).on("mouseup." + u.instanceId, a), (window.Touch || navigator.maxTouchPoints) && (e(document).on("touchmove." + u.instanceId, r), e(document).on("touchend." + u.instanceId, a)), e(document).on("selectstart." + u.instanceId, o), e("iframe").css("pointer-events", "none")) } function r(e) { var t, n, o = c(e); t = "left" === u.resizeWidthFrom ? d.width - o.x + d.x : d.width + o.x - d.x, n = "top" === u.resizeHeightFrom ? d.height - o.y + d.y : d.height + o.y - d.y, u.onDrag && u.onDrag(e, l, t, n, u) === !1 || (u.resizeHeight && l.height(n), u.resizeWidth && l.width(t)) } function a(t) { return t.stopPropagation(), t.preventDefault(), e(document).off("mousemove." + u.instanceId), e(document).off("mouseup." + u.instanceId), (window.Touch || navigator.maxTouchPoints) && (e(document).off("touchmove." + u.instanceId), e(document).off("touchend." + u.instanceId)), e(document).off("selectstart." + u.instanceId, o), l.css("transition", h), e("iframe").css("pointer-events", "auto"), u.onDragEnd && u.onDragEnd(t, l, u), !1 } function c(e) { var t = { x: 0, y: 0, width: 0, height: 0 }; if ("number" == typeof e.clientX) t.x = e.clientX, t.y = e.clientY; else { if (!e.originalEvent.touches) return null; t.x = e.originalEvent.touches[0].clientX, t.y = e.originalEvent.touches[0].clientY } return t } function s(e, t) { return e && ">" === e.trim()[0] ? (e = e.trim().replace(/^>\s*/, ""), t.find(e)) : e ? t.parent().find(e) : t } var u = e.extend({}, n); u.instanceId || (u.instanceId = "rsz_" + (new Date).getTime()); var d, h, f, l = e(this); if ("destroy" === t) { if (u = l.data("resizable"), !u) return; return f = s(u.handleSelector, l), f.off("mousedown." + u.instanceId + " touchstart." + u.instanceId), u.touchActionNone && f.css("touch-action", ""), void l.removeClass("resizable") } l.data("resizable", u), f = s(u.handleSelector, l), u.touchActionNone && f.css("touch-action", "none"), l.addClass("resizable"), f.on("mousedown." + u.instanceId + " touchstart." + u.instanceId, i) }) }) });
//# sourceMappingURL=jquery-resizable.min.js.map
;
/*
 * jQuery UI Widget 1.10.1+amd
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2013 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/jQuery.widget/
 */

(function (factory) {
    if (typeof define === "function" && define.amd) {
        // Register as an anonymous AMD module:
        define(["jquery"], factory);
    } else {
        // Browser globals:
        factory(jQuery);
    }
}(function( $, undefined ) {

var uuid = 0,
	slice = Array.prototype.slice,
	_cleanData = $.cleanData;
$.cleanData = function( elems ) {
	for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
		try {
			$( elem ).triggerHandler( "remove" );
		// http://bugs.jquery.com/ticket/8235
		} catch( e ) {}
	}
	_cleanData( elems );
};

$.widget = function( name, base, prototype ) {
	var fullName, existingConstructor, constructor, basePrototype,
		// proxiedPrototype allows the provided prototype to remain unmodified
		// so that it can be used as a mixin for multiple widgets (#8876)
		proxiedPrototype = {},
		namespace = name.split( "." )[ 0 ];

	name = name.split( "." )[ 1 ];
	fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	// create selector for plugin
	$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
		return !!$.data( elem, fullName );
	};

	$[ namespace ] = $[ namespace ] || {};
	existingConstructor = $[ namespace ][ name ];
	constructor = $[ namespace ][ name ] = function( options, element ) {
		// allow instantiation without "new" keyword
		if ( !this._createWidget ) {
			return new constructor( options, element );
		}

		// allow instantiation without initializing for simple inheritance
		// must use "new" keyword (the code above always passes args)
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};
	// extend with the existing constructor to carry over any static properties
	$.extend( constructor, existingConstructor, {
		version: prototype.version,
		// copy the object used to create the prototype in case we need to
		// redefine the widget later
		_proto: $.extend( {}, prototype ),
		// track widgets that inherit from this widget in case this widget is
		// redefined after a widget inherits from it
		_childConstructors: []
	});

	basePrototype = new base();
	// we need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
	basePrototype.options = $.widget.extend( {}, basePrototype.options );
	$.each( prototype, function( prop, value ) {
		if ( !$.isFunction( value ) ) {
			proxiedPrototype[ prop ] = value;
			return;
		}
		proxiedPrototype[ prop ] = (function() {
			var _super = function() {
					return base.prototype[ prop ].apply( this, arguments );
				},
				_superApply = function( args ) {
					return base.prototype[ prop ].apply( this, args );
				};
			return function() {
				var __super = this._super,
					__superApply = this._superApply,
					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
	}, 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 );
};

$.widget.extend = function( target ) {
	var input = slice.call( arguments, 1 ),
		inputIndex = 0,
		inputLength = input.length,
		key,
		value;
	for ( ; inputIndex < inputLength; inputIndex++ ) {
		for ( key in input[ inputIndex ] ) {
			value = input[ inputIndex ][ key ];
			if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
				// Clone objects
				if ( $.isPlainObject( value ) ) {
					target[ key ] = $.isPlainObject( target[ key ] ) ?
						$.widget.extend( {}, target[ key ], value ) :
						// Don't extend strings, arrays, etc. with objects
						$.widget.extend( {}, value );
				// Copy everything else by reference
				} else {
					target[ key ] = value;
				}
			}
		}
	}
	return target;
};

$.widget.bridge = function( name, object ) {
	var fullName = object.prototype.widgetFullName || name;
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string",
			args = slice.call( arguments, 1 ),
			returnValue = this;

		// allow multiple hashes to be passed on init
		options = !isMethodCall && args.length ?
			$.widget.extend.apply( null, [ options ].concat(args) ) :
			options;

		if ( isMethodCall ) {
			this.each(function() {
				var methodValue,
					instance = $.data( this, fullName );
				if ( !instance ) {
					return $.error( "cannot call methods on " + name + " prior to initialization; " +
						"attempted to call method '" + options + "'" );
				}
				if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
					return $.error( "no such method '" + options + "' for " + name + " widget instance" );
				}
				methodValue = instance[ options ].apply( instance, args );
				if ( methodValue !== instance && methodValue !== undefined ) {
					returnValue = methodValue && methodValue.jquery ?
						returnValue.pushStack( methodValue.get() ) :
						methodValue;
					return false;
				}
			});
		} else {
			this.each(function() {
				var instance = $.data( this, fullName );
				if ( instance ) {
					instance.option( options || {} )._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: {
		disabled: false,

		// callbacks
		create: null
	},
	_createWidget: function( options, element ) {
		element = $( element || this.defaultElement || this )[ 0 ];
		this.element = $( element );
		this.uuid = uuid++;
		this.eventNamespace = "." + this.widgetName + this.uuid;
		this.options = $.widget.extend( {},
			this.options,
			this._getCreateOptions(),
			options );

		this.bindings = $();
		this.hoverable = $();
		this.focusable = $();

		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._create();
		this._trigger( "create", null, this._getCreateEventData() );
		this._init();
	},
	_getCreateOptions: $.noop,
	_getCreateEventData: $.noop,
	_create: $.noop,
	_init: $.noop,

	destroy: function() {
		this._destroy();
		// we can probably remove the unbind calls in 2.0
		// all event bindings should go through this._on()
		this.element
			.unbind( this.eventNamespace )
			// 1.9 BC for #7810
			// TODO remove dual storage
			.removeData( this.widgetName )
			.removeData( this.widgetFullName )
			// support: jquery <1.6.3
			// http://bugs.jquery.com/ticket/9413
			.removeData( $.camelCase( this.widgetFullName ) );
		this.widget()
			.unbind( this.eventNamespace )
			.removeAttr( "aria-disabled" )
			.removeClass(
				this.widgetFullName + "-disabled " +
				"ui-state-disabled" );

		// clean up events and states
		this.bindings.unbind( this.eventNamespace );
		this.hoverable.removeClass( "ui-state-hover" );
		this.focusable.removeClass( "ui-state-focus" );
	},
	_destroy: $.noop,

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key,
			parts,
			curOption,
			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 ( value === undefined ) {
					return curOption[ key ] === undefined ? null : curOption[ key ];
				}
				curOption[ key ] = value;
			} else {
				if ( value === undefined ) {
					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 ) {
		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this.widget()
				.toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
				.attr( "aria-disabled", value );
			this.hoverable.removeClass( "ui-state-hover" );
			this.focusable.removeClass( "ui-state-focus" );
		}

		return this;
	},

	enable: function() {
		return this._setOption( "disabled", false );
	},
	disable: function() {
		return this._setOption( "disabled", true );
	},

	_on: function( suppressDisabledCheck, element, handlers ) {
		var delegateElement,
			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 {
			// accept selectors, DOM elements
			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*(.*)$/ ),
				eventName = match[1] + instance.eventNamespace,
				selector = match[2];
			if ( selector ) {
				delegateElement.delegate( selector, eventName, handlerProxy );
			} else {
				element.bind( eventName, handlerProxy );
			}
		});
	},

	_off: function( element, eventName ) {
		eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
		element.unbind( eventName ).undelegate( eventName );
	},

	_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 ) {
				$( event.currentTarget ).addClass( "ui-state-hover" );
			},
			mouseleave: function( event ) {
				$( event.currentTarget ).removeClass( "ui-state-hover" );
			}
		});
	},

	_focusable: function( element ) {
		this.focusable = this.focusable.add( element );
		this._on( element, {
			focusin: function( event ) {
				$( event.currentTarget ).addClass( "ui-state-focus" );
			},
			focusout: function( event ) {
				$( event.currentTarget ).removeClass( "ui-state-focus" );
			}
		});
	},

	_trigger: function( type, event, data ) {
		var prop, orig,
			callback = this.options[ type ];

		data = data || {};
		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();
		// the original event may come from any element
		// so we need to reset the target on the new event
		event.target = this.element[ 0 ];

		// copy original event properties over to the new event
		orig = event.originalEvent;
		if ( orig ) {
			for ( prop in orig ) {
				if ( !( prop in event ) ) {
					event[ prop ] = orig[ prop ];
				}
			}
		}

		this.element.trigger( event, data );
		return !( $.isFunction( callback ) &&
			callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
			event.isDefaultPrevented() );
	}
};

$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
	$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
		if ( typeof options === "string" ) {
			options = { effect: options };
		}
		var hasOptions,
			effectName = !options ?
				method :
				options === true || typeof options === "number" ?
					defaultEffect :
					options.effect || defaultEffect;
		options = options || {};
		if ( typeof options === "number" ) {
			options = { duration: options };
		}
		hasOptions = !$.isEmptyObject( options );
		options.complete = callback;
		if ( options.delay ) {
			element.delay( options.delay );
		}
		if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
			element[ method ]( options );
		} else if ( effectName !== method && element[ effectName ] ) {
			element[ effectName ]( options.duration, options.easing, callback );
		} else {
			element.queue(function( next ) {
				$( this )[ method ]();
				if ( callback ) {
					callback.call( element[ 0 ] );
				}
				next();
			});
		}
	};
});

}));
;
/**
 * jQuery Validation Plugin 1.11.0
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright 2013 Jörn Zaefferer
 * Released under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 */

(function ($) {

    $.extend($.fn, {
        // http://docs.jquery.com/Plugins/Validation/validate
        validate: function (options) {

            // if nothing is selected, return nothing; can't chain anyway
            if (!this.length) {
                if (options && options.debug && window.console) {
                    console.warn("Nothing selected, can't validate, returning nothing.");
                }
                return;
            }

            // check if a validator for this form was already created
            var validator = $.data(this[0], "validator");
            if (validator) {
                return validator;
            }

            // Add novalidate tag if HTML5.
            this.attr("novalidate", "novalidate");

            validator = new $.validator(options, this[0]);
            $.data(this[0], "validator", validator);

            if (validator.settings.onsubmit) {

                this.validateDelegate(":submit", "click", function (event) {
                    if (validator.settings.submitHandler) {
                        validator.submitButton = event.target;
                    }
                    // allow suppressing validation by adding a cancel class to the submit button
                    if ($(event.target).hasClass("cancel")) {
                        validator.cancelSubmit = true;
                    }
                });

                // validate the form on submit
                this.submit(function (event) {
                    if (validator.settings.debug) {
                        // prevent form submit to be able to see console output
                        event.preventDefault();
                    }
                    function handle() {
                        var hidden;
                        if (validator.settings.submitHandler) {
                            if (validator.submitButton) {
                                // insert a hidden input as a replacement for the missing submit button
                                hidden = $("<input type='hidden'/>").attr("name", validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm);
                            }
                            validator.settings.submitHandler.call(validator, validator.currentForm, event);
                            if (validator.submitButton) {
                                // and clean up afterwards; thanks to no-block-scope, hidden can be referenced
                                hidden.remove();
                            }
                            return false;
                        }
                        return true;
                    }

                    // prevent submit for invalid forms or custom submit handlers
                    if (validator.cancelSubmit) {
                        validator.cancelSubmit = false;
                        return handle();
                    }
                    if (validator.form()) {
                        if (validator.pendingRequest) {
                            validator.formSubmitted = true;
                            return false;
                        }
                        return handle();
                    } else {
                        validator.focusInvalid();
                        return false;
                    }
                });
            }

            return validator;
        },
        // http://docs.jquery.com/Plugins/Validation/valid
        valid: function () {
            if ($(this[0]).is("form")) {
                return this.validate().form();
            } else {
                var valid = true;
                var validator = $(this[0].form).validate();
                this.each(function () {
                    valid &= validator.element(this);
                });
                return valid;
            }
        },
        // attributes: space seperated list of attributes to retrieve and remove
        removeAttrs: function (attributes) {
            var result = {},
                $element = this;
            $.each(attributes.split(/\s/), function (index, value) {
                result[value] = $element.attr(value);
                $element.removeAttr(value);
            });
            return result;
        },
        // http://docs.jquery.com/Plugins/Validation/rules
        rules: function (command, argument) {
            var element = this[0];

            if (command) {
                var settings = $.data(element.form, "validator").settings;
                var staticRules = settings.rules;
                var existingRules = $.validator.staticRules(element);
                switch (command) {
                    case "add":
                        $.extend(existingRules, $.validator.normalizeRule(argument));
                        staticRules[element.name] = existingRules;
                        if (argument.messages) {
                            settings.messages[element.name] = $.extend(settings.messages[element.name], argument.messages);
                        }
                        break;
                    case "remove":
                        if (!argument) {
                            delete staticRules[element.name];
                            return existingRules;
                        }
                        var filtered = {};
                        $.each(argument.split(/\s/), function (index, method) {
                            filtered[method] = existingRules[method];
                            delete existingRules[method];
                        });
                        return filtered;
                }
            }

            var data = $.validator.normalizeRules(
                $.extend(
                    {},
                    $.validator.classRules(element),
                    $.validator.attributeRules(element),
                    $.validator.dataRules(element),
                    $.validator.staticRules(element)
                ), element);

            // make sure required is at front
            if (data.required) {
                var param = data.required;
                delete data.required;
                data = $.extend({ required: param }, data);
            }

            return data;
        }
    });

    // Custom selectors
    $.extend($.expr[":"], {
        // http://docs.jquery.com/Plugins/Validation/blank
        blank: function (a) { return !$.trim("" + a.value); },
        // http://docs.jquery.com/Plugins/Validation/filled
        filled: function (a) { return !!$.trim("" + a.value); },
        // http://docs.jquery.com/Plugins/Validation/unchecked
        unchecked: function (a) { return !a.checked; }
    });

    // constructor for validator
    $.validator = function (options, form) {
        this.settings = $.extend(true, {}, $.validator.defaults, options);
        this.currentForm = form;
        this.init();
    };

    $.validator.format = function (source, params) {
        if (arguments.length === 1) {
            return function () {
                var args = $.makeArray(arguments);
                args.unshift(source);
                return $.validator.format.apply(this, args);
            };
        }
        if (arguments.length > 2 && params.constructor !== Array) {
            params = $.makeArray(arguments).slice(1);
        }
        if (params.constructor !== Array) {
            params = [params];
        }
        $.each(params, function (i, n) {
            source = source.replace(new RegExp("\\{" + i + "\\}", "g"), function () {
                return n;
            });
        });
        return source;
    };

    $.extend($.validator, {

        defaults: {
            messages: {},
            groups: {},
            rules: {},
            errorClass: "error",
            validClass: "valid",
            errorElement: "label",
            focusInvalid: true,
            errorContainer: $([]),
            errorLabelContainer: $([]),
            onsubmit: true,
            ignore: ":hidden",
            ignoreTitle: false,
            onfocusin: function (element, event) {
                this.lastActive = element;

                // hide error label and remove error class on focus if enabled
                if (this.settings.focusCleanup && !this.blockFocusCleanup) {
                    if (this.settings.unhighlight) {
                        this.settings.unhighlight.call(this, element, this.settings.errorClass, this.settings.validClass);
                    }
                    this.addWrapper(this.errorsFor(element)).hide();
                }
            },
            onfocusout: function (element, event) {
                if (!this.checkable(element) && (element.name in this.submitted || !this.optional(element))) {
                    this.element(element);
                }
            },
            onkeyup: function (element, event) {
                if (event.which === 9 && this.elementValue(element) === "") {
                    return;
                } else if (element.name in this.submitted || element === this.lastElement) {
                    this.element(element);
                }
            },
            onclick: function (element, event) {
                // click on selects, radiobuttons and checkboxes
                if (element.name in this.submitted) {
                    this.element(element);
                }
                // or option elements, check parent select in that case
                else if (element.parentNode.name in this.submitted) {
                    this.element(element.parentNode);
                }
            },
            highlight: function (element, errorClass, validClass) {
                if (element.type === "radio") {
                    this.findByName(element.name).addClass(errorClass).removeClass(validClass);
                } else {
                    $(element).addClass(errorClass).removeClass(validClass);
                }
            },
            unhighlight: function (element, errorClass, validClass) {
                if (element.type === "radio") {
                    this.findByName(element.name).removeClass(errorClass).addClass(validClass);
                } else {
                    $(element).removeClass(errorClass).addClass(validClass);
                }
            }
        },

        // http://docs.jquery.com/Plugins/Validation/Validator/setDefaults
        setDefaults: function (settings) {
            $.extend($.validator.defaults, settings);
        },

        messages: {
            required: "This field is required.",
            remote: "Please fix this field.",
            email: "Please enter a valid email address.",
            url: "Please enter a valid URL.",
            date: "Please enter a valid date.",
            dateISO: "Please enter a valid date (ISO).",
            number: "Please enter a valid number.",
            digits: "Please enter only digits.",
            creditcard: "Please enter a valid credit card number.",
            equalTo: "Please enter the same value again.",
            maxlength: $.validator.format("Please enter no more than {0} characters."),
            minlength: $.validator.format("Please enter at least {0} characters."),
            rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
            range: $.validator.format("Please enter a value between {0} and {1}."),
            max: $.validator.format("Please enter a value less than or equal to {0}."),
            min: $.validator.format("Please enter a value greater than or equal to {0}."),
        },

        autoCreateRanges: false,

        prototype: {

            init: function () {
                this.labelContainer = $(this.settings.errorLabelContainer);
                this.errorContext = this.labelContainer.length && this.labelContainer || $(this.currentForm);
                this.containers = $(this.settings.errorContainer).add(this.settings.errorLabelContainer);
                this.submitted = {};
                this.valueCache = {};
                this.pendingRequest = 0;
                this.pending = {};
                this.invalid = {};
                this.reset();

                var groups = (this.groups = {});
                $.each(this.settings.groups, function (key, value) {
                    if (typeof value === "string") {
                        value = value.split(/\s/);
                    }
                    $.each(value, function (index, name) {
                        groups[name] = key;
                    });
                });
                var rules = this.settings.rules;
                $.each(rules, function (key, value) {
                    rules[key] = $.validator.normalizeRule(value);
                });

                function delegate(event) {
                    var validator = $.data(this[0].form, "validator"),
                        eventType = "on" + event.type.replace(/^validate/, "");
                    if (validator.settings[eventType]) {
                        validator.settings[eventType].call(validator, this[0], event);
                    }
                }
                $(this.currentForm)
                    .validateDelegate(":text, [type='password'], [type='file'], select, textarea, " +
                        "[type='number'], [type='search'] ,[type='tel'], [type='url'], " +
                        "[type='email'], [type='datetime'], [type='date'], [type='month'], " +
                        "[type='week'], [type='time'], [type='datetime-local'], " +
                        "[type='range'], [type='color'] ",
                        "focusin focusout keyup", delegate)
                    .validateDelegate("[type='radio'], [type='checkbox'], select, option", "click", delegate);

                if (this.settings.invalidHandler) {
                    $(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler);
                }
            },

            // http://docs.jquery.com/Plugins/Validation/Validator/form
            form: function () {
                this.checkForm();
                $.extend(this.submitted, this.errorMap);
                this.invalid = $.extend({}, this.errorMap);
                if (!this.valid()) {
                    $(this.currentForm).triggerHandler("invalid-form", [this]);
                }
                this.showErrors();
                return this.valid();
            },

            checkForm: function () {
                this.prepareForm();
                for (var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++) {
                    this.check(elements[i]);
                }
                return this.valid();
            },

            // http://docs.jquery.com/Plugins/Validation/Validator/element
            element: function (element) {
                element = this.validationTargetFor(this.clean(element));
                this.lastElement = element;
                this.prepareElement(element);
                this.currentElements = $(element);
                var result = this.check(element) !== false;
                if (result) {
                    delete this.invalid[element.name];
                } else {
                    this.invalid[element.name] = true;
                }
                if (!this.numberOfInvalids()) {
                    // Hide error containers on last error
                    this.toHide = this.toHide.add(this.containers);
                }
                this.showErrors();
                return result;
            },

            // http://docs.jquery.com/Plugins/Validation/Validator/showErrors
            showErrors: function (errors) {
                if (errors) {
                    // add items to error list and map
                    $.extend(this.errorMap, errors);
                    this.errorList = [];
                    for (var name in errors) {
                        this.errorList.push({
                            message: errors[name],
                            element: this.findByName(name)[0]
                        });
                    }
                    // remove items from success list
                    this.successList = $.grep(this.successList, function (element) {
                        return !(element.name in errors);
                    });
                }
                if (this.settings.showErrors) {
                    this.settings.showErrors.call(this, this.errorMap, this.errorList);
                } else {
                    this.defaultShowErrors();
                }
            },

            // http://docs.jquery.com/Plugins/Validation/Validator/resetForm
            resetForm: function () {
                if ($.fn.resetForm) {
                    $(this.currentForm).resetForm();
                }
                this.submitted = {};
                this.lastElement = null;
                this.prepareForm();
                this.hideErrors();
                this.elements().removeClass(this.settings.errorClass).removeData("previousValue");
            },

            numberOfInvalids: function () {
                return this.objectLength(this.invalid);
            },

            objectLength: function (obj) {
                var count = 0;
                for (var i in obj) {
                    count++;
                }
                return count;
            },

            hideErrors: function () {
                this.addWrapper(this.toHide).hide();
            },

            valid: function () {
                return this.size() === 0;
            },

            size: function () {
                return this.errorList.length;
            },

            focusInvalid: function () {
                if (this.settings.focusInvalid) {
                    try {
                        $(this.findLastActive() || this.errorList.length && this.errorList[0].element || [])
                            .filter(":visible")
                            .focus()
                            // manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find
                            .trigger("focusin");
                    } catch (e) {
                        // ignore IE throwing errors when focusing hidden elements
                    }
                }
            },

            findLastActive: function () {
                var lastActive = this.lastActive;
                return lastActive && $.grep(this.errorList, function (n) {
                    return n.element.name === lastActive.name;
                }).length === 1 && lastActive;
            },

            elements: function () {
                var validator = this,
                    rulesCache = {};

                // select all valid inputs inside the form (no submit or reset buttons)
                return $(this.currentForm)
                    .find("input, select, textarea")
                    .not(":submit, :reset, :image, [disabled]")
                    .not(this.settings.ignore)
                    .filter(function () {
                        if (!this.name && validator.settings.debug && window.console) {
                            console.error("%o has no name assigned", this);
                        }

                        // select only the first element for each name, and only those with rules specified
                        if (this.name in rulesCache || !validator.objectLength($(this).rules())) {
                            return false;
                        }

                        rulesCache[this.name] = true;
                        return true;
                    });
            },

            clean: function (selector) {
                return $(selector)[0];
            },

            errors: function () {
                var errorClass = this.settings.errorClass.replace(" ", ".");
                return $(this.settings.errorElement + "." + errorClass, this.errorContext);
            },

            reset: function () {
                this.successList = [];
                this.errorList = [];
                this.errorMap = {};
                this.toShow = $([]);
                this.toHide = $([]);
                this.currentElements = $([]);
            },

            prepareForm: function () {
                this.reset();
                this.toHide = this.errors().add(this.containers);
            },

            prepareElement: function (element) {
                this.reset();
                this.toHide = this.errorsFor(element);
            },

            elementValue: function (element) {
                var type = $(element).attr("type"),
                    val = $(element).val();

                if (type === "radio" || type === "checkbox") {
                    return $("input[name='" + $(element).attr("name") + "']:checked").val();
                }

                if (typeof val === "string") {
                    return val.replace(/\r/g, "");
                }
                return val;
            },

            check: function (element) {
                element = this.validationTargetFor(this.clean(element));

                var rules = $(element).rules();
                var dependencyMismatch = false;
                var val = this.elementValue(element);
                var result;

                for (var method in rules) {
                    var rule = { method: method, parameters: rules[method] };
                    try {

                        result = $.validator.methods[method].call(this, val, element, rule.parameters);

                        // if a method indicates that the field is optional and therefore valid,
                        // don't mark it as valid when there are no other rules
                        if (result === "dependency-mismatch") {
                            dependencyMismatch = true;
                            continue;
                        }
                        dependencyMismatch = false;

                        if (result === "pending") {
                            this.toHide = this.toHide.not(this.errorsFor(element));
                            return;
                        }

                        if (!result) {
                            this.formatAndAdd(element, rule);
                            return false;
                        }
                    } catch (e) {
                        if (this.settings.debug && window.console) {
                            console.log("Exception occured when checking element " + element.id + ", check the '" + rule.method + "' method.", e);
                        }
                        throw e;
                    }
                }
                if (dependencyMismatch) {
                    return;
                }
                if (this.objectLength(rules)) {
                    this.successList.push(element);
                }
                return true;
            },

            // return the custom message for the given element and validation method
            // specified in the element's HTML5 data attribute
            customDataMessage: function (element, method) {
                return $(element).data("msg-" + method.toLowerCase()) || (element.attributes && $(element).attr("data-msg-" + method.toLowerCase()));
            },

            // return the custom message for the given element name and validation method
            customMessage: function (name, method) {
                var m = this.settings.messages[name];
                return m && (m.constructor === String ? m : m[method]);
            },

            // return the first defined argument, allowing empty strings
            findDefined: function () {
                for (var i = 0; i < arguments.length; i++) {
                    if (arguments[i] !== undefined) {
                        return arguments[i];
                    }
                }
                return undefined;
            },

            defaultMessage: function (element, method) {
                return this.findDefined(
                    this.customMessage(element.name, method),
                    this.customDataMessage(element, method),
                    // title is never undefined, so handle empty string as undefined
                    !this.settings.ignoreTitle && element.title || undefined,
                    $.validator.messages[method],
                    "<strong>Warning: No message defined for " + element.name + "</strong>"
                );
            },

            formatAndAdd: function (element, rule) {
                var message = this.defaultMessage(element, rule.method),
                    theregex = /\$?\{(\d+)\}/g;
                if (typeof message === "function") {
                    message = message.call(this, rule.parameters, element);
                } else if (theregex.test(message)) {
                    message = $.validator.format(message.replace(theregex, "{$1}"), rule.parameters);
                }
                this.errorList.push({
                    message: message,
                    element: element
                });

                this.errorMap[element.name] = message;
                this.submitted[element.name] = message;
            },

            addWrapper: function (toToggle) {
                if (this.settings.wrapper) {
                    toToggle = toToggle.add(toToggle.parent(this.settings.wrapper));
                }
                return toToggle;
            },

            defaultShowErrors: function () {
                var i, elements;
                for (i = 0; this.errorList[i]; i++) {
                    var error = this.errorList[i];
                    if (this.settings.highlight) {
                        this.settings.highlight.call(this, error.element, this.settings.errorClass, this.settings.validClass);
                    }
                    this.showLabel(error.element, error.message);
                }
                if (this.errorList.length) {
                    this.toShow = this.toShow.add(this.containers);
                }
                if (this.settings.success) {
                    for (i = 0; this.successList[i]; i++) {
                        this.showLabel(this.successList[i]);
                    }
                }
                if (this.settings.unhighlight) {
                    for (i = 0, elements = this.validElements(); elements[i]; i++) {
                        this.settings.unhighlight.call(this, elements[i], this.settings.errorClass, this.settings.validClass);
                    }
                }
                this.toHide = this.toHide.not(this.toShow);
                this.hideErrors();
                this.addWrapper(this.toShow).show();
            },

            validElements: function () {
                return this.currentElements.not(this.invalidElements());
            },

            invalidElements: function () {
                return $(this.errorList).map(function () {
                    return this.element;
                });
            },

            showLabel: function (element, message) {
                var label = this.errorsFor(element);
                if (label.length) {
                    // refresh error/success class
                    label.removeClass(this.settings.validClass).addClass(this.settings.errorClass);
                    // replace message on existing label
                    label.html(message);
                } else {
                    // create label
                    label = $("<" + this.settings.errorElement + ">")
                        .attr("for", this.idOrName(element))
                        .addClass(this.settings.errorClass)
                        .html(message || "");
                    if (this.settings.wrapper) {
                        // make sure the element is visible, even in IE
                        // actually showing the wrapped element is handled elsewhere
                        label = label.hide().show().wrap("<" + this.settings.wrapper + "/>").parent();
                    }
                    if (!this.labelContainer.append(label).length) {
                        if (this.settings.errorPlacement) {
                            this.settings.errorPlacement(label, $(element));
                        } else {
                            label.insertAfter(element);
                        }
                    }
                }
                if (!message && this.settings.success) {
                    label.text("");
                    if (typeof this.settings.success === "string") {
                        label.addClass(this.settings.success);
                    } else {
                        this.settings.success(label, element);
                    }
                }
                this.toShow = this.toShow.add(label);
            },

            errorsFor: function (element) {
                var name = this.idOrName(element);
                return this.errors().filter(function () {
                    return $(this).attr("for") === name;
                });
            },

            idOrName: function (element) {
                return this.groups[element.name] || (this.checkable(element) ? element.name : element.id || element.name);
            },

            validationTargetFor: function (element) {
                // if radio/checkbox, validate first element in group instead
                if (this.checkable(element)) {
                    element = this.findByName(element.name).not(this.settings.ignore)[0];
                }
                return element;
            },

            checkable: function (element) {
                return (/radio|checkbox/i).test(element.type);
            },

            findByName: function (name) {
                return $(this.currentForm).find("[name='" + name + "']");
            },

            getLength: function (value, element) {
                switch (element.nodeName.toLowerCase()) {
                    case "select":
                        return $("option:selected", element).length;
                    case "input":
                        if (this.checkable(element)) {
                            return this.findByName(element.name).filter(":checked").length;
                        }
                }
                return value.length;
            },

            depend: function (param, element) {
                return this.dependTypes[typeof param] ? this.dependTypes[typeof param](param, element) : true;
            },

            dependTypes: {
                "boolean": function (param, element) {
                    return param;
                },
                "string": function (param, element) {
                    return !!$(param, element.form).length;
                },
                "function": function (param, element) {
                    return param(element);
                }
            },

            optional: function (element) {
                var val = this.elementValue(element);
                return !$.validator.methods.required.call(this, val, element) && "dependency-mismatch";
            },

            startRequest: function (element) {
                if (!this.pending[element.name]) {
                    this.pendingRequest++;
                    this.pending[element.name] = true;
                }
            },

            stopRequest: function (element, valid) {
                this.pendingRequest--;
                // sometimes synchronization fails, make sure pendingRequest is never < 0
                if (this.pendingRequest < 0) {
                    this.pendingRequest = 0;
                }
                delete this.pending[element.name];
                if (valid && this.pendingRequest === 0 && this.formSubmitted && this.form()) {
                    $(this.currentForm).submit();
                    this.formSubmitted = false;
                } else if (!valid && this.pendingRequest === 0 && this.formSubmitted) {
                    $(this.currentForm).triggerHandler("invalid-form", [this]);
                    this.formSubmitted = false;
                }
            },

            previousValue: function (element) {
                return $.data(element, "previousValue") || $.data(element, "previousValue", {
                    old: null,
                    valid: true,
                    message: this.defaultMessage(element, "remote")
                });
            }

        },

        classRuleSettings: {
            required: { required: true },
            email: { email: true },
            url: { url: true },
            date: { date: true },
            dateISO: { dateISO: true },
            number: { number: true },
            digits: { digits: true },
            creditcard: { creditcard: true }
        },

        addClassRules: function (className, rules) {
            if (className.constructor === String) {
                this.classRuleSettings[className] = rules;
            } else {
                $.extend(this.classRuleSettings, className);
            }
        },

        classRules: function (element) {
            var rules = {};
            var classes = $(element).attr("class");
            if (classes) {
                $.each(classes.split(" "), function () {
                    if (this in $.validator.classRuleSettings) {
                        $.extend(rules, $.validator.classRuleSettings[this]);
                    }
                });
            }
            return rules;
        },

        attributeRules: function (element) {
            var rules = {};
            var $element = $(element);

            for (var method in $.validator.methods) {
                var value;

                // support for <input required> in both html5 and older browsers
                if (method === "required") {
                    value = $element.get(0).getAttribute(method);
                    // Some browsers return an empty string for the required attribute
                    // and non-HTML5 browsers might have required="" markup
                    if (value === "") {
                        value = true;
                    }
                    // force non-HTML5 browsers to return bool
                    value = !!value;
                } else {
                    value = $element.attr(method);
                }

                if (value) {
                    rules[method] = value;
                } else if ($element[0].getAttribute("type") === method) {
                    rules[method] = true;
                }
            }

            // maxlength may be returned as -1, 2147483647 (IE) and 524288 (safari) for text inputs
            if (rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength)) {
                delete rules.maxlength;
            }

            return rules;
        },

        dataRules: function (element) {
            var method, value,
                rules = {}, $element = $(element);
            for (method in $.validator.methods) {
                value = $element.data("rule-" + method.toLowerCase());
                if (value !== undefined) {
                    rules[method] = value;
                }
            }
            return rules;
        },

        staticRules: function (element) {
            var rules = {};
            var validator = $.data(element.form, "validator");
            if (validator.settings.rules) {
                rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {};
            }
            return rules;
        },

        normalizeRules: function (rules, element) {
            // handle dependency check
            $.each(rules, function (prop, val) {
                // ignore rule when param is explicitly false, eg. required:false
                if (val === false) {
                    delete rules[prop];
                    return;
                }
                if (val.param || val.depends) {
                    var keepRule = true;
                    switch (typeof val.depends) {
                        case "string":
                            keepRule = !!$(val.depends, element.form).length;
                            break;
                        case "function":
                            keepRule = val.depends.call(element, element);
                            break;
                    }
                    if (keepRule) {
                        rules[prop] = val.param !== undefined ? val.param : true;
                    } else {
                        delete rules[prop];
                    }
                }
            });

            // evaluate parameters
            $.each(rules, function (rule, parameter) {
                rules[rule] = $.isFunction(parameter) ? parameter(element) : parameter;
            });

            // clean number parameters
            $.each(['minlength', 'maxlength'], function () {
                if (rules[this]) {
                    rules[this] = Number(rules[this]);
                }
            });
            $.each(['rangelength'], function () {
                var parts;
                if (rules[this]) {
                    if ($.isArray(rules[this])) {
                        rules[this] = [Number(rules[this][0]), Number(rules[this][1])];
                    } else if (typeof rules[this] === "string") {
                        parts = rules[this].split(/[\s,]+/);
                        rules[this] = [Number(parts[0]), Number(parts[1])];
                    }
                }
            });

            if ($.validator.autoCreateRanges) {
                // auto-create ranges
                if (rules.min && rules.max) {
                    rules.range = [rules.min, rules.max];
                    delete rules.min;
                    delete rules.max;
                }
                if (rules.minlength && rules.maxlength) {
                    rules.rangelength = [rules.minlength, rules.maxlength];
                    delete rules.minlength;
                    delete rules.maxlength;
                }
            }

            return rules;
        },

        // Converts a simple string to a {string: true} rule, e.g., "required" to {required:true}
        normalizeRule: function (data) {
            if (typeof data === "string") {
                var transformed = {};
                $.each(data.split(/\s/), function () {
                    transformed[this] = true;
                });
                data = transformed;
            }
            return data;
        },

        // http://docs.jquery.com/Plugins/Validation/Validator/addMethod
        addMethod: function (name, method, message) {
            $.validator.methods[name] = method;
            $.validator.messages[name] = message !== undefined ? message : $.validator.messages[name];
            if (method.length < 3) {
                $.validator.addClassRules(name, $.validator.normalizeRule(name));
            }
        },

        methods: {

            // http://docs.jquery.com/Plugins/Validation/Methods/required
            required: function (value, element, param) {
                // check if dependency is met
                if (!this.depend(param, element)) {
                    return "dependency-mismatch";
                }
                if (element.nodeName.toLowerCase() === "select") {
                    // could be an array for select-multiple or a string, both are fine this way
                    var val = $(element).val();
                    return val && val.length > 0;
                }
                if (this.checkable(element)) {
                    return this.getLength(value, element) > 0;
                }
                return $.trim(value).length > 0;
            },

            // http://docs.jquery.com/Plugins/Validation/Methods/remote
            remote: function (value, element, param) {
                if (this.optional(element)) {
                    return "dependency-mismatch";
                }

                var previous = this.previousValue(element);
                if (!this.settings.messages[element.name]) {
                    this.settings.messages[element.name] = {};
                }
                previous.originalMessage = this.settings.messages[element.name].remote;
                this.settings.messages[element.name].remote = previous.message;

                param = typeof param === "string" && { url: param } || param;

                if (previous.old === value) {
                    return previous.valid;
                }

                previous.old = value;
                var validator = this;
                this.startRequest(element);
                var data = {};
                data[element.name] = value;
                $.ajax($.extend(true, {
                    url: param,
                    mode: "abort",
                    port: "validate" + element.name,
                    dataType: "json",
                    data: data,
                    success: function (response) {
                        validator.settings.messages[element.name].remote = previous.originalMessage;
                        var valid = response === true || response === "true";
                        if (valid) {
                            var submitted = validator.formSubmitted;
                            validator.prepareElement(element);
                            validator.formSubmitted = submitted;
                            validator.successList.push(element);
                            delete validator.invalid[element.name];
                            validator.showErrors();
                        } else {
                            var errors = {};
                            var message = response || validator.defaultMessage(element, "remote");
                            errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
                            validator.invalid[element.name] = true;
                            validator.showErrors(errors);
                        }
                        previous.valid = valid;
                        validator.stopRequest(element, valid);
                    }
                }, param));
                return "pending";
            },

            // http://docs.jquery.com/Plugins/Validation/Methods/minlength
            minlength: function (value, element, param) {
                var length = $.isArray(value) ? value.length : this.getLength($.trim(value), element);
                return this.optional(element) || length >= param;
            },

            // http://docs.jquery.com/Plugins/Validation/Methods/maxlength
            maxlength: function (value, element, param) {
                var length = $.isArray(value) ? value.length : this.getLength($.trim(value), element);
                return this.optional(element) || length <= param;
            },

            // http://docs.jquery.com/Plugins/Validation/Methods/rangelength
            rangelength: function (value, element, param) {
                var length = $.isArray(value) ? value.length : this.getLength($.trim(value), element);
                return this.optional(element) || (length >= param[0] && length <= param[1]);
            },

            // http://docs.jquery.com/Plugins/Validation/Methods/min
            min: function (value, element, param) {
                return this.optional(element) || value >= param;
            },

            // http://docs.jquery.com/Plugins/Validation/Methods/max
            max: function (value, element, param) {
                return this.optional(element) || value <= param;
            },

            // http://docs.jquery.com/Plugins/Validation/Methods/range
            range: function (value, element, param) {
                return this.optional(element) || (value >= param[0] && value <= param[1]);
            },

            // http://docs.jquery.com/Plugins/Validation/Methods/email
            email: function (value, element) {
                // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
                return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(value);
            },

            // http://docs.jquery.com/Plugins/Validation/Methods/url
            url: function (value, element) {
                // contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
                return this.optional(element) || /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
            },

            // http://docs.jquery.com/Plugins/Validation/Methods/date
            date: function (value, element) {
                return this.optional(element) || !/Invalid|NaN/.test(new Date(value).toString());
            },

            // http://docs.jquery.com/Plugins/Validation/Methods/dateISO
            dateISO: function (value, element) {
                return this.optional(element) || /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(value);
            },

            // http://docs.jquery.com/Plugins/Validation/Methods/number
            number: function (value, element) {
                return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value);
            },

            // http://docs.jquery.com/Plugins/Validation/Methods/digits
            digits: function (value, element) {
                return this.optional(element) || /^\d+$/.test(value);
            },

            // http://docs.jquery.com/Plugins/Validation/Methods/creditcard
            // based on http://en.wikipedia.org/wiki/Luhn
            creditcard: function (value, element) {
                if (this.optional(element)) {
                    return "dependency-mismatch";
                }
                // accept only spaces, digits and dashes
                if (/[^0-9 \-]+/.test(value)) {
                    return false;
                }
                var nCheck = 0,
                    nDigit = 0,
                    bEven = false;

                value = value.replace(/\D/g, "");

                for (var n = value.length - 1; n >= 0; n--) {
                    var cDigit = value.charAt(n);
                    nDigit = parseInt(cDigit, 10);
                    if (bEven) {
                        if ((nDigit *= 2) > 9) {
                            nDigit -= 9;
                        }
                    }
                    nCheck += nDigit;
                    bEven = !bEven;
                }

                return (nCheck % 10) === 0;
            },

            // http://docs.jquery.com/Plugins/Validation/Methods/equalTo
            equalTo: function (value, element, param) {
                // bind to the blur event of the target in order to revalidate whenever the target field is updated
                // TODO find a way to bind the event just once, avoiding the unbind-rebind overhead
                var target = $(param);
                if (this.settings.onfocusout) {
                    target.unbind(".validate-equalTo").bind("blur.validate-equalTo", function () {
                        $(element).valid();
                    });
                }
                return value === target.val();
            }

        }

    });

    // deprecated, use $.validator.format instead
    $.format = $.validator.format;

}(jQuery));

// ajax mode: abort
// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()
(function ($) {
    var pendingRequests = {};
    // Use a prefilter if available (1.5+)
    if ($.ajaxPrefilter) {
        $.ajaxPrefilter(function (settings, _, xhr) {
            var port = settings.port;
            if (settings.mode === "abort") {
                if (pendingRequests[port]) {
                    pendingRequests[port].abort();
                }
                pendingRequests[port] = xhr;
            }
        });
    } else {
        // Proxy ajax
        var ajax = $.ajax;
        $.ajax = function (settings) {
            var mode = ("mode" in settings ? settings : $.ajaxSettings).mode,
                port = ("port" in settings ? settings : $.ajaxSettings).port;
            if (mode === "abort") {
                if (pendingRequests[port]) {
                    pendingRequests[port].abort();
                }
                return (pendingRequests[port] = ajax.apply(this, arguments));
            }
            return ajax.apply(this, arguments);
        };
    }
}(jQuery));

// provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation
// handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target
(function ($) {
    $.extend($.fn, {
        validateDelegate: function (delegate, type, handler) {
            return this.bind(type, function (event) {
                var target = $(event.target);
                if (target.is(delegate)) {
                    return handler.apply(target, arguments);
                }
            });
        }
    });
}(jQuery));
;
/*!
** Unobtrusive validation support library for jQuery and jQuery Validate
** Copyright (C) Microsoft Corporation. All rights reserved.
*/

/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */
/*global document: false, jQuery: false */

(function ($) {
    var $jQval = $.validator,
        adapters,
        data_validation = "unobtrusiveValidation";

    function setValidationValues(options, ruleName, value) {
        options.rules[ruleName] = value;
        if (options.message) {
            options.messages[ruleName] = options.message;
        }
    }

    function splitAndTrim(value) {
        return value.replace(/^\s+|\s+$/g, "").split(/\s*,\s*/g);
    }

    function getModelPrefix(fieldName) {
        return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
    }

    function appendModelPrefix(value, prefix) {
        if (value.indexOf("*.") === 0) {
            value = value.replace("*.", prefix);
        }
        return value;
    }

    function onError(error, inputElement) {  // 'this' is the form element
        var container = $(this).find("[data-valmsg-for='" + inputElement[0].name + "']"),
            replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;

        container.removeClass("field-validation-valid").addClass("field-validation-error");
        error.data("unobtrusiveContainer", container);

        if (replace) {
            container.empty();
            error.removeClass("input-validation-error").appendTo(container);
        }
        else {
            error.hide();
        }
    }

    function onErrors(form, validator) {  // 'this' is the form element
        var container = $(this).find("[data-valmsg-summary=true]"),
            list = container.find("ul");

        if (list && list.length && validator.errorList.length) {
            list.empty();
            container.addClass("validation-summary-errors").removeClass("validation-summary-valid");

            $.each(validator.errorList, function () {
                $("<li />").html(this.message).appendTo(list);
            });
        }
    }

    function onSuccess(error) {  // 'this' is the form element
        var container = error.data("unobtrusiveContainer"),
            replace = $.parseJSON(container.attr("data-valmsg-replace"));

        if (container) {
            container.addClass("field-validation-valid").removeClass("field-validation-error");
            error.removeData("unobtrusiveContainer");

            if (replace) {
                container.empty();
            }
        }
    }

    function validationInfo(form) {
        var $form = $(form),
            result = $form.data(data_validation);

        if (!result) {
            result = {
                options: {  // options structure passed to jQuery Validate's validate() method
                    errorClass: "input-validation-error",
                    errorElement: "span",
                    errorPlacement: $.proxy(onError, form),
                    invalidHandler: $.proxy(onErrors, form),
                    messages: {},
                    rules: {},
                    success: $.proxy(onSuccess, form)
                },
                attachValidation: function () {
                    $form.validate(this.options);
                },
                validate: function () {  // a validation function that is called by unobtrusive Ajax
                    $form.validate();
                    return $form.valid();
                }
            };
            $form.data(data_validation, result);
        }

        return result;
    }

    $jQval.unobtrusive = {
        adapters: [],

        parseElement: function (element, skipAttach) {
            /// <summary>
            /// Parses a single HTML element for unobtrusive validation attributes.
            /// </summary>
            /// <param name="element" domElement="true">The HTML element to be parsed.</param>
            /// <param name="skipAttach" type="Boolean">[Optional] true to skip attaching the
            /// validation to the form. If parsing just this single element, you should specify true.
            /// If parsing several elements, you should specify false, and manually attach the validation
            /// to the form when you are finished. The default is false.</param>
            var $element = $(element),
                form = $element.parents("form")[0],
                valInfo, rules, messages;

            if (!form) {  // Cannot do client-side validation without a form
                return;
            }

            valInfo = validationInfo(form);
            valInfo.options.rules[element.name] = rules = {};
            valInfo.options.messages[element.name] = messages = {};

            $.each(this.adapters, function () {
                var prefix = "data-val-" + this.name,
                    message = $element.attr(prefix),
                    paramValues = {};

                if (message !== undefined) {  // Compare against undefined, because an empty message is legal (and falsy)
                    prefix += "-";

                    $.each(this.params, function () {
                        paramValues[this] = $element.attr(prefix + this);
                    });

                    this.adapt({
                        element: element,
                        form: form,
                        message: message,
                        params: paramValues,
                        rules: rules,
                        messages: messages
                    });
                }
            });

            jQuery.extend(rules, { "__dummy__": true });

            if (!skipAttach) {
                valInfo.attachValidation();
            }
        },

        parse: function (selector) {
            /// <summary>
            /// Parses all the HTML elements in the specified selector. It looks for input elements decorated
            /// with the [data-val=true] attribute value and enables validation according to the data-val-*
            /// attribute values.
            /// </summary>
            /// <param name="selector" type="String">Any valid jQuery selector.</param>
            $(selector).find(":input[data-val=true]").each(function () {
                $jQval.unobtrusive.parseElement(this, true);
            });

            $("form").each(function () {
                var info = validationInfo(this);
                if (info) {
                    info.attachValidation();
                }
            });
        }
    };

    adapters = $jQval.unobtrusive.adapters;

    adapters.add = function (adapterName, params, fn) {
        /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary>
        /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
        /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
        /// <param name="params" type="Array" optional="true">[Optional] An array of parameter names (strings) that will
        /// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and
        /// mmmm is the parameter name).</param>
        /// <param name="fn" type="Function">The function to call, which adapts the values from the HTML
        /// attributes into jQuery Validate rules and/or messages.</param>
        /// <returns type="jQuery.validator.unobtrusive.adapters" />
        if (!fn) {  // Called with no params, just a function
            fn = params;
            params = [];
        }
        this.push({ name: adapterName, params: params, adapt: fn });
        return this;
    };

    adapters.addBool = function (adapterName, ruleName) {
        /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
        /// the jQuery Validate validation rule has no parameter values.</summary>
        /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
        /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
        /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
        /// of adapterName will be used instead.</param>
        /// <returns type="jQuery.validator.unobtrusive.adapters" />
        return this.add(adapterName, function (options) {
            setValidationValues(options, ruleName || adapterName, true);
        });
    };

    adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) {
        /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
        /// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and
        /// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary>
        /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
        /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
        /// <param name="minRuleName" type="String">The name of the jQuery Validate rule to be used when you only
        /// have a minimum value.</param>
        /// <param name="maxRuleName" type="String">The name of the jQuery Validate rule to be used when you only
        /// have a maximum value.</param>
        /// <param name="minMaxRuleName" type="String">The name of the jQuery Validate rule to be used when you
        /// have both a minimum and maximum value.</param>
        /// <param name="minAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
        /// contains the minimum value. The default is "min".</param>
        /// <param name="maxAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
        /// contains the maximum value. The default is "max".</param>
        /// <returns type="jQuery.validator.unobtrusive.adapters" />
        return this.add(adapterName, [minAttribute || "min", maxAttribute || "max"], function (options) {
            var min = options.params.min,
                max = options.params.max;

            if (min && max) {
                setValidationValues(options, minMaxRuleName, [min, max]);
            }
            else if (min) {
                setValidationValues(options, minRuleName, min);
            }
            else if (max) {
                setValidationValues(options, maxRuleName, max);
            }
        });
    };

    adapters.addSingleVal = function (adapterName, attribute, ruleName) {
        /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
        /// the jQuery Validate validation rule has a single value.</summary>
        /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
        /// in the data-val-nnnn HTML attribute(where nnnn is the adapter name).</param>
        /// <param name="attribute" type="String">[Optional] The name of the HTML attribute that contains the value.
        /// The default is "val".</param>
        /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
        /// of adapterName will be used instead.</param>
        /// <returns type="jQuery.validator.unobtrusive.adapters" />
        return this.add(adapterName, [attribute || "val"], function (options) {
            setValidationValues(options, ruleName || adapterName, options.params[attribute]);
        });
    };

    $jQval.addMethod("__dummy__", function (value, element, params) {
        return true;
    });

    $jQval.addMethod("regex", function (value, element, params) {
        var match;
        if (this.optional(element)) {
            return true;
        }

        match = new RegExp(params).exec(value);
        return (match && (match.index === 0) && (match[0].length === value.length));
    });

    adapters.addSingleVal("accept", "exts").addSingleVal("regex", "pattern");
    adapters.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");
    adapters.addMinMax("length", "minlength", "maxlength", "rangelength").addMinMax("range", "min", "max", "range");
    adapters.add("equalto", ["other"], function (options) {
        var prefix = getModelPrefix(options.element.name),
            other = options.params.other,
            fullOtherName = appendModelPrefix(other, prefix),
            element = $(options.form).find(":input[name=" + fullOtherName + "]")[0];

        setValidationValues(options, "equalTo", element);
    });
    adapters.add("required", function (options) {
        // jQuery Validate equates "required" with "mandatory" for checkbox elements
        if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
            setValidationValues(options, "required", true);
        }
    });
    adapters.add("remote", ["url", "type", "additionalfields"], function (options) {
        var value = {
            url: options.params.url,
            type: options.params.type || "GET",
            data: {}
        },
            prefix = getModelPrefix(options.element.name);

        $.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) {
            var paramName = appendModelPrefix(fieldName, prefix);
            value.data[paramName] = function () {
                return $(options.form).find(":input[name='" + paramName + "']").val();
            };
        });

        setValidationValues(options, "remote", value);
    });

    $(function () {
        $jQval.unobtrusive.parse(document);
    });
}(jQuery));;
// funtion repeat for internet explorer 
// reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
if (!String.prototype.repeat) {
    String.prototype.repeat = function (count) {
        'use strict';
        if (this == null)
            throw new TypeError('can\'t convert ' + this + ' to object');
        var str = '' + this;
        // To convert string to integer.
        count = +count;
        // Check NaN
        if (count != count)
            count = 0;

        if (count < 0)
            throw new RangeError('repeat count must be non-negative');

        if (count == Infinity)
            throw new RangeError('repeat count must be less than infinity');

        count = Math.floor(count);
        if (str.length == 0 || count == 0)
            return '';

        // Ensuring count is a 31-bit integer allows us to heavily optimize the
        // main part. But anyway, most current (August 2014) browsers can't handle
        // strings 1 << 28 chars or longer, so:
        if (str.length * count >= 1 << 28)
            throw new RangeError('repeat count must not overflow maximum string size');

        var maxCount = str.length * count;
        count = Math.floor(Math.log(count) / Math.log(2));
        while (count) {
            str += str;
            count--;
        }
        str += str.substring(0, maxCount - str.length);
        return str;
    }
};
/*! jQuery Timepicker Addon - v1.5.3 - 2015-04-19
* http://trentrichardson.com/examples/timepicker
* Copyright (c) 2015 Trent Richardson; Licensed MIT */
(function (factory) {
	if (typeof define === 'function' && define.amd) {
		define(['jquery', 'jquery.ui'], factory);
	} else {
		factory(jQuery);
	}
}(function ($) {

	/*
	* Lets not redefine timepicker, Prevent "Uncaught RangeError: Maximum call stack size exceeded"
	*/
	$.ui.timepicker = $.ui.timepicker || {};
	if ($.ui.timepicker.version) {
		return;
	}

	/*
	* Extend jQueryUI, get it started with our version number
	*/
	$.extend($.ui, {
		timepicker: {
			version: "1.5.3"
		}
	});

	/* 
	* Timepicker manager.
	* Use the singleton instance of this class, $.timepicker, to interact with the time picker.
	* Settings for (groups of) time pickers are maintained in an instance object,
	* allowing multiple different settings on the same page.
	*/
	var Timepicker = function () {
		this.regional = []; // Available regional settings, indexed by language code
		this.regional[''] = { // Default regional settings
			currentText: 'Now',
			closeText: 'Done',
			amNames: ['AM', 'A'],
			pmNames: ['PM', 'P'],
			timeFormat: 'HH:mm',
			timeSuffix: '',
			timeOnlyTitle: 'Choose Time',
			timeText: 'Time',
			hourText: 'Hour',
			minuteText: 'Minute',
			secondText: 'Second',
			millisecText: 'Millisecond',
			microsecText: 'Microsecond',
			timezoneText: 'Time Zone',
			isRTL: false
		};
		this._defaults = { // Global defaults for all the datetime picker instances
			showButtonPanel: true,
			timeOnly: false,
			timeOnlyShowDate: false,
			showHour: null,
			showMinute: null,
			showSecond: null,
			showMillisec: null,
			showMicrosec: null,
			showTimezone: null,
			showTime: true,
			stepHour: 1,
			stepMinute: 1,
			stepSecond: 1,
			stepMillisec: 1,
			stepMicrosec: 1,
			hour: 0,
			minute: 0,
			second: 0,
			millisec: 0,
			microsec: 0,
			timezone: null,
			hourMin: 0,
			minuteMin: 0,
			secondMin: 0,
			millisecMin: 0,
			microsecMin: 0,
			hourMax: 23,
			minuteMax: 59,
			secondMax: 59,
			millisecMax: 999,
			microsecMax: 999,
			minDateTime: null,
			maxDateTime: null,
			maxTime: null,
			minTime: null,
			onSelect: null,
			hourGrid: 0,
			minuteGrid: 0,
			secondGrid: 0,
			millisecGrid: 0,
			microsecGrid: 0,
			alwaysSetTime: true,
			separator: ' ',
			altFieldTimeOnly: true,
			altTimeFormat: null,
			altSeparator: null,
			altTimeSuffix: null,
			altRedirectFocus: true,
			pickerTimeFormat: null,
			pickerTimeSuffix: null,
			showTimepicker: true,
			timezoneList: null,
			addSliderAccess: false,
			sliderAccessArgs: null,
			controlType: 'slider',
			oneLine: false,
			defaultValue: null,
			parse: 'strict',
			afterInject: null
		};
		$.extend(this._defaults, this.regional['']);
	};

	$.extend(Timepicker.prototype, {
		$input: null,
		$altInput: null,
		$timeObj: null,
		inst: null,
		hour_slider: null,
		minute_slider: null,
		second_slider: null,
		millisec_slider: null,
		microsec_slider: null,
		timezone_select: null,
		maxTime: null,
		minTime: null,
		hour: 0,
		minute: 0,
		second: 0,
		millisec: 0,
		microsec: 0,
		timezone: null,
		hourMinOriginal: null,
		minuteMinOriginal: null,
		secondMinOriginal: null,
		millisecMinOriginal: null,
		microsecMinOriginal: null,
		hourMaxOriginal: null,
		minuteMaxOriginal: null,
		secondMaxOriginal: null,
		millisecMaxOriginal: null,
		microsecMaxOriginal: null,
		ampm: '',
		formattedDate: '',
		formattedTime: '',
		formattedDateTime: '',
		timezoneList: null,
		units: ['hour', 'minute', 'second', 'millisec', 'microsec'],
		support: {},
		control: null,

		/* 
		* Override the default settings for all instances of the time picker.
		* @param  {Object} settings  object - the new settings to use as defaults (anonymous object)
		* @return {Object} the manager object
		*/
		setDefaults: function (settings) {
			extendRemove(this._defaults, settings || {});
			return this;
		},

		/*
		* Create a new Timepicker instance
		*/
		_newInst: function ($input, opts) {
			var tp_inst = new Timepicker(),
				inlineSettings = {},
				fns = {},
				overrides, i;

			for (var attrName in this._defaults) {
				if (this._defaults.hasOwnProperty(attrName)) {
					var attrValue = $input.attr('time:' + attrName);
					if (attrValue) {
						try {
							inlineSettings[attrName] = eval(attrValue);
						} catch (err) {
							inlineSettings[attrName] = attrValue;
						}
					}
				}
			}

			overrides = {
				beforeShow: function (input, dp_inst) {
					if ($.isFunction(tp_inst._defaults.evnts.beforeShow)) {
						return tp_inst._defaults.evnts.beforeShow.call($input[0], input, dp_inst, tp_inst);
					}
				},
				onChangeMonthYear: function (year, month, dp_inst) {
					// Update the time as well : this prevents the time from disappearing from the $input field.
					// tp_inst._updateDateTime(dp_inst);
					if ($.isFunction(tp_inst._defaults.evnts.onChangeMonthYear)) {
						tp_inst._defaults.evnts.onChangeMonthYear.call($input[0], year, month, dp_inst, tp_inst);
					}
				},
				onClose: function (dateText, dp_inst) {
					if (tp_inst.timeDefined === true && $input.val() !== '') {
						tp_inst._updateDateTime(dp_inst);
					}
					if ($.isFunction(tp_inst._defaults.evnts.onClose)) {
						tp_inst._defaults.evnts.onClose.call($input[0], dateText, dp_inst, tp_inst);
					}
				}
			};
			for (i in overrides) {
				if (overrides.hasOwnProperty(i)) {
					fns[i] = opts[i] || null;
				}
			}

			tp_inst._defaults = $.extend({}, this._defaults, inlineSettings, opts, overrides, {
				evnts: fns,
				timepicker: tp_inst // add timepicker as a property of datepicker: $.datepicker._get(dp_inst, 'timepicker');
			});
			tp_inst.amNames = $.map(tp_inst._defaults.amNames, function (val) {
				return val.toUpperCase();
			});
			tp_inst.pmNames = $.map(tp_inst._defaults.pmNames, function (val) {
				return val.toUpperCase();
			});

			// detect which units are supported
			tp_inst.support = detectSupport(
					tp_inst._defaults.timeFormat + 
					(tp_inst._defaults.pickerTimeFormat ? tp_inst._defaults.pickerTimeFormat : '') +
					(tp_inst._defaults.altTimeFormat ? tp_inst._defaults.altTimeFormat : ''));

			// controlType is string - key to our this._controls
			if (typeof(tp_inst._defaults.controlType) === 'string') {
				if (tp_inst._defaults.controlType === 'slider' && typeof($.ui.slider) === 'undefined') {
					tp_inst._defaults.controlType = 'select';
				}
				tp_inst.control = tp_inst._controls[tp_inst._defaults.controlType];
			}
			// controlType is an object and must implement create, options, value methods
			else {
				tp_inst.control = tp_inst._defaults.controlType;
			}

			// prep the timezone options
			var timezoneList = [-720, -660, -600, -570, -540, -480, -420, -360, -300, -270, -240, -210, -180, -120, -60,
					0, 60, 120, 180, 210, 240, 270, 300, 330, 345, 360, 390, 420, 480, 525, 540, 570, 600, 630, 660, 690, 720, 765, 780, 840];
			if (tp_inst._defaults.timezoneList !== null) {
				timezoneList = tp_inst._defaults.timezoneList;
			}
			var tzl = timezoneList.length, tzi = 0, tzv = null;
			if (tzl > 0 && typeof timezoneList[0] !== 'object') {
				for (; tzi < tzl; tzi++) {
					tzv = timezoneList[tzi];
					timezoneList[tzi] = { value: tzv, label: $.timepicker.timezoneOffsetString(tzv, tp_inst.support.iso8601) };
				}
			}
			tp_inst._defaults.timezoneList = timezoneList;

			// set the default units
			tp_inst.timezone = tp_inst._defaults.timezone !== null ? $.timepicker.timezoneOffsetNumber(tp_inst._defaults.timezone) :
							((new Date()).getTimezoneOffset() * -1);
			tp_inst.hour = tp_inst._defaults.hour < tp_inst._defaults.hourMin ? tp_inst._defaults.hourMin :
							tp_inst._defaults.hour > tp_inst._defaults.hourMax ? tp_inst._defaults.hourMax : tp_inst._defaults.hour;
			tp_inst.minute = tp_inst._defaults.minute < tp_inst._defaults.minuteMin ? tp_inst._defaults.minuteMin :
							tp_inst._defaults.minute > tp_inst._defaults.minuteMax ? tp_inst._defaults.minuteMax : tp_inst._defaults.minute;
			tp_inst.second = tp_inst._defaults.second < tp_inst._defaults.secondMin ? tp_inst._defaults.secondMin :
							tp_inst._defaults.second > tp_inst._defaults.secondMax ? tp_inst._defaults.secondMax : tp_inst._defaults.second;
			tp_inst.millisec = tp_inst._defaults.millisec < tp_inst._defaults.millisecMin ? tp_inst._defaults.millisecMin :
							tp_inst._defaults.millisec > tp_inst._defaults.millisecMax ? tp_inst._defaults.millisecMax : tp_inst._defaults.millisec;
			tp_inst.microsec = tp_inst._defaults.microsec < tp_inst._defaults.microsecMin ? tp_inst._defaults.microsecMin :
							tp_inst._defaults.microsec > tp_inst._defaults.microsecMax ? tp_inst._defaults.microsecMax : tp_inst._defaults.microsec;
			tp_inst.ampm = '';
			tp_inst.$input = $input;

			if (tp_inst._defaults.altField) {
				tp_inst.$altInput = $(tp_inst._defaults.altField);
				if (tp_inst._defaults.altRedirectFocus === true) {
					tp_inst.$altInput.css({
						cursor: 'pointer'
					}).focus(function () {
						$input.trigger("focus");
					});
				}
			}

			if (tp_inst._defaults.minDate === 0 || tp_inst._defaults.minDateTime === 0) {
				tp_inst._defaults.minDate = new Date();
			}
			if (tp_inst._defaults.maxDate === 0 || tp_inst._defaults.maxDateTime === 0) {
				tp_inst._defaults.maxDate = new Date();
			}

			// datepicker needs minDate/maxDate, timepicker needs minDateTime/maxDateTime..
			if (tp_inst._defaults.minDate !== undefined && tp_inst._defaults.minDate instanceof Date) {
				tp_inst._defaults.minDateTime = new Date(tp_inst._defaults.minDate.getTime());
			}
			if (tp_inst._defaults.minDateTime !== undefined && tp_inst._defaults.minDateTime instanceof Date) {
				tp_inst._defaults.minDate = new Date(tp_inst._defaults.minDateTime.getTime());
			}
			if (tp_inst._defaults.maxDate !== undefined && tp_inst._defaults.maxDate instanceof Date) {
				tp_inst._defaults.maxDateTime = new Date(tp_inst._defaults.maxDate.getTime());
			}
			if (tp_inst._defaults.maxDateTime !== undefined && tp_inst._defaults.maxDateTime instanceof Date) {
				tp_inst._defaults.maxDate = new Date(tp_inst._defaults.maxDateTime.getTime());
			}
			tp_inst.$input.bind('focus', function () {
				tp_inst._onFocus();
			});

			return tp_inst;
		},

		/*
		* add our sliders to the calendar
		*/
		_addTimePicker: function (dp_inst) {
			var currDT = $.trim((this.$altInput && this._defaults.altFieldTimeOnly) ? this.$input.val() + ' ' + this.$altInput.val() : this.$input.val());

			this.timeDefined = this._parseTime(currDT);
			this._limitMinMaxDateTime(dp_inst, false);
			this._injectTimePicker();
			this._afterInject();
		},

		/*
		* parse the time string from input value or _setTime
		*/
		_parseTime: function (timeString, withDate) {
			if (!this.inst) {
				this.inst = $.datepicker._getInst(this.$input[0]);
			}

			if (withDate || !this._defaults.timeOnly) {
				var dp_dateFormat = $.datepicker._get(this.inst, 'dateFormat');
				try {
					var parseRes = parseDateTimeInternal(dp_dateFormat, this._defaults.timeFormat, timeString, $.datepicker._getFormatConfig(this.inst), this._defaults);
					if (!parseRes.timeObj) {
						return false;
					}
					$.extend(this, parseRes.timeObj);
				} catch (err) {
					$.timepicker.log("Error parsing the date/time string: " + err +
									"\ndate/time string = " + timeString +
									"\ntimeFormat = " + this._defaults.timeFormat +
									"\ndateFormat = " + dp_dateFormat);
					return false;
				}
				return true;
			} else {
				var timeObj = $.datepicker.parseTime(this._defaults.timeFormat, timeString, this._defaults);
				if (!timeObj) {
					return false;
				}
				$.extend(this, timeObj);
				return true;
			}
		},

		/*
		* Handle callback option after injecting timepicker
		*/
		_afterInject: function() {
			var o = this.inst.settings;
			if ($.isFunction(o.afterInject)) {
				o.afterInject.call(this);
			}
		},

		/*
		* generate and inject html for timepicker into ui datepicker
		*/
		_injectTimePicker: function () {
			var $dp = this.inst.dpDiv,
				o = this.inst.settings,
				tp_inst = this,
				litem = '',
				uitem = '',
				show = null,
				max = {},
				gridSize = {},
				size = null,
				i = 0,
				l = 0;

			// Prevent displaying twice
			if ($dp.find("div.ui-timepicker-div").length === 0 && o.showTimepicker) {
				var noDisplay = ' ui_tpicker_unit_hide',
					html = '<div class="ui-timepicker-div' + (o.isRTL ? ' ui-timepicker-rtl' : '') + (o.oneLine && o.controlType === 'select' ? ' ui-timepicker-oneLine' : '') + '"><dl>' + '<dt class="ui_tpicker_time_label"' + ((o.showTime) ? '' : noDisplay) + '>' + o.timeText + '</dt>' +
								'<dd class="ui_tpicker_time '+ ((o.showTime) ? '' : noDisplay) + '"></dd>';

				// Create the markup
				for (i = 0, l = this.units.length; i < l; i++) {
					litem = this.units[i];
					uitem = litem.substr(0, 1).toUpperCase() + litem.substr(1);
					show = o['show' + uitem] !== null ? o['show' + uitem] : this.support[litem];

					// Added by Peter Medeiros:
					// - Figure out what the hour/minute/second max should be based on the step values.
					// - Example: if stepMinute is 15, then minMax is 45.
					max[litem] = parseInt((o[litem + 'Max'] - ((o[litem + 'Max'] - o[litem + 'Min']) % o['step' + uitem])), 10);
					gridSize[litem] = 0;

					html += '<dt class="ui_tpicker_' + litem + '_label' + (show ? '' : noDisplay) + '">' + o[litem + 'Text'] + '</dt>' +
								'<dd class="ui_tpicker_' + litem + (show ? '' : noDisplay) + '"><div class="ui_tpicker_' + litem + '_slider' + (show ? '' : noDisplay) + '"></div>';

					if (show && o[litem + 'Grid'] > 0) {
						html += '<div style="padding-left: 1px"><table class="ui-tpicker-grid-label"><tr>';

						if (litem === 'hour') {
							for (var h = o[litem + 'Min']; h <= max[litem]; h += parseInt(o[litem + 'Grid'], 10)) {
								gridSize[litem]++;
								var tmph = $.datepicker.formatTime(this.support.ampm ? 'hht' : 'HH', {hour: h}, o);
								html += '<td data-for="' + litem + '">' + tmph + '</td>';
							}
						}
						else {
							for (var m = o[litem + 'Min']; m <= max[litem]; m += parseInt(o[litem + 'Grid'], 10)) {
								gridSize[litem]++;
								html += '<td data-for="' + litem + '">' + ((m < 10) ? '0' : '') + m + '</td>';
							}
						}

						html += '</tr></table></div>';
					}
					html += '</dd>';
				}
				
				// Timezone
				var showTz = o.showTimezone !== null ? o.showTimezone : this.support.timezone;
				html += '<dt class="ui_tpicker_timezone_label' + (showTz ? '' : noDisplay) + '">' + o.timezoneText + '</dt>';
				html += '<dd class="ui_tpicker_timezone' + (showTz ? '' : noDisplay) + '"></dd>';

				// Create the elements from string
				html += '</dl></div>';
				var $tp = $(html);

				// if we only want time picker...
				if (o.timeOnly === true) {
					$tp.prepend('<div class="ui-widget-header ui-helper-clearfix ui-corner-all">' + '<div class="ui-datepicker-title">' + o.timeOnlyTitle + '</div>' + '</div>');
					$dp.find('.ui-datepicker-header, .ui-datepicker-calendar').hide();
				}
				
				// add sliders, adjust grids, add events
				for (i = 0, l = tp_inst.units.length; i < l; i++) {
					litem = tp_inst.units[i];
					uitem = litem.substr(0, 1).toUpperCase() + litem.substr(1);
					show = o['show' + uitem] !== null ? o['show' + uitem] : this.support[litem];

					// add the slider
					tp_inst[litem + '_slider'] = tp_inst.control.create(tp_inst, $tp.find('.ui_tpicker_' + litem + '_slider'), litem, tp_inst[litem], o[litem + 'Min'], max[litem], o['step' + uitem]);

					// adjust the grid and add click event
					if (show && o[litem + 'Grid'] > 0) {
						size = 100 * gridSize[litem] * o[litem + 'Grid'] / (max[litem] - o[litem + 'Min']);
						$tp.find('.ui_tpicker_' + litem + ' table').css({
							width: size + "%",
							marginLeft: o.isRTL ? '0' : ((size / (-2 * gridSize[litem])) + "%"),
							marginRight: o.isRTL ? ((size / (-2 * gridSize[litem])) + "%") : '0',
							borderCollapse: 'collapse'
						}).find("td").click(function (e) {
								var $t = $(this),
									h = $t.html(),
									n = parseInt(h.replace(/[^0-9]/g), 10),
									ap = h.replace(/[^apm]/ig),
									f = $t.data('for'); // loses scope, so we use data-for

								if (f === 'hour') {
									if (ap.indexOf('p') !== -1 && n < 12) {
										n += 12;
									}
									else {
										if (ap.indexOf('a') !== -1 && n === 12) {
											n = 0;
										}
									}
								}
								
								tp_inst.control.value(tp_inst, tp_inst[f + '_slider'], litem, n);

								tp_inst._onTimeChange();
								tp_inst._onSelectHandler();
							}).css({
								cursor: 'pointer',
								width: (100 / gridSize[litem]) + '%',
								textAlign: 'center',
								overflow: 'hidden'
							});
					} // end if grid > 0
				} // end for loop

				// Add timezone options
				this.timezone_select = $tp.find('.ui_tpicker_timezone').append('<select></select>').find("select");
				$.fn.append.apply(this.timezone_select,
				$.map(o.timezoneList, function (val, idx) {
					return $("<option />").val(typeof val === "object" ? val.value : val).text(typeof val === "object" ? val.label : val);
				}));
				if (typeof(this.timezone) !== "undefined" && this.timezone !== null && this.timezone !== "") {
					var local_timezone = (new Date(this.inst.selectedYear, this.inst.selectedMonth, this.inst.selectedDay, 12)).getTimezoneOffset() * -1;
					if (local_timezone === this.timezone) {
						selectLocalTimezone(tp_inst);
					} else {
						this.timezone_select.val(this.timezone);
					}
				} else {
					if (typeof(this.hour) !== "undefined" && this.hour !== null && this.hour !== "") {
						this.timezone_select.val(o.timezone);
					} else {
						selectLocalTimezone(tp_inst);
					}
				}
				this.timezone_select.change(function () {
					tp_inst._onTimeChange();
					tp_inst._onSelectHandler();
					tp_inst._afterInject();
				});
				// End timezone options
				
				// inject timepicker into datepicker
				var $buttonPanel = $dp.find('.ui-datepicker-buttonpane');
				if ($buttonPanel.length) {
					$buttonPanel.before($tp);
				} else {
					$dp.append($tp);
				}

				this.$timeObj = $tp.find('.ui_tpicker_time');

				if (this.inst !== null) {
					var timeDefined = this.timeDefined;
					this._onTimeChange();
					this.timeDefined = timeDefined;
				}

				// slideAccess integration: http://trentrichardson.com/2011/11/11/jquery-ui-sliders-and-touch-accessibility/
				if (this._defaults.addSliderAccess) {
					var sliderAccessArgs = this._defaults.sliderAccessArgs,
						rtl = this._defaults.isRTL;
					sliderAccessArgs.isRTL = rtl;
						
					setTimeout(function () { // fix for inline mode
						if ($tp.find('.ui-slider-access').length === 0) {
							$tp.find('.ui-slider:visible').sliderAccess(sliderAccessArgs);

							// fix any grids since sliders are shorter
							var sliderAccessWidth = $tp.find('.ui-slider-access:eq(0)').outerWidth(true);
							if (sliderAccessWidth) {
								$tp.find('table:visible').each(function () {
									var $g = $(this),
										oldWidth = $g.outerWidth(),
										oldMarginLeft = $g.css(rtl ? 'marginRight' : 'marginLeft').toString().replace('%', ''),
										newWidth = oldWidth - sliderAccessWidth,
										newMarginLeft = ((oldMarginLeft * newWidth) / oldWidth) + '%',
										css = { width: newWidth, marginRight: 0, marginLeft: 0 };
									css[rtl ? 'marginRight' : 'marginLeft'] = newMarginLeft;
									$g.css(css);
								});
							}
						}
					}, 10);
				}
				// end slideAccess integration

				tp_inst._limitMinMaxDateTime(this.inst, true);
			}
		},

		/*
		* This function tries to limit the ability to go outside the
		* min/max date range
		*/
		_limitMinMaxDateTime: function (dp_inst, adjustSliders) {
			var o = this._defaults,
				dp_date = new Date(dp_inst.selectedYear, dp_inst.selectedMonth, dp_inst.selectedDay);

			if (!this._defaults.showTimepicker) {
				return;
			} // No time so nothing to check here

			if ($.datepicker._get(dp_inst, 'minDateTime') !== null && $.datepicker._get(dp_inst, 'minDateTime') !== undefined && dp_date) {
				var minDateTime = $.datepicker._get(dp_inst, 'minDateTime'),
					minDateTimeDate = new Date(minDateTime.getFullYear(), minDateTime.getMonth(), minDateTime.getDate(), 0, 0, 0, 0);

				if (this.hourMinOriginal === null || this.minuteMinOriginal === null || this.secondMinOriginal === null || this.millisecMinOriginal === null || this.microsecMinOriginal === null) {
					this.hourMinOriginal = o.hourMin;
					this.minuteMinOriginal = o.minuteMin;
					this.secondMinOriginal = o.secondMin;
					this.millisecMinOriginal = o.millisecMin;
					this.microsecMinOriginal = o.microsecMin;
				}

				if (dp_inst.settings.timeOnly || minDateTimeDate.getTime() === dp_date.getTime()) {
					this._defaults.hourMin = minDateTime.getHours();
					if (this.hour <= this._defaults.hourMin) {
						this.hour = this._defaults.hourMin;
						this._defaults.minuteMin = minDateTime.getMinutes();
						if (this.minute <= this._defaults.minuteMin) {
							this.minute = this._defaults.minuteMin;
							this._defaults.secondMin = minDateTime.getSeconds();
							if (this.second <= this._defaults.secondMin) {
								this.second = this._defaults.secondMin;
								this._defaults.millisecMin = minDateTime.getMilliseconds();
								if (this.millisec <= this._defaults.millisecMin) {
									this.millisec = this._defaults.millisecMin;
									this._defaults.microsecMin = minDateTime.getMicroseconds();
								} else {
									if (this.microsec < this._defaults.microsecMin) {
										this.microsec = this._defaults.microsecMin;
									}
									this._defaults.microsecMin = this.microsecMinOriginal;
								}
							} else {
								this._defaults.millisecMin = this.millisecMinOriginal;
								this._defaults.microsecMin = this.microsecMinOriginal;
							}
						} else {
							this._defaults.secondMin = this.secondMinOriginal;
							this._defaults.millisecMin = this.millisecMinOriginal;
							this._defaults.microsecMin = this.microsecMinOriginal;
						}
					} else {
						this._defaults.minuteMin = this.minuteMinOriginal;
						this._defaults.secondMin = this.secondMinOriginal;
						this._defaults.millisecMin = this.millisecMinOriginal;
						this._defaults.microsecMin = this.microsecMinOriginal;
					}
				} else {
					this._defaults.hourMin = this.hourMinOriginal;
					this._defaults.minuteMin = this.minuteMinOriginal;
					this._defaults.secondMin = this.secondMinOriginal;
					this._defaults.millisecMin = this.millisecMinOriginal;
					this._defaults.microsecMin = this.microsecMinOriginal;
				}
			}

			if ($.datepicker._get(dp_inst, 'maxDateTime') !== null && $.datepicker._get(dp_inst, 'maxDateTime') !== undefined && dp_date) {
				var maxDateTime = $.datepicker._get(dp_inst, 'maxDateTime'),
					maxDateTimeDate = new Date(maxDateTime.getFullYear(), maxDateTime.getMonth(), maxDateTime.getDate(), 0, 0, 0, 0);

				if (this.hourMaxOriginal === null || this.minuteMaxOriginal === null || this.secondMaxOriginal === null || this.millisecMaxOriginal === null) {
					this.hourMaxOriginal = o.hourMax;
					this.minuteMaxOriginal = o.minuteMax;
					this.secondMaxOriginal = o.secondMax;
					this.millisecMaxOriginal = o.millisecMax;
					this.microsecMaxOriginal = o.microsecMax;
				}

				if (dp_inst.settings.timeOnly || maxDateTimeDate.getTime() === dp_date.getTime()) {
					this._defaults.hourMax = maxDateTime.getHours();
					if (this.hour >= this._defaults.hourMax) {
						this.hour = this._defaults.hourMax;
						this._defaults.minuteMax = maxDateTime.getMinutes();
						if (this.minute >= this._defaults.minuteMax) {
							this.minute = this._defaults.minuteMax;
							this._defaults.secondMax = maxDateTime.getSeconds();
							if (this.second >= this._defaults.secondMax) {
								this.second = this._defaults.secondMax;
								this._defaults.millisecMax = maxDateTime.getMilliseconds();
								if (this.millisec >= this._defaults.millisecMax) {
									this.millisec = this._defaults.millisecMax;
									this._defaults.microsecMax = maxDateTime.getMicroseconds();
								} else {
									if (this.microsec > this._defaults.microsecMax) {
										this.microsec = this._defaults.microsecMax;
									}
									this._defaults.microsecMax = this.microsecMaxOriginal;
								}
							} else {
								this._defaults.millisecMax = this.millisecMaxOriginal;
								this._defaults.microsecMax = this.microsecMaxOriginal;
							}
						} else {
							this._defaults.secondMax = this.secondMaxOriginal;
							this._defaults.millisecMax = this.millisecMaxOriginal;
							this._defaults.microsecMax = this.microsecMaxOriginal;
						}
					} else {
						this._defaults.minuteMax = this.minuteMaxOriginal;
						this._defaults.secondMax = this.secondMaxOriginal;
						this._defaults.millisecMax = this.millisecMaxOriginal;
						this._defaults.microsecMax = this.microsecMaxOriginal;
					}
				} else {
					this._defaults.hourMax = this.hourMaxOriginal;
					this._defaults.minuteMax = this.minuteMaxOriginal;
					this._defaults.secondMax = this.secondMaxOriginal;
					this._defaults.millisecMax = this.millisecMaxOriginal;
					this._defaults.microsecMax = this.microsecMaxOriginal;
				}
			}

			if (dp_inst.settings.minTime!==null) {				
				var tempMinTime=new Date("01/01/1970 " + dp_inst.settings.minTime);				
				if (this.hour<tempMinTime.getHours()) {
					this.hour=this._defaults.hourMin=tempMinTime.getHours();
					this.minute=this._defaults.minuteMin=tempMinTime.getMinutes();							
				} else if (this.hour===tempMinTime.getHours() && this.minute<tempMinTime.getMinutes()) {
					this.minute=this._defaults.minuteMin=tempMinTime.getMinutes();
				} else {						
					if (this._defaults.hourMin<tempMinTime.getHours()) {
						this._defaults.hourMin=tempMinTime.getHours();
						this._defaults.minuteMin=tempMinTime.getMinutes();					
					} else if (this._defaults.hourMin===tempMinTime.getHours()===this.hour && this._defaults.minuteMin<tempMinTime.getMinutes()) {
						this._defaults.minuteMin=tempMinTime.getMinutes();						
					} else {
						this._defaults.minuteMin=0;
					}
				}				
			}
			
			if (dp_inst.settings.maxTime!==null) {				
				var tempMaxTime=new Date("01/01/1970 " + dp_inst.settings.maxTime);
				if (this.hour>tempMaxTime.getHours()) {
					this.hour=this._defaults.hourMax=tempMaxTime.getHours();						
					this.minute=this._defaults.minuteMax=tempMaxTime.getMinutes();
				} else if (this.hour===tempMaxTime.getHours() && this.minute>tempMaxTime.getMinutes()) {							
					this.minute=this._defaults.minuteMax=tempMaxTime.getMinutes();						
				} else {
					if (this._defaults.hourMax>tempMaxTime.getHours()) {
						this._defaults.hourMax=tempMaxTime.getHours();
						this._defaults.minuteMax=tempMaxTime.getMinutes();					
					} else if (this._defaults.hourMax===tempMaxTime.getHours()===this.hour && this._defaults.minuteMax>tempMaxTime.getMinutes()) {
						this._defaults.minuteMax=tempMaxTime.getMinutes();						
					} else {
						this._defaults.minuteMax=59;
					}
				}						
			}
			
			if (adjustSliders !== undefined && adjustSliders === true) {
				var hourMax = parseInt((this._defaults.hourMax - ((this._defaults.hourMax - this._defaults.hourMin) % this._defaults.stepHour)), 10),
					minMax = parseInt((this._defaults.minuteMax - ((this._defaults.minuteMax - this._defaults.minuteMin) % this._defaults.stepMinute)), 10),
					secMax = parseInt((this._defaults.secondMax - ((this._defaults.secondMax - this._defaults.secondMin) % this._defaults.stepSecond)), 10),
					millisecMax = parseInt((this._defaults.millisecMax - ((this._defaults.millisecMax - this._defaults.millisecMin) % this._defaults.stepMillisec)), 10),
					microsecMax = parseInt((this._defaults.microsecMax - ((this._defaults.microsecMax - this._defaults.microsecMin) % this._defaults.stepMicrosec)), 10);

				if (this.hour_slider) {
					this.control.options(this, this.hour_slider, 'hour', { min: this._defaults.hourMin, max: hourMax, step: this._defaults.stepHour });
					this.control.value(this, this.hour_slider, 'hour', this.hour - (this.hour % this._defaults.stepHour));
				}
				if (this.minute_slider) {
					this.control.options(this, this.minute_slider, 'minute', { min: this._defaults.minuteMin, max: minMax, step: this._defaults.stepMinute });
					this.control.value(this, this.minute_slider, 'minute', this.minute - (this.minute % this._defaults.stepMinute));
				}
				if (this.second_slider) {
					this.control.options(this, this.second_slider, 'second', { min: this._defaults.secondMin, max: secMax, step: this._defaults.stepSecond });
					this.control.value(this, this.second_slider, 'second', this.second - (this.second % this._defaults.stepSecond));
				}
				if (this.millisec_slider) {
					this.control.options(this, this.millisec_slider, 'millisec', { min: this._defaults.millisecMin, max: millisecMax, step: this._defaults.stepMillisec });
					this.control.value(this, this.millisec_slider, 'millisec', this.millisec - (this.millisec % this._defaults.stepMillisec));
				}
				if (this.microsec_slider) {
					this.control.options(this, this.microsec_slider, 'microsec', { min: this._defaults.microsecMin, max: microsecMax, step: this._defaults.stepMicrosec });
					this.control.value(this, this.microsec_slider, 'microsec', this.microsec - (this.microsec % this._defaults.stepMicrosec));
				}
			}

		},

		/*
		* when a slider moves, set the internal time...
		* on time change is also called when the time is updated in the text field
		*/
		_onTimeChange: function () {
			if (!this._defaults.showTimepicker) {
                                return;
			}
			var hour = (this.hour_slider) ? this.control.value(this, this.hour_slider, 'hour') : false,
				minute = (this.minute_slider) ? this.control.value(this, this.minute_slider, 'minute') : false,
				second = (this.second_slider) ? this.control.value(this, this.second_slider, 'second') : false,
				millisec = (this.millisec_slider) ? this.control.value(this, this.millisec_slider, 'millisec') : false,
				microsec = (this.microsec_slider) ? this.control.value(this, this.microsec_slider, 'microsec') : false,
				timezone = (this.timezone_select) ? this.timezone_select.val() : false,
				o = this._defaults,
				pickerTimeFormat = o.pickerTimeFormat || o.timeFormat,
				pickerTimeSuffix = o.pickerTimeSuffix || o.timeSuffix;

			if (typeof(hour) === 'object') {
				hour = false;
			}
			if (typeof(minute) === 'object') {
				minute = false;
			}
			if (typeof(second) === 'object') {
				second = false;
			}
			if (typeof(millisec) === 'object') {
				millisec = false;
			}
			if (typeof(microsec) === 'object') {
				microsec = false;
			}
			if (typeof(timezone) === 'object') {
				timezone = false;
			}

			if (hour !== false) {
				hour = parseInt(hour, 10);
			}
			if (minute !== false) {
				minute = parseInt(minute, 10);
			}
			if (second !== false) {
				second = parseInt(second, 10);
			}
			if (millisec !== false) {
				millisec = parseInt(millisec, 10);
			}
			if (microsec !== false) {
				microsec = parseInt(microsec, 10);
			}
			if (timezone !== false) {
				timezone = timezone.toString();
			}

			var ampm = o[hour < 12 ? 'amNames' : 'pmNames'][0];

			// If the update was done in the input field, the input field should not be updated.
			// If the update was done using the sliders, update the input field.
			var hasChanged = (
						hour !== parseInt(this.hour,10) || // sliders should all be numeric
						minute !== parseInt(this.minute,10) || 
						second !== parseInt(this.second,10) || 
						millisec !== parseInt(this.millisec,10) || 
						microsec !== parseInt(this.microsec,10) || 
						(this.ampm.length > 0 && (hour < 12) !== ($.inArray(this.ampm.toUpperCase(), this.amNames) !== -1)) || 
						(this.timezone !== null && timezone !== this.timezone.toString()) // could be numeric or "EST" format, so use toString()
					);

			if (hasChanged) {

				if (hour !== false) {
					this.hour = hour;
				}
				if (minute !== false) {
					this.minute = minute;
				}
				if (second !== false) {
					this.second = second;
				}
				if (millisec !== false) {
					this.millisec = millisec;
				}
				if (microsec !== false) {
					this.microsec = microsec;
				}
				if (timezone !== false) {
					this.timezone = timezone;
				}

				if (!this.inst) {
					this.inst = $.datepicker._getInst(this.$input[0]);
				}

				this._limitMinMaxDateTime(this.inst, true);
			}
			if (this.support.ampm) {
				this.ampm = ampm;
			}

			// Updates the time within the timepicker
			this.formattedTime = $.datepicker.formatTime(o.timeFormat, this, o);
			if (this.$timeObj) {
				if (pickerTimeFormat === o.timeFormat) {
					this.$timeObj.text(this.formattedTime + pickerTimeSuffix);
				}
				else {
					this.$timeObj.text($.datepicker.formatTime(pickerTimeFormat, this, o) + pickerTimeSuffix);
				}
			}

			this.timeDefined = true;
			if (hasChanged) {
				this._updateDateTime();
				//this.$input.focus(); // may automatically open the picker on setDate
			}
		},

		/*
		* call custom onSelect.
		* bind to sliders slidestop, and grid click.
		*/
		_onSelectHandler: function () {
			var onSelect = this._defaults.onSelect || this.inst.settings.onSelect;
			var inputEl = this.$input ? this.$input[0] : null;
			if (onSelect && inputEl) {
				onSelect.apply(inputEl, [this.formattedDateTime, this]);
			}
		},

		/*
		* update our input with the new date time..
		*/
		_updateDateTime: function (dp_inst) {
			dp_inst = this.inst || dp_inst;
			var dtTmp = (dp_inst.currentYear > 0? 
							new Date(dp_inst.currentYear, dp_inst.currentMonth, dp_inst.currentDay) : 
							new Date(dp_inst.selectedYear, dp_inst.selectedMonth, dp_inst.selectedDay)),
				dt = $.datepicker._daylightSavingAdjust(dtTmp),
				//dt = $.datepicker._daylightSavingAdjust(new Date(dp_inst.selectedYear, dp_inst.selectedMonth, dp_inst.selectedDay)),
				//dt = $.datepicker._daylightSavingAdjust(new Date(dp_inst.currentYear, dp_inst.currentMonth, dp_inst.currentDay)),
				dateFmt = $.datepicker._get(dp_inst, 'dateFormat'),
				formatCfg = $.datepicker._getFormatConfig(dp_inst),
				timeAvailable = dt !== null && this.timeDefined;
			this.formattedDate = $.datepicker.formatDate(dateFmt, (dt === null ? new Date() : dt), formatCfg);
			var formattedDateTime = this.formattedDate;
			
			// if a slider was changed but datepicker doesn't have a value yet, set it
			if (dp_inst.lastVal === "") {
                dp_inst.currentYear = dp_inst.selectedYear;
                dp_inst.currentMonth = dp_inst.selectedMonth;
                dp_inst.currentDay = dp_inst.selectedDay;
            }

			/*
			* remove following lines to force every changes in date picker to change the input value
			* Bug descriptions: when an input field has a default value, and click on the field to pop up the date picker. 
			* If the user manually empty the value in the input field, the date picker will never change selected value.
			*/
			//if (dp_inst.lastVal !== undefined && (dp_inst.lastVal.length > 0 && this.$input.val().length === 0)) {
			//	return;
			//}

			if (this._defaults.timeOnly === true && this._defaults.timeOnlyShowDate === false) {
				formattedDateTime = this.formattedTime;
			} else if ((this._defaults.timeOnly !== true && (this._defaults.alwaysSetTime || timeAvailable)) || (this._defaults.timeOnly === true && this._defaults.timeOnlyShowDate === true)) {
				formattedDateTime += this._defaults.separator + this.formattedTime + this._defaults.timeSuffix;
			}

			this.formattedDateTime = formattedDateTime;

			if (!this._defaults.showTimepicker) {
				this.$input.val(this.formattedDate);
			} else if (this.$altInput && this._defaults.timeOnly === false && this._defaults.altFieldTimeOnly === true) {
				this.$altInput.val(this.formattedTime);
				this.$input.val(this.formattedDate);
			} else if (this.$altInput) {
				this.$input.val(formattedDateTime);
				var altFormattedDateTime = '',
					altSeparator = this._defaults.altSeparator !== null ? this._defaults.altSeparator : this._defaults.separator,
					altTimeSuffix = this._defaults.altTimeSuffix !== null ? this._defaults.altTimeSuffix : this._defaults.timeSuffix;
				
				if (!this._defaults.timeOnly) {
					if (this._defaults.altFormat) {
						altFormattedDateTime = $.datepicker.formatDate(this._defaults.altFormat, (dt === null ? new Date() : dt), formatCfg);
					}
					else {
						altFormattedDateTime = this.formattedDate;
					}

					if (altFormattedDateTime) {
						altFormattedDateTime += altSeparator;
					}
				}

				if (this._defaults.altTimeFormat !== null) {
					altFormattedDateTime += $.datepicker.formatTime(this._defaults.altTimeFormat, this, this._defaults) + altTimeSuffix;
				}
				else {
					altFormattedDateTime += this.formattedTime + altTimeSuffix;
				}
				this.$altInput.val(altFormattedDateTime);
			} else {
				this.$input.val(formattedDateTime);
			}

			this.$input.trigger("change");
		},

		_onFocus: function () {
			if (!this.$input.val() && this._defaults.defaultValue) {
				this.$input.val(this._defaults.defaultValue);
				var inst = $.datepicker._getInst(this.$input.get(0)),
					tp_inst = $.datepicker._get(inst, 'timepicker');
				if (tp_inst) {
					if (tp_inst._defaults.timeOnly && (inst.input.val() !== inst.lastVal)) {
						try {
							$.datepicker._updateDatepicker(inst);
						} catch (err) {
							$.timepicker.log(err);
						}
					}
				}
			}
		},

		/*
		* Small abstraction to control types
		* We can add more, just be sure to follow the pattern: create, options, value
		*/
		_controls: {
			// slider methods
			slider: {
				create: function (tp_inst, obj, unit, val, min, max, step) {
					var rtl = tp_inst._defaults.isRTL; // if rtl go -60->0 instead of 0->60
					return obj.prop('slide', null).slider({
						orientation: "horizontal",
						value: rtl ? val * -1 : val,
						min: rtl ? max * -1 : min,
						max: rtl ? min * -1 : max,
						step: step,
						slide: function (event, ui) {
							tp_inst.control.value(tp_inst, $(this), unit, rtl ? ui.value * -1 : ui.value);
							tp_inst._onTimeChange();
						},
						stop: function (event, ui) {
							tp_inst._onSelectHandler();
						}
					});	
				},
				options: function (tp_inst, obj, unit, opts, val) {
					if (tp_inst._defaults.isRTL) {
						if (typeof(opts) === 'string') {
							if (opts === 'min' || opts === 'max') {
								if (val !== undefined) {
									return obj.slider(opts, val * -1);
								}
								return Math.abs(obj.slider(opts));
							}
							return obj.slider(opts);
						}
						var min = opts.min, 
							max = opts.max;
						opts.min = opts.max = null;
						if (min !== undefined) {
							opts.max = min * -1;
						}
						if (max !== undefined) {
							opts.min = max * -1;
						}
						return obj.slider(opts);
					}
					if (typeof(opts) === 'string' && val !== undefined) {
						return obj.slider(opts, val);
					}
					return obj.slider(opts);
				},
				value: function (tp_inst, obj, unit, val) {
					if (tp_inst._defaults.isRTL) {
						if (val !== undefined) {
							return obj.slider('value', val * -1);
						}
						return Math.abs(obj.slider('value'));
					}
					if (val !== undefined) {
						return obj.slider('value', val);
					}
					return obj.slider('value');
				}
			},
			// select methods
			select: {
				create: function (tp_inst, obj, unit, val, min, max, step) {
					var sel = '<select class="ui-timepicker-select ui-state-default ui-corner-all" data-unit="' + unit + '" data-min="' + min + '" data-max="' + max + '" data-step="' + step + '">',
						format = tp_inst._defaults.pickerTimeFormat || tp_inst._defaults.timeFormat;

					for (var i = min; i <= max; i += step) {
						sel += '<option value="' + i + '"' + (i === val ? ' selected' : '') + '>';
						if (unit === 'hour') {
							sel += $.datepicker.formatTime($.trim(format.replace(/[^ht ]/ig, '')), {hour: i}, tp_inst._defaults);
						}
						else if (unit === 'millisec' || unit === 'microsec' || i >= 10) { sel += i; }
						else {sel += '0' + i.toString(); }
						sel += '</option>';
					}
					sel += '</select>';

					obj.children('select').remove();

					$(sel).appendTo(obj).change(function (e) {
						tp_inst._onTimeChange();
						tp_inst._onSelectHandler();
						tp_inst._afterInject();
					});

					return obj;
				},
				options: function (tp_inst, obj, unit, opts, val) {
					var o = {},
						$t = obj.children('select');
					if (typeof(opts) === 'string') {
						if (val === undefined) {
							return $t.data(opts);
						}
						o[opts] = val;	
					}
					else { o = opts; }
					return tp_inst.control.create(tp_inst, obj, $t.data('unit'), $t.val(), o.min>=0 ? o.min : $t.data('min'), o.max || $t.data('max'), o.step || $t.data('step'));
				},
				value: function (tp_inst, obj, unit, val) {
					var $t = obj.children('select');
					if (val !== undefined) {
						return $t.val(val);
					}
					return $t.val();
				}
			}
		} // end _controls

	});

	$.fn.extend({
		/*
		* shorthand just to use timepicker.
		*/
		timepicker: function (o) {
			o = o || {};
			var tmp_args = Array.prototype.slice.call(arguments);

			if (typeof o === 'object') {
				tmp_args[0] = $.extend(o, {
					timeOnly: true
				});
			}

			return $(this).each(function () {
				$.fn.datetimepicker.apply($(this), tmp_args);
			});
		},

		/*
		* extend timepicker to datepicker
		*/
		datetimepicker: function (o) {
			o = o || {};
			var tmp_args = arguments;

			if (typeof(o) === 'string') {
				if (o === 'getDate'  || (o === 'option' && tmp_args.length === 2 && typeof (tmp_args[1]) === 'string')) {
					return $.fn.datepicker.apply($(this[0]), tmp_args);
				} else {
					return this.each(function () {
						var $t = $(this);
						$t.datepicker.apply($t, tmp_args);
					});
				}
			} else {
				return this.each(function () {
					var $t = $(this);
					$t.datepicker($.timepicker._newInst($t, o)._defaults);
				});
			}
		}
	});

	/*
	* Public Utility to parse date and time
	*/
	$.datepicker.parseDateTime = function (dateFormat, timeFormat, dateTimeString, dateSettings, timeSettings) {
		var parseRes = parseDateTimeInternal(dateFormat, timeFormat, dateTimeString, dateSettings, timeSettings);
		if (parseRes.timeObj) {
			var t = parseRes.timeObj;
			parseRes.date.setHours(t.hour, t.minute, t.second, t.millisec);
			parseRes.date.setMicroseconds(t.microsec);
		}

		return parseRes.date;
	};

	/*
	* Public utility to parse time
	*/
	$.datepicker.parseTime = function (timeFormat, timeString, options) {
		var o = extendRemove(extendRemove({}, $.timepicker._defaults), options || {}),
			iso8601 = (timeFormat.replace(/\'.*?\'/g, '').indexOf('Z') !== -1);

		// Strict parse requires the timeString to match the timeFormat exactly
		var strictParse = function (f, s, o) {

			// pattern for standard and localized AM/PM markers
			var getPatternAmpm = function (amNames, pmNames) {
				var markers = [];
				if (amNames) {
					$.merge(markers, amNames);
				}
				if (pmNames) {
					$.merge(markers, pmNames);
				}
				markers = $.map(markers, function (val) {
					return val.replace(/[.*+?|()\[\]{}\\]/g, '\\$&');
				});
				return '(' + markers.join('|') + ')?';
			};

			// figure out position of time elements.. cause js cant do named captures
			var getFormatPositions = function (timeFormat) {
				var finds = timeFormat.toLowerCase().match(/(h{1,2}|m{1,2}|s{1,2}|l{1}|c{1}|t{1,2}|z|'.*?')/g),
					orders = {
						h: -1,
						m: -1,
						s: -1,
						l: -1,
						c: -1,
						t: -1,
						z: -1
					};

				if (finds) {
					for (var i = 0; i < finds.length; i++) {
						if (orders[finds[i].toString().charAt(0)] === -1) {
							orders[finds[i].toString().charAt(0)] = i + 1;
						}
					}
				}
				return orders;
			};

			var regstr = '^' + f.toString()
					.replace(/([hH]{1,2}|mm?|ss?|[tT]{1,2}|[zZ]|[lc]|'.*?')/g, function (match) {
							var ml = match.length;
							switch (match.charAt(0).toLowerCase()) {
							case 'h':
								return ml === 1 ? '(\\d?\\d)' : '(\\d{' + ml + '})';
							case 'm':
								return ml === 1 ? '(\\d?\\d)' : '(\\d{' + ml + '})';
							case 's':
								return ml === 1 ? '(\\d?\\d)' : '(\\d{' + ml + '})';
							case 'l':
								return '(\\d?\\d?\\d)';
							case 'c':
								return '(\\d?\\d?\\d)';
							case 'z':
								return '(z|[-+]\\d\\d:?\\d\\d|\\S+)?';
							case 't':
								return getPatternAmpm(o.amNames, o.pmNames);
							default:    // literal escaped in quotes
								return '(' + match.replace(/\'/g, "").replace(/(\.|\$|\^|\\|\/|\(|\)|\[|\]|\?|\+|\*)/g, function (m) { return "\\" + m; }) + ')?';
							}
						})
					.replace(/\s/g, '\\s?') +
					o.timeSuffix + '$',
				order = getFormatPositions(f),
				ampm = '',
				treg;

			treg = s.match(new RegExp(regstr, 'i'));

			var resTime = {
				hour: 0,
				minute: 0,
				second: 0,
				millisec: 0,
				microsec: 0
			};

			if (treg) {
				if (order.t !== -1) {
					if (treg[order.t] === undefined || treg[order.t].length === 0) {
						ampm = '';
						resTime.ampm = '';
					} else {
						ampm = $.inArray(treg[order.t].toUpperCase(), $.map(o.amNames, function (x,i) { return x.toUpperCase(); })) !== -1 ? 'AM' : 'PM';
						resTime.ampm = o[ampm === 'AM' ? 'amNames' : 'pmNames'][0];
					}
				}

				if (order.h !== -1) {
					if (ampm === 'AM' && treg[order.h] === '12') {
						resTime.hour = 0; // 12am = 0 hour
					} else {
						if (ampm === 'PM' && treg[order.h] !== '12') {
							resTime.hour = parseInt(treg[order.h], 10) + 12; // 12pm = 12 hour, any other pm = hour + 12
						} else {
							resTime.hour = Number(treg[order.h]);
						}
					}
				}

				if (order.m !== -1) {
					resTime.minute = Number(treg[order.m]);
				}
				if (order.s !== -1) {
					resTime.second = Number(treg[order.s]);
				}
				if (order.l !== -1) {
					resTime.millisec = Number(treg[order.l]);
				}
				if (order.c !== -1) {
					resTime.microsec = Number(treg[order.c]);
				}
				if (order.z !== -1 && treg[order.z] !== undefined) {
					resTime.timezone = $.timepicker.timezoneOffsetNumber(treg[order.z]);
				}


				return resTime;
			}
			return false;
		};// end strictParse

		// First try JS Date, if that fails, use strictParse
		var looseParse = function (f, s, o) {
			try {
				var d = new Date('2012-01-01 ' + s);
				if (isNaN(d.getTime())) {
					d = new Date('2012-01-01T' + s);
					if (isNaN(d.getTime())) {
						d = new Date('01/01/2012 ' + s);
						if (isNaN(d.getTime())) {
							throw "Unable to parse time with native Date: " + s;
						}
					}
				}

				return {
					hour: d.getHours(),
					minute: d.getMinutes(),
					second: d.getSeconds(),
					millisec: d.getMilliseconds(),
					microsec: d.getMicroseconds(),
					timezone: d.getTimezoneOffset() * -1
				};
			}
			catch (err) {
				try {
					return strictParse(f, s, o);
				}
				catch (err2) {
					$.timepicker.log("Unable to parse \ntimeString: " + s + "\ntimeFormat: " + f);
				}				
			}
			return false;
		}; // end looseParse
		
		if (typeof o.parse === "function") {
			return o.parse(timeFormat, timeString, o);
		}
		if (o.parse === 'loose') {
			return looseParse(timeFormat, timeString, o);
		}
		return strictParse(timeFormat, timeString, o);
	};

	/**
	 * Public utility to format the time
	 * @param {string} format format of the time
	 * @param {Object} time Object not a Date for timezones
	 * @param {Object} [options] essentially the regional[].. amNames, pmNames, ampm
	 * @returns {string} the formatted time
	 */
	$.datepicker.formatTime = function (format, time, options) {
		options = options || {};
		options = $.extend({}, $.timepicker._defaults, options);
		time = $.extend({
			hour: 0,
			minute: 0,
			second: 0,
			millisec: 0,
			microsec: 0,
			timezone: null
		}, time);

		var tmptime = format,
			ampmName = options.amNames[0],
			hour = parseInt(time.hour, 10);

		if (hour > 11) {
			ampmName = options.pmNames[0];
		}

		tmptime = tmptime.replace(/(?:HH?|hh?|mm?|ss?|[tT]{1,2}|[zZ]|[lc]|'.*?')/g, function (match) {
			switch (match) {
			case 'HH':
				return ('0' + hour).slice(-2);
			case 'H':
				return hour;
			case 'hh':
				return ('0' + convert24to12(hour)).slice(-2);
			case 'h':
				return convert24to12(hour);
			case 'mm':
				return ('0' + time.minute).slice(-2);
			case 'm':
				return time.minute;
			case 'ss':
				return ('0' + time.second).slice(-2);
			case 's':
				return time.second;
			case 'l':
				return ('00' + time.millisec).slice(-3);
			case 'c':
				return ('00' + time.microsec).slice(-3);
			case 'z':
				return $.timepicker.timezoneOffsetString(time.timezone === null ? options.timezone : time.timezone, false);
			case 'Z':
				return $.timepicker.timezoneOffsetString(time.timezone === null ? options.timezone : time.timezone, true);
			case 'T':
				return ampmName.charAt(0).toUpperCase();
			case 'TT':
				return ampmName.toUpperCase();
			case 't':
				return ampmName.charAt(0).toLowerCase();
			case 'tt':
				return ampmName.toLowerCase();
			default:
				return match.replace(/'/g, "");
			}
		});

		return tmptime;
	};

	/*
	* the bad hack :/ override datepicker so it doesn't close on select
	// inspired: http://stackoverflow.com/questions/1252512/jquery-datepicker-prevent-closing-picker-when-clicking-a-date/1762378#1762378
	*/
	$.datepicker._base_selectDate = $.datepicker._selectDate;
	$.datepicker._selectDate = function (id, dateStr) {
		var inst = this._getInst($(id)[0]),
			tp_inst = this._get(inst, 'timepicker'),
			was_inline;

		if (tp_inst && inst.settings.showTimepicker) {
			tp_inst._limitMinMaxDateTime(inst, true);
			was_inline = inst.inline;
			inst.inline = inst.stay_open = true;
			//This way the onSelect handler called from calendarpicker get the full dateTime
			this._base_selectDate(id, dateStr);
			inst.inline = was_inline;
			inst.stay_open = false;
			this._notifyChange(inst);
			this._updateDatepicker(inst);
		} else {
			this._base_selectDate(id, dateStr);
		}
	};

	/*
	* second bad hack :/ override datepicker so it triggers an event when changing the input field
	* and does not redraw the datepicker on every selectDate event
	*/
	$.datepicker._base_updateDatepicker = $.datepicker._updateDatepicker;
	$.datepicker._updateDatepicker = function (inst) {

		// don't popup the datepicker if there is another instance already opened
		var input = inst.input[0];
		if ($.datepicker._curInst && $.datepicker._curInst !== inst && $.datepicker._datepickerShowing && $.datepicker._lastInput !== input) {
			return;
		}

		if (typeof(inst.stay_open) !== 'boolean' || inst.stay_open === false) {

			this._base_updateDatepicker(inst);

			// Reload the time control when changing something in the input text field.
			var tp_inst = this._get(inst, 'timepicker');
			if (tp_inst) {
				tp_inst._addTimePicker(inst);
			}
		}
	};

	/*
	* third bad hack :/ override datepicker so it allows spaces and colon in the input field
	*/
	$.datepicker._base_doKeyPress = $.datepicker._doKeyPress;
	$.datepicker._doKeyPress = function (event) {
		var inst = $.datepicker._getInst(event.target),
			tp_inst = $.datepicker._get(inst, 'timepicker');

		if (tp_inst) {
			if ($.datepicker._get(inst, 'constrainInput')) {
				var ampm = tp_inst.support.ampm,
					tz = tp_inst._defaults.showTimezone !== null ? tp_inst._defaults.showTimezone : tp_inst.support.timezone,
					dateChars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat')),
					datetimeChars = tp_inst._defaults.timeFormat.toString()
											.replace(/[hms]/g, '')
											.replace(/TT/g, ampm ? 'APM' : '')
											.replace(/Tt/g, ampm ? 'AaPpMm' : '')
											.replace(/tT/g, ampm ? 'AaPpMm' : '')
											.replace(/T/g, ampm ? 'AP' : '')
											.replace(/tt/g, ampm ? 'apm' : '')
											.replace(/t/g, ampm ? 'ap' : '') + 
											" " + tp_inst._defaults.separator + 
											tp_inst._defaults.timeSuffix + 
											(tz ? tp_inst._defaults.timezoneList.join('') : '') + 
											(tp_inst._defaults.amNames.join('')) + (tp_inst._defaults.pmNames.join('')) + 
											dateChars,
					chr = String.fromCharCode(event.charCode === undefined ? event.keyCode : event.charCode);
				return event.ctrlKey || (chr < ' ' || !dateChars || datetimeChars.indexOf(chr) > -1);
			}
		}

		return $.datepicker._base_doKeyPress(event);
	};

	/*
	* Fourth bad hack :/ override _updateAlternate function used in inline mode to init altField
	* Update any alternate field to synchronise with the main field.
	*/
	$.datepicker._base_updateAlternate = $.datepicker._updateAlternate;
	$.datepicker._updateAlternate = function (inst) {
		var tp_inst = this._get(inst, 'timepicker');
		if (tp_inst) {
			var altField = tp_inst._defaults.altField;
			if (altField) { // update alternate field too
				var altFormat = tp_inst._defaults.altFormat || tp_inst._defaults.dateFormat,
					date = this._getDate(inst),
					formatCfg = $.datepicker._getFormatConfig(inst),
					altFormattedDateTime = '', 
					altSeparator = tp_inst._defaults.altSeparator ? tp_inst._defaults.altSeparator : tp_inst._defaults.separator, 
					altTimeSuffix = tp_inst._defaults.altTimeSuffix ? tp_inst._defaults.altTimeSuffix : tp_inst._defaults.timeSuffix,
					altTimeFormat = tp_inst._defaults.altTimeFormat !== null ? tp_inst._defaults.altTimeFormat : tp_inst._defaults.timeFormat;
				
				altFormattedDateTime += $.datepicker.formatTime(altTimeFormat, tp_inst, tp_inst._defaults) + altTimeSuffix;
				if (!tp_inst._defaults.timeOnly && !tp_inst._defaults.altFieldTimeOnly && date !== null) {
					if (tp_inst._defaults.altFormat) {
						altFormattedDateTime = $.datepicker.formatDate(tp_inst._defaults.altFormat, date, formatCfg) + altSeparator + altFormattedDateTime;
					}
					else {
						altFormattedDateTime = tp_inst.formattedDate + altSeparator + altFormattedDateTime;
					}
				}
				$(altField).val( inst.input.val() ? altFormattedDateTime : "");
			}
		}
		else {
			$.datepicker._base_updateAlternate(inst);	
		}
	};

	/*
	* Override key up event to sync manual input changes.
	*/
	$.datepicker._base_doKeyUp = $.datepicker._doKeyUp;
	$.datepicker._doKeyUp = function (event) {
		var inst = $.datepicker._getInst(event.target),
			tp_inst = $.datepicker._get(inst, 'timepicker');

		if (tp_inst) {
			if (tp_inst._defaults.timeOnly && (inst.input.val() !== inst.lastVal)) {
				try {
					$.datepicker._updateDatepicker(inst);
				} catch (err) {
					$.timepicker.log(err);
				}
			}
		}

		return $.datepicker._base_doKeyUp(event);
	};

	/*
	* override "Today" button to also grab the time.
	*/
	$.datepicker._base_gotoToday = $.datepicker._gotoToday;
	$.datepicker._gotoToday = function (id) {
		var inst = this._getInst($(id)[0]),
			$dp = inst.dpDiv;
		var tp_inst = this._get(inst, 'timepicker');
		selectLocalTimezone(tp_inst);
		var now = new Date();
		this._setTime(inst, now);
		this._setDate(inst, now);
		this._base_gotoToday(id);
	};

	/*
	* Disable & enable the Time in the datetimepicker
	*/
	$.datepicker._disableTimepickerDatepicker = function (target) {
		var inst = this._getInst(target);
		if (!inst) {
			return;
		}

		var tp_inst = this._get(inst, 'timepicker');
		$(target).datepicker('getDate'); // Init selected[Year|Month|Day]
		if (tp_inst) {
			inst.settings.showTimepicker = false;
			tp_inst._defaults.showTimepicker = false;
			tp_inst._updateDateTime(inst);
		}
	};

	$.datepicker._enableTimepickerDatepicker = function (target) {
		var inst = this._getInst(target);
		if (!inst) {
			return;
		}

		var tp_inst = this._get(inst, 'timepicker');
		$(target).datepicker('getDate'); // Init selected[Year|Month|Day]
		if (tp_inst) {
			inst.settings.showTimepicker = true;
			tp_inst._defaults.showTimepicker = true;
			tp_inst._addTimePicker(inst); // Could be disabled on page load
			tp_inst._updateDateTime(inst);
		}
	};

	/*
	* Create our own set time function
	*/
	$.datepicker._setTime = function (inst, date) {
		var tp_inst = this._get(inst, 'timepicker');
		if (tp_inst) {
			var defaults = tp_inst._defaults;

			// calling _setTime with no date sets time to defaults
			tp_inst.hour = date ? date.getHours() : defaults.hour;
			tp_inst.minute = date ? date.getMinutes() : defaults.minute;
			tp_inst.second = date ? date.getSeconds() : defaults.second;
			tp_inst.millisec = date ? date.getMilliseconds() : defaults.millisec;
			tp_inst.microsec = date ? date.getMicroseconds() : defaults.microsec;

			//check if within min/max times.. 
			tp_inst._limitMinMaxDateTime(inst, true);

			tp_inst._onTimeChange();
			tp_inst._updateDateTime(inst);
		}
	};

	/*
	* Create new public method to set only time, callable as $().datepicker('setTime', date)
	*/
	$.datepicker._setTimeDatepicker = function (target, date, withDate) {
		var inst = this._getInst(target);
		if (!inst) {
			return;
		}

		var tp_inst = this._get(inst, 'timepicker');

		if (tp_inst) {
			this._setDateFromField(inst);
			var tp_date;
			if (date) {
				if (typeof date === "string") {
					tp_inst._parseTime(date, withDate);
					tp_date = new Date();
					tp_date.setHours(tp_inst.hour, tp_inst.minute, tp_inst.second, tp_inst.millisec);
					tp_date.setMicroseconds(tp_inst.microsec);
				} else {
					tp_date = new Date(date.getTime());
					tp_date.setMicroseconds(date.getMicroseconds());
				}
				if (tp_date.toString() === 'Invalid Date') {
					tp_date = undefined;
				}
				this._setTime(inst, tp_date);
			}
		}

	};

	/*
	* override setDate() to allow setting time too within Date object
	*/
	$.datepicker._base_setDateDatepicker = $.datepicker._setDateDatepicker;
	$.datepicker._setDateDatepicker = function (target, _date) {
		var inst = this._getInst(target);
		var date = _date;
		if (!inst) {
			return;
		}

		if (typeof(_date) === 'string') {
			date = new Date(_date);
			if (!date.getTime()) {
				this._base_setDateDatepicker.apply(this, arguments);
				date = $(target).datepicker('getDate');
			}
		}

		var tp_inst = this._get(inst, 'timepicker');
		var tp_date;
		if (date instanceof Date) {
			tp_date = new Date(date.getTime());
			tp_date.setMicroseconds(date.getMicroseconds());
		} else {
			tp_date = date;
		}
		
		// This is important if you are using the timezone option, javascript's Date 
		// object will only return the timezone offset for the current locale, so we 
		// adjust it accordingly.  If not using timezone option this won't matter..
		// If a timezone is different in tp, keep the timezone as is
		if (tp_inst && tp_date) {
			// look out for DST if tz wasn't specified
			if (!tp_inst.support.timezone && tp_inst._defaults.timezone === null) {
				tp_inst.timezone = tp_date.getTimezoneOffset() * -1;
			}
			date = $.timepicker.timezoneAdjust(date, tp_inst.timezone);
			tp_date = $.timepicker.timezoneAdjust(tp_date, tp_inst.timezone);
		}

		this._updateDatepicker(inst);
		this._base_setDateDatepicker.apply(this, arguments);
		this._setTimeDatepicker(target, tp_date, true);
	};

	/*
	* override getDate() to allow getting time too within Date object
	*/
	$.datepicker._base_getDateDatepicker = $.datepicker._getDateDatepicker;
	$.datepicker._getDateDatepicker = function (target, noDefault) {
		var inst = this._getInst(target);
		if (!inst) {
			return;
		}

		var tp_inst = this._get(inst, 'timepicker');

		if (tp_inst) {
			// if it hasn't yet been defined, grab from field
			if (inst.lastVal === undefined) {
				this._setDateFromField(inst, noDefault);
			}

			var date = this._getDate(inst);
			var currDT = $.trim((tp_inst.$altInput && tp_inst._defaults.altFieldTimeOnly) ? tp_inst.$input.val() + ' ' + tp_inst.$altInput.val() : tp_inst.$input.val());
			if (date && tp_inst._parseTime(currDT, !inst.settings.timeOnly)) {
				date.setHours(tp_inst.hour, tp_inst.minute, tp_inst.second, tp_inst.millisec);
				date.setMicroseconds(tp_inst.microsec);

				// This is important if you are using the timezone option, javascript's Date 
				// object will only return the timezone offset for the current locale, so we 
				// adjust it accordingly.  If not using timezone option this won't matter..
				if (tp_inst.timezone != null) {
					// look out for DST if tz wasn't specified
					if (!tp_inst.support.timezone && tp_inst._defaults.timezone === null) {
						tp_inst.timezone = date.getTimezoneOffset() * -1;
					}
					date = $.timepicker.timezoneAdjust(date, tp_inst.timezone);
				}
			}
			return date;
		}
		return this._base_getDateDatepicker(target, noDefault);
	};

	/*
	* override parseDate() because UI 1.8.14 throws an error about "Extra characters"
	* An option in datapicker to ignore extra format characters would be nicer.
	*/
	$.datepicker._base_parseDate = $.datepicker.parseDate;
	$.datepicker.parseDate = function (format, value, settings) {
		var date;
		try {
			date = this._base_parseDate(format, value, settings);
		} catch (err) {
			// Hack!  The error message ends with a colon, a space, and
			// the "extra" characters.  We rely on that instead of
			// attempting to perfectly reproduce the parsing algorithm.
			if (err.indexOf(":") >= 0) {
				date = this._base_parseDate(format, value.substring(0, value.length - (err.length - err.indexOf(':') - 2)), settings);
				$.timepicker.log("Error parsing the date string: " + err + "\ndate string = " + value + "\ndate format = " + format);
			} else {
				throw err;
			}
		}
		return date;
	};

	/*
	* override formatDate to set date with time to the input
	*/
	$.datepicker._base_formatDate = $.datepicker._formatDate;
	$.datepicker._formatDate = function (inst, day, month, year) {
		var tp_inst = this._get(inst, 'timepicker');
		if (tp_inst) {
			tp_inst._updateDateTime(inst);
			return tp_inst.$input.val();
		}
		return this._base_formatDate(inst);
	};

	/*
	* override options setter to add time to maxDate(Time) and minDate(Time). MaxDate
	*/
	$.datepicker._base_optionDatepicker = $.datepicker._optionDatepicker;
	$.datepicker._optionDatepicker = function (target, name, value) {
		var inst = this._getInst(target),
			name_clone;
		if (!inst) {
			return null;
		}

		var tp_inst = this._get(inst, 'timepicker');
		if (tp_inst) {
			var min = null,
				max = null,
				onselect = null,
				overrides = tp_inst._defaults.evnts,
				fns = {},
				prop,
				ret,
				oldVal,
				$target;
			if (typeof name === 'string') { // if min/max was set with the string
				if (name === 'minDate' || name === 'minDateTime') {
					min = value;
				} else if (name === 'maxDate' || name === 'maxDateTime') {
					max = value;
				} else if (name === 'onSelect') {
					onselect = value;
				} else if (overrides.hasOwnProperty(name)) {
					if (typeof (value) === 'undefined') {
						return overrides[name];
					}
					fns[name] = value;
					name_clone = {}; //empty results in exiting function after overrides updated
				}
			} else if (typeof name === 'object') { //if min/max was set with the JSON
				if (name.minDate) {
					min = name.minDate;
				} else if (name.minDateTime) {
					min = name.minDateTime;
				} else if (name.maxDate) {
					max = name.maxDate;
				} else if (name.maxDateTime) {
					max = name.maxDateTime;
				}
				for (prop in overrides) {
					if (overrides.hasOwnProperty(prop) && name[prop]) {
						fns[prop] = name[prop];
					}
				}
			}
			for (prop in fns) {
				if (fns.hasOwnProperty(prop)) {
					overrides[prop] = fns[prop];
					if (!name_clone) { name_clone = $.extend({}, name); }
					delete name_clone[prop];
				}
			}
			if (name_clone && isEmptyObject(name_clone)) { return; }
			if (min) { //if min was set
				if (min === 0) {
					min = new Date();
				} else {
					min = new Date(min);
				}
				tp_inst._defaults.minDate = min;
				tp_inst._defaults.minDateTime = min;
			} else if (max) { //if max was set
				if (max === 0) {
					max = new Date();
				} else {
					max = new Date(max);
				}
				tp_inst._defaults.maxDate = max;
				tp_inst._defaults.maxDateTime = max;
			} else if (onselect) {
				tp_inst._defaults.onSelect = onselect;
			}

			// Datepicker will override our date when we call _base_optionDatepicker when 
			// calling minDate/maxDate, so we will first grab the value, call 
			// _base_optionDatepicker, then set our value back.
			if(min || max){
				$target = $(target);
				oldVal = $target.datetimepicker('getDate');
				ret = this._base_optionDatepicker.call($.datepicker, target, name_clone || name, value);
				$target.datetimepicker('setDate', oldVal);
				return ret;
			}
		}
		if (value === undefined) {
			return this._base_optionDatepicker.call($.datepicker, target, name);
		}
		return this._base_optionDatepicker.call($.datepicker, target, name_clone || name, value);
	};
	
	/*
	* jQuery isEmptyObject does not check hasOwnProperty - if someone has added to the object prototype,
	* it will return false for all objects
	*/
	var isEmptyObject = function (obj) {
		var prop;
		for (prop in obj) {
			if (obj.hasOwnProperty(prop)) {
				return false;
			}
		}
		return true;
	};

	/*
	* jQuery extend now ignores nulls!
	*/
	var extendRemove = function (target, props) {
		$.extend(target, props);
		for (var name in props) {
			if (props[name] === null || props[name] === undefined) {
				target[name] = props[name];
			}
		}
		return target;
	};

	/*
	* Determine by the time format which units are supported
	* Returns an object of booleans for each unit
	*/
	var detectSupport = function (timeFormat) {
		var tf = timeFormat.replace(/'.*?'/g, '').toLowerCase(), // removes literals
			isIn = function (f, t) { // does the format contain the token?
					return f.indexOf(t) !== -1 ? true : false;
				};
		return {
				hour: isIn(tf, 'h'),
				minute: isIn(tf, 'm'),
				second: isIn(tf, 's'),
				millisec: isIn(tf, 'l'),
				microsec: isIn(tf, 'c'),
				timezone: isIn(tf, 'z'),
				ampm: isIn(tf, 't') && isIn(timeFormat, 'h'),
				iso8601: isIn(timeFormat, 'Z')
			};
	};

	/*
	* Converts 24 hour format into 12 hour
	* Returns 12 hour without leading 0
	*/
	var convert24to12 = function (hour) {
		hour %= 12;

		if (hour === 0) {
			hour = 12;
		}

		return String(hour);
	};

	var computeEffectiveSetting = function (settings, property) {
		return settings && settings[property] ? settings[property] : $.timepicker._defaults[property];
	};

	/*
	* Splits datetime string into date and time substrings.
	* Throws exception when date can't be parsed
	* Returns {dateString: dateString, timeString: timeString}
	*/
	var splitDateTime = function (dateTimeString, timeSettings) {
		// The idea is to get the number separator occurrences in datetime and the time format requested (since time has
		// fewer unknowns, mostly numbers and am/pm). We will use the time pattern to split.
		var separator = computeEffectiveSetting(timeSettings, 'separator'),
			format = computeEffectiveSetting(timeSettings, 'timeFormat'),
			timeParts = format.split(separator), // how many occurrences of separator may be in our format?
			timePartsLen = timeParts.length,
			allParts = dateTimeString.split(separator),
			allPartsLen = allParts.length;

		if (allPartsLen > 1) {
			return {
				dateString: allParts.splice(0, allPartsLen - timePartsLen).join(separator),
				timeString: allParts.splice(0, timePartsLen).join(separator)
			};
		}

		return {
			dateString: dateTimeString,
			timeString: ''
		};
	};

	/*
	* Internal function to parse datetime interval
	* Returns: {date: Date, timeObj: Object}, where
	*   date - parsed date without time (type Date)
	*   timeObj = {hour: , minute: , second: , millisec: , microsec: } - parsed time. Optional
	*/
	var parseDateTimeInternal = function (dateFormat, timeFormat, dateTimeString, dateSettings, timeSettings) {
		var date,
			parts,
			parsedTime;

		parts = splitDateTime(dateTimeString, timeSettings);
		date = $.datepicker._base_parseDate(dateFormat, parts.dateString, dateSettings);

		if (parts.timeString === '') {
			return {
				date: date
			};
		}

		parsedTime = $.datepicker.parseTime(timeFormat, parts.timeString, timeSettings);

		if (!parsedTime) {
			throw 'Wrong time format';
		}

		return {
			date: date,
			timeObj: parsedTime
		};
	};

	/*
	* Internal function to set timezone_select to the local timezone
	*/
	var selectLocalTimezone = function (tp_inst, date) {
		if (tp_inst && tp_inst.timezone_select) {
			var now = date || new Date();
			tp_inst.timezone_select.val(-now.getTimezoneOffset());
		}
	};

	/*
	* Create a Singleton Instance
	*/
	$.timepicker = new Timepicker();

	/**
	 * Get the timezone offset as string from a date object (eg '+0530' for UTC+5.5)
	 * @param {number} tzMinutes if not a number, less than -720 (-1200), or greater than 840 (+1400) this value is returned
	 * @param {boolean} iso8601 if true formats in accordance to iso8601 "+12:45"
	 * @return {string}
	 */
	$.timepicker.timezoneOffsetString = function (tzMinutes, iso8601) {
		if (isNaN(tzMinutes) || tzMinutes > 840 || tzMinutes < -720) {
			return tzMinutes;
		}

		var off = tzMinutes,
			minutes = off % 60,
			hours = (off - minutes) / 60,
			iso = iso8601 ? ':' : '',
			tz = (off >= 0 ? '+' : '-') + ('0' + Math.abs(hours)).slice(-2) + iso + ('0' + Math.abs(minutes)).slice(-2);
		
		if (tz === '+00:00') {
			return 'Z';
		}
		return tz;
	};

	/**
	 * Get the number in minutes that represents a timezone string
	 * @param  {string} tzString formatted like "+0500", "-1245", "Z"
	 * @return {number} the offset minutes or the original string if it doesn't match expectations
	 */
	$.timepicker.timezoneOffsetNumber = function (tzString) {
		var normalized = tzString.toString().replace(':', ''); // excuse any iso8601, end up with "+1245"

		if (normalized.toUpperCase() === 'Z') { // if iso8601 with Z, its 0 minute offset
			return 0;
		}

		if (!/^(\-|\+)\d{4}$/.test(normalized)) { // possibly a user defined tz, so just give it back
			return tzString;
		}

		return ((normalized.substr(0, 1) === '-' ? -1 : 1) * // plus or minus
					((parseInt(normalized.substr(1, 2), 10) * 60) + // hours (converted to minutes)
					parseInt(normalized.substr(3, 2), 10))); // minutes
	};

	/**
	 * No way to set timezone in js Date, so we must adjust the minutes to compensate. (think setDate, getDate)
	 * @param  {Date} date
	 * @param  {string} toTimezone formatted like "+0500", "-1245"
	 * @return {Date}
	 */
	$.timepicker.timezoneAdjust = function (date, toTimezone) {
		var toTz = $.timepicker.timezoneOffsetNumber(toTimezone);
		if (!isNaN(toTz)) {
			date.setMinutes(date.getMinutes() + -date.getTimezoneOffset() - toTz);
		}
		return date;
	};

	/**
	 * Calls `timepicker()` on the `startTime` and `endTime` elements, and configures them to
	 * enforce date range limits.
	 * n.b. The input value must be correctly formatted (reformatting is not supported)
	 * @param  {Element} startTime
	 * @param  {Element} endTime
	 * @param  {Object} options Options for the timepicker() call
	 * @return {jQuery}
	 */
	$.timepicker.timeRange = function (startTime, endTime, options) {
		return $.timepicker.handleRange('timepicker', startTime, endTime, options);
	};

	/**
	 * Calls `datetimepicker` on the `startTime` and `endTime` elements, and configures them to
	 * enforce date range limits.
	 * @param  {Element} startTime
	 * @param  {Element} endTime
	 * @param  {Object} options Options for the `timepicker()` call. Also supports `reformat`,
	 *   a boolean value that can be used to reformat the input values to the `dateFormat`.
	 * @param  {string} method Can be used to specify the type of picker to be added
	 * @return {jQuery}
	 */
	$.timepicker.datetimeRange = function (startTime, endTime, options) {
		$.timepicker.handleRange('datetimepicker', startTime, endTime, options);
	};

	/**
	 * Calls `datepicker` on the `startTime` and `endTime` elements, and configures them to
	 * enforce date range limits.
	 * @param  {Element} startTime
	 * @param  {Element} endTime
	 * @param  {Object} options Options for the `timepicker()` call. Also supports `reformat`,
	 *   a boolean value that can be used to reformat the input values to the `dateFormat`.
	 * @return {jQuery}
	 */
	$.timepicker.dateRange = function (startTime, endTime, options) {
		$.timepicker.handleRange('datepicker', startTime, endTime, options);
	};

	/**
	 * Calls `method` on the `startTime` and `endTime` elements, and configures them to
	 * enforce date range limits.
	 * @param  {string} method Can be used to specify the type of picker to be added
	 * @param  {Element} startTime
	 * @param  {Element} endTime
	 * @param  {Object} options Options for the `timepicker()` call. Also supports `reformat`,
	 *   a boolean value that can be used to reformat the input values to the `dateFormat`.
	 * @return {jQuery}
	 */
	$.timepicker.handleRange = function (method, startTime, endTime, options) {
		options = $.extend({}, {
			minInterval: 0, // min allowed interval in milliseconds
			maxInterval: 0, // max allowed interval in milliseconds
			start: {},      // options for start picker
			end: {}         // options for end picker
		}, options);

		// for the mean time this fixes an issue with calling getDate with timepicker()
		var timeOnly = false;
		if(method === 'timepicker'){
			timeOnly = true;
			method = 'datetimepicker';
		}

		function checkDates(changed, other) {
			var startdt = startTime[method]('getDate'),
				enddt = endTime[method]('getDate'),
				changeddt = changed[method]('getDate');

			if (startdt !== null) {
				var minDate = new Date(startdt.getTime()),
					maxDate = new Date(startdt.getTime());

				minDate.setMilliseconds(minDate.getMilliseconds() + options.minInterval);
				maxDate.setMilliseconds(maxDate.getMilliseconds() + options.maxInterval);

				if (options.minInterval > 0 && minDate > enddt) { // minInterval check
					endTime[method]('setDate', minDate);
				}
				else if (options.maxInterval > 0 && maxDate < enddt) { // max interval check
					endTime[method]('setDate', maxDate);
				}
				else if (startdt > enddt) {
					other[method]('setDate', changeddt);
				}
			}
		}

		function selected(changed, other, option) {
			if (!changed.val()) {
				return;
			}
			var date = changed[method].call(changed, 'getDate');
			if (date !== null && options.minInterval > 0) {
				if (option === 'minDate') {
					date.setMilliseconds(date.getMilliseconds() + options.minInterval);
				}
				if (option === 'maxDate') {
					date.setMilliseconds(date.getMilliseconds() - options.minInterval);
				}
			}
			
			if (date.getTime) {
				other[method].call(other, 'option', option, date);
			}
		}

		$.fn[method].call(startTime, $.extend({
			timeOnly: timeOnly,
			onClose: function (dateText, inst) {
				checkDates($(this), endTime);
			},
			onSelect: function (selectedDateTime) {
				selected($(this), endTime, 'minDate');
			}
		}, options, options.start));
		$.fn[method].call(endTime, $.extend({
			timeOnly: timeOnly,
			onClose: function (dateText, inst) {
				checkDates($(this), startTime);
			},
			onSelect: function (selectedDateTime) {
				selected($(this), startTime, 'maxDate');
			}
		}, options, options.end));

		checkDates(startTime, endTime);
		
		selected(startTime, endTime, 'minDate');
		selected(endTime, startTime, 'maxDate');

		return $([startTime.get(0), endTime.get(0)]);
	};

	/**
	 * Log error or data to the console during error or debugging
	 * @param  {Object} err pass any type object to log to the console during error or debugging
	 * @return {void}
	 */
	$.timepicker.log = function () {
		if (window.console) {
			window.console.log.apply(window.console, Array.prototype.slice.call(arguments));
		}
	};

	/*
	 * Add util object to allow access to private methods for testability.
	 */
	$.timepicker._util = {
		_extendRemove: extendRemove,
		_isEmptyObject: isEmptyObject,
		_convert24to12: convert24to12,
		_detectSupport: detectSupport,
		_selectLocalTimezone: selectLocalTimezone,
		_computeEffectiveSetting: computeEffectiveSetting,
		_splitDateTime: splitDateTime,
		_parseDateTimeInternal: parseDateTimeInternal
	};

	/*
	* Microsecond support
	*/
	if (!Date.prototype.getMicroseconds) {
		Date.prototype.microseconds = 0;
		Date.prototype.getMicroseconds = function () { return this.microseconds; };
		Date.prototype.setMicroseconds = function (m) {
			this.setMilliseconds(this.getMilliseconds() + Math.floor(m / 1000));
			this.microseconds = m % 1000;
			return this;
		};
	}

	/*
	* Keep up with the version
	*/
	$.timepicker.version = "1.5.3";

}));;
// jQuery Alert Dialogs Plugin
//
// Version 1.1
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
// 14 May 2009
//
// Visit http://abeautifulsite.net/notebook/87 for more information
//
// Usage:
//		jAlert( message, [title, callback] )
//		jConfirm( message, [title, callback] )
//		jPrompt( message, [value, title, callback] )
// 
// History:
//
//		1.00 - Released (29 December 2008)
//
//		1.01 - Fixed bug where unbinding would destroy all resize events
//
// License:
// 
// This plugin is dual-licensed under the GNU General Public License and the MIT License and
// is copyright 2008 A Beautiful Site, LLC. 
//
(function($) {
	
	$.alerts = {
		
		// These properties can be read/written by accessing $.alerts.propertyName from your scripts at any time
		
		verticalOffset: -75,                // vertical offset of the dialog from center screen, in pixels
		horizontalOffset: 0,                // horizontal offset of the dialog from center screen, in pixels/
		repositionOnResize: true,           // re-centers the dialog on window resize
		overlayOpacity: .6,                // transparency level of overlay
		overlayColor: '#FFF',               // base color of overlay
		draggable: true,                    // make the dialogs draggable (requires UI Draggables plugin)
		okButton: '&nbsp;Fermer&nbsp;',         // text for the OK button
		cancelButton: '&nbsp;Annuler&nbsp;', // text for the Cancel button
		dialogClass: null,                  // if specified, this class will be applied to all dialogs
		
		// Public methods
		
		alert: function(message, title, callback) {
			if( title == null ) title = 'Informations';
			$.alerts._show(title, message, null, 'alert', function(result) {
				if( callback ) callback(result);
			});
		},
		
		confirm: function(message, title, callback) {
			if( title == null ) title = 'Confirm';
			$.alerts._show(title, message, null, 'confirm', function(result) {
				if( callback ) callback(result);
			});
		},
			
		prompt: function(message, value, title, callback) {
			if( title == null ) title = 'Prompt';
			$.alerts._show(title, message, value, 'prompt', function(result) {
				if( callback ) callback(result);
			});
		},
		
		// Private methods
		
		_show: function(title, msg, value, type, callback) {
			
			$.alerts._hide();
			$.alerts._overlay('show');
			
			$("BODY").append(
			  '<div id="popup_container">' +
			    '<h1 id="popup_title"></h1>' +
			    '<div id="popup_content">' +
			      '<div id="popup_message"></div>' +
				'</div>' +
			  '</div>');
			
			if( $.alerts.dialogClass ) $("#popup_container").addClass($.alerts.dialogClass);
			
			// IE6 Fix
			
			$("#popup_container").css({
			    position: 'fixed',
				zIndex: 99999,
				padding: 0,
				margin: 0
			});
			
			$("#popup_title").text(title);
			$("#popup_content").addClass(type);
			$("#popup_message").text(msg);
			$("#popup_message").html( "<label>" + $("#popup_message").text().replace(/\n/g, '<br />') + "</label>");
			
			$("#popup_container").css({
				minWidth: $("#popup_container").outerWidth(),
				maxWidth: $("#popup_container").outerWidth()
			});
			
			$.alerts._reposition();
			$.alerts._maintainPosition(true);
			
			switch( type ) {
				case 'alert':
				    $("#popup_content").after('<div id="popup_panel"><input class="btn" type="button" value="' + $.alerts.okButton + '" id="popup_ok" /></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						callback(true);
					});
					$("#popup_ok").focus().keypress( function(e) {
						if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
					});
				break;
			    case 'confirm':
			        $("#popup_title").html("<i class='fa fa-warning fa-lg'></i> &nbsp;&nbsp;" + title);

				    $("#popup_content").after('<div id="popup_panel"><input type="button" value="Ok" class="btn btn-warning" id="popup_ok" /> <input class="btn btn-grey" type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						if( callback ) callback(true);
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback(false);
					});
					$("#popup_ok").focus();
					$("#popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
				break;
			    case 'prompt':
			        $("#popup_message").append('<textarea  id="popup_prompt" />');
			        $("#popup_content").after('<div id="popup_panel"> <input type="button" class="btn btn-grey" value="' + $.alerts.cancelButton + '" id="popup_cancel" /><input type="button" class="btn btn-success" value="OK" id="popup_ok" /></div>');
					$("#popup_prompt").width( $("#popup_message").width() );
					$("#popup_ok").click( function() {
						var val = $("#popup_prompt").val();
						$.alerts._hide();
						if( callback ) callback( val );
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback( null );
					});
					$("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
					if( value ) $("#popup_prompt").val(value);
					$("#popup_prompt").focus().select();
				break;
			}
			
			// Make draggable
			if( $.alerts.draggable ) {
				try {
					$("#popup_container").draggable({ handle: $("#popup_title") });
					$("#popup_title").css({ cursor: 'move' });
				} catch(e) { /* requires jQuery UI draggables */ }
			}
		},
		
		_hide: function() {
			$("#popup_container").remove();
			$.alerts._overlay('hide');
			$.alerts._maintainPosition(false);
		},
		
		_overlay: function(status) {
			switch( status ) {
				case 'show':
					$.alerts._overlay('hide');
					$("BODY").append('<div id="popup_overlay"></div>');
					$("#popup_overlay").css({
						position: 'absolute',
						zIndex: 99998,
						top: '0px',
						left: '0px',
						width: '100%',
						height: $(document).height(),
						background: $.alerts.overlayColor,
						opacity: $.alerts.overlayOpacity
					});
				break;
				case 'hide':
					$("#popup_overlay").remove();
				break;
			}
		},
		
		_reposition: function() {
			var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset;
			var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset;
			if( top < 0 ) top = 0;
			if( left < 0 ) left = 0;
			
			// IE6 fix
			//if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();
			
			$("#popup_container").css({
				top: top + 'px',
				left: left + 'px'
			});
			$("#popup_overlay").height( $(document).height() );
		},
		
		_maintainPosition: function(status) {
			if( $.alerts.repositionOnResize ) {
				switch(status) {
					case true:
						$(window).bind('resize', $.alerts._reposition);
					break;
					case false:
						$(window).unbind('resize', $.alerts._reposition);
					break;
				}
			}
		}
		
	}
	
	// Shortuct functions
	jAlert = function(message, title, callback) {
		$.alerts.alert(message, title, callback);
	}
	
	jConfirm = function(message, title, callback) {
		$.alerts.confirm(message, title, callback);
	};
		
	jPrompt = function(message, value, title, callback) {
		$.alerts.prompt(message, value, title, callback);
	};
	
})(jQuery);;
/**
 * jQuery EasyUI 1.4.3
 * 
 * Copyright (c) 2009-2015 www.jeasyui.com. All rights reserved.
 *
 * Licensed under the GPL license: http://www.gnu.org/licenses/gpl.txt
 * To use it on other terms please contact us at info@jeasyui.com
 *
 */
(function($){
$.parser={auto:true,onComplete:function(_1){
},plugins:["draggable","droppable","resizable","pagination","tooltip","linkbutton","menu","menubutton","splitbutton","switchbutton","progressbar","tree","textbox","filebox","combo","combobox","combotree","combogrid","numberbox","validatebox","searchbox","spinner","numberspinner","timespinner","datetimespinner","calendar","datebox","datetimebox","slider","layout","panel","datagrid","propertygrid","treegrid","datalist","tabs","accordion","window","dialog","form"],parse:function(_2){
var aa=[];
for(var i=0;i<$.parser.plugins.length;i++){
var _3=$.parser.plugins[i];
var r=$(".easyui-"+_3,_2);
if(r.length){
if(r[_3]){
r[_3]();
}else{
aa.push({name:_3,jq:r});
}
}
}
if(aa.length&&window.easyloader){
var _4=[];
for(var i=0;i<aa.length;i++){
_4.push(aa[i].name);
}
easyloader.load(_4,function(){
for(var i=0;i<aa.length;i++){
var _5=aa[i].name;
var jq=aa[i].jq;
jq[_5]();
}
$.parser.onComplete.call($.parser,_2);
});
}else{
$.parser.onComplete.call($.parser,_2);
}
},parseValue:function(_6,_7,_8,_9){
_9=_9||0;
var v=$.trim(String(_7||""));
var _a=v.substr(v.length-1,1);
if(_a=="%"){
v=parseInt(v.substr(0,v.length-1));
if(_6.toLowerCase().indexOf("width")>=0){
v=Math.floor((_8.width()-_9)*v/100);
}else{
v=Math.floor((_8.height()-_9)*v/100);
}
}else{
v=parseInt(v)||undefined;
}
return v;
},parseOptions:function(_b,_c){
var t=$(_b);
var _d={};
var s=$.trim(t.attr("data-options"));
if(s){
if(s.substring(0,1)!="{"){
s="{"+s+"}";
}
_d=(new Function("return "+s))();
}
$.map(["width","height","left","top","minWidth","maxWidth","minHeight","maxHeight"],function(p){
var pv=$.trim(_b.style[p]||"");
if(pv){
if(pv.indexOf("%")==-1){
pv=parseInt(pv)||undefined;
}
_d[p]=pv;
}
});
if(_c){
var _e={};
for(var i=0;i<_c.length;i++){
var pp=_c[i];
if(typeof pp=="string"){
_e[pp]=t.attr(pp);
}else{
for(var _f in pp){
var _10=pp[_f];
if(_10=="boolean"){
_e[_f]=t.attr(_f)?(t.attr(_f)=="true"):undefined;
}else{
if(_10=="number"){
_e[_f]=t.attr(_f)=="0"?0:parseFloat(t.attr(_f))||undefined;
}
}
}
}
}
$.extend(_d,_e);
}
return _d;
}};
$(function(){
var d=$("<div style=\"position:absolute;top:-1000px;width:100px;height:100px;padding:5px\"></div>").appendTo("body");
$._boxModel=d.outerWidth()!=100;
d.remove();
d=$("<div style=\"position:fixed\"></div>").appendTo("body");
$._positionFixed=(d.css("position")=="fixed");
d.remove();
if(!window.easyloader&&$.parser.auto){
$.parser.parse();
}
});
$.fn._outerWidth=function(_11){
if(_11==undefined){
if(this[0]==window){
return this.width()||document.body.clientWidth;
}
return this.outerWidth()||0;
}
return this._size("width",_11);
};
$.fn._outerHeight=function(_12){
if(_12==undefined){
if(this[0]==window){
return this.height()||document.body.clientHeight;
}
return this.outerHeight()||0;
}
return this._size("height",_12);
};
$.fn._scrollLeft=function(_13){
if(_13==undefined){
return this.scrollLeft();
}else{
return this.each(function(){
$(this).scrollLeft(_13);
});
}
};
$.fn._propAttr=$.fn.prop||$.fn.attr;
$.fn._size=function(_14,_15){
if(typeof _14=="string"){
if(_14=="clear"){
return this.each(function(){
$(this).css({width:"",minWidth:"",maxWidth:"",height:"",minHeight:"",maxHeight:""});
});
}else{
if(_14=="fit"){
return this.each(function(){
_16(this,this.tagName=="BODY"?$("body"):$(this).parent(),true);
});
}else{
if(_14=="unfit"){
return this.each(function(){
_16(this,$(this).parent(),false);
});
}else{
if(_15==undefined){
return _17(this[0],_14);
}else{
return this.each(function(){
_17(this,_14,_15);
});
}
}
}
}
}else{
return this.each(function(){
_15=_15||$(this).parent();
$.extend(_14,_16(this,_15,_14.fit)||{});
var r1=_18(this,"width",_15,_14);
var r2=_18(this,"height",_15,_14);
if(r1||r2){
$(this).addClass("easyui-fluid");
}else{
$(this).removeClass("easyui-fluid");
}
});
}
function _16(_19,_1a,fit){
if(!_1a.length){
return false;
}
var t=$(_19)[0];
var p=_1a[0];
var _1b=p.fcount||0;
if(fit){
if(!t.fitted){
t.fitted=true;
p.fcount=_1b+1;
$(p).addClass("panel-noscroll");
if(p.tagName=="BODY"){
$("html").addClass("panel-fit");
}
}
return {width:($(p).width()||1),height:($(p).height()||1)};
}else{
if(t.fitted){
t.fitted=false;
p.fcount=_1b-1;
if(p.fcount==0){
$(p).removeClass("panel-noscroll");
if(p.tagName=="BODY"){
$("html").removeClass("panel-fit");
}
}
}
return false;
}
};
function _18(_1c,_1d,_1e,_1f){
var t=$(_1c);
var p=_1d;
var p1=p.substr(0,1).toUpperCase()+p.substr(1);
var min=$.parser.parseValue("min"+p1,_1f["min"+p1],_1e);
var max=$.parser.parseValue("max"+p1,_1f["max"+p1],_1e);
var val=$.parser.parseValue(p,_1f[p],_1e);
var _20=(String(_1f[p]||"").indexOf("%")>=0?true:false);
if(!isNaN(val)){
var v=Math.min(Math.max(val,min||0),max||99999);
if(!_20){
_1f[p]=v;
}
t._size("min"+p1,"");
t._size("max"+p1,"");
t._size(p,v);
}else{
t._size(p,"");
t._size("min"+p1,min);
t._size("max"+p1,max);
}
return _20||_1f.fit;
};
function _17(_21,_22,_23){
var t=$(_21);
if(_23==undefined){
_23=parseInt(_21.style[_22]);
if(isNaN(_23)){
return undefined;
}
if($._boxModel){
_23+=_24();
}
return _23;
}else{
if(_23===""){
t.css(_22,"");
}else{
if($._boxModel){
_23-=_24();
if(_23<0){
_23=0;
}
}
t.css(_22,_23+"px");
}
}
function _24(){
if(_22.toLowerCase().indexOf("width")>=0){
return t.outerWidth()-t.width();
}else{
return t.outerHeight()-t.height();
}
};
};
};
})(jQuery);
(function($){
var _25=null;
var _26=null;
var _27=false;
function _28(e){
if(e.touches.length!=1){
return;
}
if(!_27){
_27=true;
dblClickTimer=setTimeout(function(){
_27=false;
},500);
}else{
clearTimeout(dblClickTimer);
_27=false;
_29(e,"dblclick");
}
_25=setTimeout(function(){
_29(e,"contextmenu",3);
},1000);
_29(e,"mousedown");
if($.fn.draggable.isDragging||$.fn.resizable.isResizing){
e.preventDefault();
}
};
function _2a(e){
if(e.touches.length!=1){
return;
}
if(_25){
clearTimeout(_25);
}
_29(e,"mousemove");
if($.fn.draggable.isDragging||$.fn.resizable.isResizing){
e.preventDefault();
}
};
function _2b(e){
if(_25){
clearTimeout(_25);
}
_29(e,"mouseup");
if($.fn.draggable.isDragging||$.fn.resizable.isResizing){
e.preventDefault();
}
};
function _29(e,_2c,_2d){
var _2e=new $.Event(_2c);
_2e.pageX=e.changedTouches[0].pageX;
_2e.pageY=e.changedTouches[0].pageY;
_2e.which=_2d||1;
$(e.target).trigger(_2e);
};
if(document.addEventListener){
document.addEventListener("touchstart",_28,true);
document.addEventListener("touchmove",_2a,true);
document.addEventListener("touchend",_2b,true);
}
})(jQuery);
(function($){
function _2f(e){
var _30=$.data(e.data.target,"draggable");
var _31=_30.options;
var _32=_30.proxy;
var _33=e.data;
var _34=_33.startLeft+e.pageX-_33.startX;
var top=_33.startTop+e.pageY-_33.startY;
if(_32){
if(_32.parent()[0]==document.body){
if(_31.deltaX!=null&&_31.deltaX!=undefined){
_34=e.pageX+_31.deltaX;
}else{
_34=e.pageX-e.data.offsetWidth;
}
if(_31.deltaY!=null&&_31.deltaY!=undefined){
top=e.pageY+_31.deltaY;
}else{
top=e.pageY-e.data.offsetHeight;
}
}else{
if(_31.deltaX!=null&&_31.deltaX!=undefined){
_34+=e.data.offsetWidth+_31.deltaX;
}
if(_31.deltaY!=null&&_31.deltaY!=undefined){
top+=e.data.offsetHeight+_31.deltaY;
}
}
}
if(e.data.parent!=document.body){
_34+=$(e.data.parent).scrollLeft();
top+=$(e.data.parent).scrollTop();
}
if(_31.axis=="h"){
_33.left=_34;
}else{
if(_31.axis=="v"){
_33.top=top;
}else{
_33.left=_34;
_33.top=top;
}
}
};
function _35(e){
var _36=$.data(e.data.target,"draggable");
var _37=_36.options;
var _38=_36.proxy;
if(!_38){
_38=$(e.data.target);
}
_38.css({left:e.data.left,top:e.data.top});
$("body").css("cursor",_37.cursor);
};
function _39(e){
if(!$.fn.draggable.isDragging){
return false;
}
var _3a=$.data(e.data.target,"draggable");
var _3b=_3a.options;
var _3c=$(".droppable").filter(function(){
return e.data.target!=this;
}).filter(function(){
var _3d=$.data(this,"droppable").options.accept;
if(_3d){
return $(_3d).filter(function(){
return this==e.data.target;
}).length>0;
}else{
return true;
}
});
_3a.droppables=_3c;
var _3e=_3a.proxy;
if(!_3e){
if(_3b.proxy){
if(_3b.proxy=="clone"){
_3e=$(e.data.target).clone().insertAfter(e.data.target);
}else{
_3e=_3b.proxy.call(e.data.target,e.data.target);
}
_3a.proxy=_3e;
}else{
_3e=$(e.data.target);
}
}
_3e.css("position","absolute");
_2f(e);
_35(e);
_3b.onStartDrag.call(e.data.target,e);
return false;
};
function _3f(e){
if(!$.fn.draggable.isDragging){
return false;
}
var _40=$.data(e.data.target,"draggable");
_2f(e);
if(_40.options.onDrag.call(e.data.target,e)!=false){
_35(e);
}
var _41=e.data.target;
_40.droppables.each(function(){
var _42=$(this);
if(_42.droppable("options").disabled){
return;
}
var p2=_42.offset();
if(e.pageX>p2.left&&e.pageX<p2.left+_42.outerWidth()&&e.pageY>p2.top&&e.pageY<p2.top+_42.outerHeight()){
if(!this.entered){
$(this).trigger("_dragenter",[_41]);
this.entered=true;
}
$(this).trigger("_dragover",[_41]);
}else{
if(this.entered){
$(this).trigger("_dragleave",[_41]);
this.entered=false;
}
}
});
return false;
};
function _43(e){
if(!$.fn.draggable.isDragging){
_44();
return false;
}
_3f(e);
var _45=$.data(e.data.target,"draggable");
var _46=_45.proxy;
var _47=_45.options;
if(_47.revert){
if(_48()==true){
$(e.data.target).css({position:e.data.startPosition,left:e.data.startLeft,top:e.data.startTop});
}else{
if(_46){
var _49,top;
if(_46.parent()[0]==document.body){
_49=e.data.startX-e.data.offsetWidth;
top=e.data.startY-e.data.offsetHeight;
}else{
_49=e.data.startLeft;
top=e.data.startTop;
}
_46.animate({left:_49,top:top},function(){
_4a();
});
}else{
$(e.data.target).animate({left:e.data.startLeft,top:e.data.startTop},function(){
$(e.data.target).css("position",e.data.startPosition);
});
}
}
}else{
$(e.data.target).css({position:"absolute",left:e.data.left,top:e.data.top});
_48();
}
_47.onStopDrag.call(e.data.target,e);
_44();
function _4a(){
if(_46){
_46.remove();
}
_45.proxy=null;
};
function _48(){
var _4b=false;
_45.droppables.each(function(){
var _4c=$(this);
if(_4c.droppable("options").disabled){
return;
}
var p2=_4c.offset();
if(e.pageX>p2.left&&e.pageX<p2.left+_4c.outerWidth()&&e.pageY>p2.top&&e.pageY<p2.top+_4c.outerHeight()){
if(_47.revert){
$(e.data.target).css({position:e.data.startPosition,left:e.data.startLeft,top:e.data.startTop});
}
$(this).trigger("_drop",[e.data.target]);
_4a();
_4b=true;
this.entered=false;
return false;
}
});
if(!_4b&&!_47.revert){
_4a();
}
return _4b;
};
return false;
};
function _44(){
if($.fn.draggable.timer){
clearTimeout($.fn.draggable.timer);
$.fn.draggable.timer=undefined;
}
$(document).unbind(".draggable");
$.fn.draggable.isDragging=false;
setTimeout(function(){
$("body").css("cursor","");
},100);
};
$.fn.draggable=function(_4d,_4e){
if(typeof _4d=="string"){
return $.fn.draggable.methods[_4d](this,_4e);
}
return this.each(function(){
var _4f;
var _50=$.data(this,"draggable");
if(_50){
_50.handle.unbind(".draggable");
_4f=$.extend(_50.options,_4d);
}else{
_4f=$.extend({},$.fn.draggable.defaults,$.fn.draggable.parseOptions(this),_4d||{});
}
var _51=_4f.handle?(typeof _4f.handle=="string"?$(_4f.handle,this):_4f.handle):$(this);
$.data(this,"draggable",{options:_4f,handle:_51});
if(_4f.disabled){
$(this).css("cursor","");
return;
}
_51.unbind(".draggable").bind("mousemove.draggable",{target:this},function(e){
if($.fn.draggable.isDragging){
return;
}
var _52=$.data(e.data.target,"draggable").options;
if(_53(e)){
$(this).css("cursor",_52.cursor);
}else{
$(this).css("cursor","");
}
}).bind("mouseleave.draggable",{target:this},function(e){
$(this).css("cursor","");
}).bind("mousedown.draggable",{target:this},function(e){
if(_53(e)==false){
return;
}
$(this).css("cursor","");
var _54=$(e.data.target).position();
var _55=$(e.data.target).offset();
var _56={startPosition:$(e.data.target).css("position"),startLeft:_54.left,startTop:_54.top,left:_54.left,top:_54.top,startX:e.pageX,startY:e.pageY,offsetWidth:(e.pageX-_55.left),offsetHeight:(e.pageY-_55.top),target:e.data.target,parent:$(e.data.target).parent()[0]};
$.extend(e.data,_56);
var _57=$.data(e.data.target,"draggable").options;
if(_57.onBeforeDrag.call(e.data.target,e)==false){
return;
}
$(document).bind("mousedown.draggable",e.data,_39);
$(document).bind("mousemove.draggable",e.data,_3f);
$(document).bind("mouseup.draggable",e.data,_43);
$.fn.draggable.timer=setTimeout(function(){
$.fn.draggable.isDragging=true;
_39(e);
},_57.delay);
return false;
});
function _53(e){
var _58=$.data(e.data.target,"draggable");
var _59=_58.handle;
var _5a=$(_59).offset();
var _5b=$(_59).outerWidth();
var _5c=$(_59).outerHeight();
var t=e.pageY-_5a.top;
var r=_5a.left+_5b-e.pageX;
var b=_5a.top+_5c-e.pageY;
var l=e.pageX-_5a.left;
return Math.min(t,r,b,l)>_58.options.edge;
};
});
};
$.fn.draggable.methods={options:function(jq){
return $.data(jq[0],"draggable").options;
},proxy:function(jq){
return $.data(jq[0],"draggable").proxy;
},enable:function(jq){
return jq.each(function(){
$(this).draggable({disabled:false});
});
},disable:function(jq){
return jq.each(function(){
$(this).draggable({disabled:true});
});
}};
$.fn.draggable.parseOptions=function(_5d){
var t=$(_5d);
return $.extend({},$.parser.parseOptions(_5d,["cursor","handle","axis",{"revert":"boolean","deltaX":"number","deltaY":"number","edge":"number","delay":"number"}]),{disabled:(t.attr("disabled")?true:undefined)});
};
$.fn.draggable.defaults={proxy:null,revert:false,cursor:"move",deltaX:null,deltaY:null,handle:null,disabled:false,edge:0,axis:null,delay:100,onBeforeDrag:function(e){
},onStartDrag:function(e){
},onDrag:function(e){
},onStopDrag:function(e){
}};
$.fn.draggable.isDragging=false;
})(jQuery);
(function($){
function _5e(_5f){
$(_5f).addClass("droppable");
$(_5f).bind("_dragenter",function(e,_60){
$.data(_5f,"droppable").options.onDragEnter.apply(_5f,[e,_60]);
});
$(_5f).bind("_dragleave",function(e,_61){
$.data(_5f,"droppable").options.onDragLeave.apply(_5f,[e,_61]);
});
$(_5f).bind("_dragover",function(e,_62){
$.data(_5f,"droppable").options.onDragOver.apply(_5f,[e,_62]);
});
$(_5f).bind("_drop",function(e,_63){
$.data(_5f,"droppable").options.onDrop.apply(_5f,[e,_63]);
});
};
$.fn.droppable=function(_64,_65){
if(typeof _64=="string"){
return $.fn.droppable.methods[_64](this,_65);
}
_64=_64||{};
return this.each(function(){
var _66=$.data(this,"droppable");
if(_66){
$.extend(_66.options,_64);
}else{
_5e(this);
$.data(this,"droppable",{options:$.extend({},$.fn.droppable.defaults,$.fn.droppable.parseOptions(this),_64)});
}
});
};
$.fn.droppable.methods={options:function(jq){
return $.data(jq[0],"droppable").options;
},enable:function(jq){
return jq.each(function(){
$(this).droppable({disabled:false});
});
},disable:function(jq){
return jq.each(function(){
$(this).droppable({disabled:true});
});
}};
$.fn.droppable.parseOptions=function(_67){
var t=$(_67);
return $.extend({},$.parser.parseOptions(_67,["accept"]),{disabled:(t.attr("disabled")?true:undefined)});
};
$.fn.droppable.defaults={accept:null,disabled:false,onDragEnter:function(e,_68){
},onDragOver:function(e,_69){
},onDragLeave:function(e,_6a){
},onDrop:function(e,_6b){
}};
})(jQuery);
(function($){
$.fn.resizable=function(_6c,_6d){
if(typeof _6c=="string"){
return $.fn.resizable.methods[_6c](this,_6d);
}
function _6e(e){
var _6f=e.data;
var _70=$.data(_6f.target,"resizable").options;
if(_6f.dir.indexOf("e")!=-1){
var _71=_6f.startWidth+e.pageX-_6f.startX;
_71=Math.min(Math.max(_71,_70.minWidth),_70.maxWidth);
_6f.width=_71;
}
if(_6f.dir.indexOf("s")!=-1){
var _72=_6f.startHeight+e.pageY-_6f.startY;
_72=Math.min(Math.max(_72,_70.minHeight),_70.maxHeight);
_6f.height=_72;
}
if(_6f.dir.indexOf("w")!=-1){
var _71=_6f.startWidth-e.pageX+_6f.startX;
_71=Math.min(Math.max(_71,_70.minWidth),_70.maxWidth);
_6f.width=_71;
_6f.left=_6f.startLeft+_6f.startWidth-_6f.width;
}
if(_6f.dir.indexOf("n")!=-1){
var _72=_6f.startHeight-e.pageY+_6f.startY;
_72=Math.min(Math.max(_72,_70.minHeight),_70.maxHeight);
_6f.height=_72;
_6f.top=_6f.startTop+_6f.startHeight-_6f.height;
}
};
function _73(e){
var _74=e.data;
var t=$(_74.target);
t.css({left:_74.left,top:_74.top});
if(t.outerWidth()!=_74.width){
t._outerWidth(_74.width);
}
if(t.outerHeight()!=_74.height){
t._outerHeight(_74.height);
}
};
function _75(e){
$.fn.resizable.isResizing=true;
$.data(e.data.target,"resizable").options.onStartResize.call(e.data.target,e);
return false;
};
function _76(e){
_6e(e);
if($.data(e.data.target,"resizable").options.onResize.call(e.data.target,e)!=false){
_73(e);
}
return false;
};
function _77(e){
$.fn.resizable.isResizing=false;
_6e(e,true);
_73(e);
$.data(e.data.target,"resizable").options.onStopResize.call(e.data.target,e);
$(document).unbind(".resizable");
$("body").css("cursor","");
return false;
};
return this.each(function(){
var _78=null;
var _79=$.data(this,"resizable");
if(_79){
$(this).unbind(".resizable");
_78=$.extend(_79.options,_6c||{});
}else{
_78=$.extend({},$.fn.resizable.defaults,$.fn.resizable.parseOptions(this),_6c||{});
$.data(this,"resizable",{options:_78});
}
if(_78.disabled==true){
return;
}
$(this).bind("mousemove.resizable",{target:this},function(e){
if($.fn.resizable.isResizing){
return;
}
var dir=_7a(e);
if(dir==""){
$(e.data.target).css("cursor","");
}else{
$(e.data.target).css("cursor",dir+"-resize");
}
}).bind("mouseleave.resizable",{target:this},function(e){
$(e.data.target).css("cursor","");
}).bind("mousedown.resizable",{target:this},function(e){
var dir=_7a(e);
if(dir==""){
return;
}
function _7b(css){
var val=parseInt($(e.data.target).css(css));
if(isNaN(val)){
return 0;
}else{
return val;
}
};
var _7c={target:e.data.target,dir:dir,startLeft:_7b("left"),startTop:_7b("top"),left:_7b("left"),top:_7b("top"),startX:e.pageX,startY:e.pageY,startWidth:$(e.data.target).outerWidth(),startHeight:$(e.data.target).outerHeight(),width:$(e.data.target).outerWidth(),height:$(e.data.target).outerHeight(),deltaWidth:$(e.data.target).outerWidth()-$(e.data.target).width(),deltaHeight:$(e.data.target).outerHeight()-$(e.data.target).height()};
$(document).bind("mousedown.resizable",_7c,_75);
$(document).bind("mousemove.resizable",_7c,_76);
$(document).bind("mouseup.resizable",_7c,_77);
$("body").css("cursor",dir+"-resize");
});
function _7a(e){
var tt=$(e.data.target);
var dir="";
var _7d=tt.offset();
var _7e=tt.outerWidth();
var _7f=tt.outerHeight();
var _80=_78.edge;
if(e.pageY>_7d.top&&e.pageY<_7d.top+_80){
dir+="n";
}else{
if(e.pageY<_7d.top+_7f&&e.pageY>_7d.top+_7f-_80){
dir+="s";
}
}
if(e.pageX>_7d.left&&e.pageX<_7d.left+_80){
dir+="w";
}else{
if(e.pageX<_7d.left+_7e&&e.pageX>_7d.left+_7e-_80){
dir+="e";
}
}
var _81=_78.handles.split(",");
for(var i=0;i<_81.length;i++){
var _82=_81[i].replace(/(^\s*)|(\s*$)/g,"");
if(_82=="all"||_82==dir){
return dir;
}
}
return "";
};
});
};
$.fn.resizable.methods={options:function(jq){
return $.data(jq[0],"resizable").options;
},enable:function(jq){
return jq.each(function(){
$(this).resizable({disabled:false});
});
},disable:function(jq){
return jq.each(function(){
$(this).resizable({disabled:true});
});
}};
$.fn.resizable.parseOptions=function(_83){
var t=$(_83);
return $.extend({},$.parser.parseOptions(_83,["handles",{minWidth:"number",minHeight:"number",maxWidth:"number",maxHeight:"number",edge:"number"}]),{disabled:(t.attr("disabled")?true:undefined)});
};
$.fn.resizable.defaults={disabled:false,handles:"n, e, s, w, ne, se, sw, nw, all",minWidth:10,minHeight:10,maxWidth:10000,maxHeight:10000,edge:5,onStartResize:function(e){
},onResize:function(e){
},onStopResize:function(e){
}};
$.fn.resizable.isResizing=false;
})(jQuery);
(function($){
function _84(_85,_86){
var _87=$.data(_85,"linkbutton").options;
if(_86){
$.extend(_87,_86);
}
if(_87.width||_87.height||_87.fit){
var btn=$(_85);
var _88=btn.parent();
var _89=btn.is(":visible");
if(!_89){
var _8a=$("<div style=\"display:none\"></div>").insertBefore(_85);
var _8b={position:btn.css("position"),display:btn.css("display"),left:btn.css("left")};
btn.appendTo("body");
btn.css({position:"absolute",display:"inline-block",left:-20000});
}
btn._size(_87,_88);
var _8c=btn.find(".l-btn-left");
_8c.css("margin-top",0);
_8c.css("margin-top",parseInt((btn.height()-_8c.height())/2)+"px");
if(!_89){
btn.insertAfter(_8a);
btn.css(_8b);
_8a.remove();
}
}
};
function _8d(_8e){
var _8f=$.data(_8e,"linkbutton").options;
var t=$(_8e).empty();
t.addClass("l-btn").removeClass("l-btn-plain l-btn-selected l-btn-plain-selected l-btn-outline");
t.removeClass("l-btn-small l-btn-medium l-btn-large").addClass("l-btn-"+_8f.size);
if(_8f.plain){
t.addClass("l-btn-plain");
}
if(_8f.outline){
t.addClass("l-btn-outline");
}
if(_8f.selected){
t.addClass(_8f.plain?"l-btn-selected l-btn-plain-selected":"l-btn-selected");
}
t.attr("group",_8f.group||"");
t.attr("id",_8f.id||"");
var _90=$("<span class=\"l-btn-left\"></span>").appendTo(t);
if(_8f.text){
$("<span class=\"l-btn-text\"></span>").html(_8f.text).appendTo(_90);
}else{
$("<span class=\"l-btn-text l-btn-empty\">&nbsp;</span>").appendTo(_90);
}
if(_8f.iconCls){
$("<span class=\"l-btn-icon\">&nbsp;</span>").addClass(_8f.iconCls).appendTo(_90);
_90.addClass("l-btn-icon-"+_8f.iconAlign);
}
t.unbind(".linkbutton").bind("focus.linkbutton",function(){
if(!_8f.disabled){
$(this).addClass("l-btn-focus");
}
}).bind("blur.linkbutton",function(){
$(this).removeClass("l-btn-focus");
}).bind("click.linkbutton",function(){
if(!_8f.disabled){
if(_8f.toggle){
if(_8f.selected){
$(this).linkbutton("unselect");
}else{
$(this).linkbutton("select");
}
}
_8f.onClick.call(this);
}
});
_91(_8e,_8f.selected);
_92(_8e,_8f.disabled);
};
function _91(_93,_94){
var _95=$.data(_93,"linkbutton").options;
if(_94){
if(_95.group){
$("a.l-btn[group=\""+_95.group+"\"]").each(function(){
var o=$(this).linkbutton("options");
if(o.toggle){
$(this).removeClass("l-btn-selected l-btn-plain-selected");
o.selected=false;
}
});
}
$(_93).addClass(_95.plain?"l-btn-selected l-btn-plain-selected":"l-btn-selected");
_95.selected=true;
}else{
if(!_95.group){
$(_93).removeClass("l-btn-selected l-btn-plain-selected");
_95.selected=false;
}
}
};
function _92(_96,_97){
var _98=$.data(_96,"linkbutton");
var _99=_98.options;
$(_96).removeClass("l-btn-disabled l-btn-plain-disabled");
if(_97){
_99.disabled=true;
var _9a=$(_96).attr("href");
if(_9a){
_98.href=_9a;
$(_96).attr("href","javascript:void(0)");
}
if(_96.onclick){
_98.onclick=_96.onclick;
_96.onclick=null;
}
_99.plain?$(_96).addClass("l-btn-disabled l-btn-plain-disabled"):$(_96).addClass("l-btn-disabled");
}else{
_99.disabled=false;
if(_98.href){
$(_96).attr("href",_98.href);
}
if(_98.onclick){
_96.onclick=_98.onclick;
}
}
};
$.fn.linkbutton=function(_9b,_9c){
if(typeof _9b=="string"){
return $.fn.linkbutton.methods[_9b](this,_9c);
}
_9b=_9b||{};
return this.each(function(){
var _9d=$.data(this,"linkbutton");
if(_9d){
$.extend(_9d.options,_9b);
}else{
$.data(this,"linkbutton",{options:$.extend({},$.fn.linkbutton.defaults,$.fn.linkbutton.parseOptions(this),_9b)});
$(this).removeAttr("disabled");
$(this).bind("_resize",function(e,_9e){
if($(this).hasClass("easyui-fluid")||_9e){
_84(this);
}
return false;
});
}
_8d(this);
_84(this);
});
};
$.fn.linkbutton.methods={options:function(jq){
return $.data(jq[0],"linkbutton").options;
},resize:function(jq,_9f){
return jq.each(function(){
_84(this,_9f);
});
},enable:function(jq){
return jq.each(function(){
_92(this,false);
});
},disable:function(jq){
return jq.each(function(){
_92(this,true);
});
},select:function(jq){
return jq.each(function(){
_91(this,true);
});
},unselect:function(jq){
return jq.each(function(){
_91(this,false);
});
}};
$.fn.linkbutton.parseOptions=function(_a0){
var t=$(_a0);
return $.extend({},$.parser.parseOptions(_a0,["id","iconCls","iconAlign","group","size","text",{plain:"boolean",toggle:"boolean",selected:"boolean",outline:"boolean"}]),{disabled:(t.attr("disabled")?true:undefined),text:($.trim(t.html())||undefined),iconCls:(t.attr("icon")||t.attr("iconCls"))});
};
$.fn.linkbutton.defaults={id:null,disabled:false,toggle:false,selected:false,outline:false,group:null,plain:false,text:"",iconCls:null,iconAlign:"left",size:"small",onClick:function(){
}};
})(jQuery);
(function($){
function _a1(_a2){
var _a3=$.data(_a2,"pagination");
var _a4=_a3.options;
var bb=_a3.bb={};
var _a5=$(_a2).addClass("pagination").html("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tr></tr></table>");
var tr=_a5.find("tr");
var aa=$.extend([],_a4.layout);
if(!_a4.showPageList){
_a6(aa,"list");
}
if(!_a4.showRefresh){
_a6(aa,"refresh");
}
if(aa[0]=="sep"){
aa.shift();
}
if(aa[aa.length-1]=="sep"){
aa.pop();
}
for(var _a7=0;_a7<aa.length;_a7++){
var _a8=aa[_a7];
if(_a8=="list"){
var ps=$("<select class=\"pagination-page-list\"></select>");
ps.bind("change",function(){
_a4.pageSize=parseInt($(this).val());
_a4.onChangePageSize.call(_a2,_a4.pageSize);
_ae(_a2,_a4.pageNumber);
});
for(var i=0;i<_a4.pageList.length;i++){
$("<option></option>").text(_a4.pageList[i]).appendTo(ps);
}
$("<td></td>").append(ps).appendTo(tr);
}else{
if(_a8=="sep"){
$("<td><div class=\"pagination-btn-separator\"></div></td>").appendTo(tr);
}else{
if(_a8=="first"){
bb.first=_a9("first");
}else{
if(_a8=="prev"){
bb.prev=_a9("prev");
}else{
if(_a8=="next"){
bb.next=_a9("next");
}else{
if(_a8=="last"){
bb.last=_a9("last");
}else{
if(_a8=="manual"){
$("<span style=\"padding-left:6px;\"></span>").html(_a4.beforePageText).appendTo(tr).wrap("<td></td>");
bb.num=$("<input class=\"pagination-num\" type=\"text\" value=\"1\" size=\"2\">").appendTo(tr).wrap("<td></td>");
bb.num.unbind(".pagination").bind("keydown.pagination",function(e){
if(e.keyCode==13){
var _aa=parseInt($(this).val())||1;
_ae(_a2,_aa);
return false;
}
});
bb.after=$("<span style=\"padding-right:6px;\"></span>").appendTo(tr).wrap("<td></td>");
}else{
if(_a8=="refresh"){
bb.refresh=_a9("refresh");
}else{
if(_a8=="links"){
$("<td class=\"pagination-links\"></td>").appendTo(tr);
}
}
}
}
}
}
}
}
}
}
if(_a4.buttons){
$("<td><div class=\"pagination-btn-separator\"></div></td>").appendTo(tr);
if($.isArray(_a4.buttons)){
for(var i=0;i<_a4.buttons.length;i++){
var btn=_a4.buttons[i];
if(btn=="-"){
$("<td><div class=\"pagination-btn-separator\"></div></td>").appendTo(tr);
}else{
var td=$("<td></td>").appendTo(tr);
var a=$("<a href=\"javascript:void(0)\"></a>").appendTo(td);
a[0].onclick=eval(btn.handler||function(){
});
a.linkbutton($.extend({},btn,{plain:true}));
}
}
}else{
var td=$("<td></td>").appendTo(tr);
$(_a4.buttons).appendTo(td).show();
}
}
$("<div class=\"pagination-info\"></div>").appendTo(_a5);
$("<div style=\"clear:both;\"></div>").appendTo(_a5);
function _a9(_ab){
var btn=_a4.nav[_ab];
var a=$("<a href=\"javascript:void(0)\"></a>").appendTo(tr);
a.wrap("<td></td>");
a.linkbutton({iconCls:btn.iconCls,plain:true}).unbind(".pagination").bind("click.pagination",function(){
btn.handler.call(_a2);
});
return a;
};
function _a6(aa,_ac){
var _ad=$.inArray(_ac,aa);
if(_ad>=0){
aa.splice(_ad,1);
}
return aa;
};
};
function _ae(_af,_b0){
var _b1=$.data(_af,"pagination").options;
_b2(_af,{pageNumber:_b0});
_b1.onSelectPage.call(_af,_b1.pageNumber,_b1.pageSize);
};
function _b2(_b3,_b4){
var _b5=$.data(_b3,"pagination");
var _b6=_b5.options;
var bb=_b5.bb;
$.extend(_b6,_b4||{});
var ps=$(_b3).find("select.pagination-page-list");
if(ps.length){
ps.val(_b6.pageSize+"");
_b6.pageSize=parseInt(ps.val());
}
var _b7=Math.ceil(_b6.total/_b6.pageSize)||1;
if(_b6.pageNumber<1){
_b6.pageNumber=1;
}
if(_b6.pageNumber>_b7){
_b6.pageNumber=_b7;
}
if(_b6.total==0){
_b6.pageNumber=0;
_b7=0;
}
if(bb.num){
bb.num.val(_b6.pageNumber);
}
if(bb.after){
bb.after.html(_b6.afterPageText.replace(/{pages}/,_b7));
}
var td=$(_b3).find("td.pagination-links");
if(td.length){
td.empty();
var _b8=_b6.pageNumber-Math.floor(_b6.links/2);
if(_b8<1){
_b8=1;
}
var _b9=_b8+_b6.links-1;
if(_b9>_b7){
_b9=_b7;
}
_b8=_b9-_b6.links+1;
if(_b8<1){
_b8=1;
}
for(var i=_b8;i<=_b9;i++){
var a=$("<a class=\"pagination-link\" href=\"javascript:void(0)\"></a>").appendTo(td);
a.linkbutton({plain:true,text:i});
if(i==_b6.pageNumber){
a.linkbutton("select");
}else{
a.unbind(".pagination").bind("click.pagination",{pageNumber:i},function(e){
_ae(_b3,e.data.pageNumber);
});
}
}
}
var _ba=_b6.displayMsg;
_ba=_ba.replace(/{from}/,_b6.total==0?0:_b6.pageSize*(_b6.pageNumber-1)+1);
_ba=_ba.replace(/{to}/,Math.min(_b6.pageSize*(_b6.pageNumber),_b6.total));
_ba=_ba.replace(/{total}/,_b6.total);
$(_b3).find("div.pagination-info").html(_ba);
if(bb.first){
bb.first.linkbutton({disabled:((!_b6.total)||_b6.pageNumber==1)});
}
if(bb.prev){
bb.prev.linkbutton({disabled:((!_b6.total)||_b6.pageNumber==1)});
}
if(bb.next){
bb.next.linkbutton({disabled:(_b6.pageNumber==_b7)});
}
if(bb.last){
bb.last.linkbutton({disabled:(_b6.pageNumber==_b7)});
}
_bb(_b3,_b6.loading);
};
function _bb(_bc,_bd){
var _be=$.data(_bc,"pagination");
var _bf=_be.options;
_bf.loading=_bd;
if(_bf.showRefresh&&_be.bb.refresh){
_be.bb.refresh.linkbutton({iconCls:(_bf.loading?"pagination-loading":"pagination-load")});
}
};
$.fn.pagination=function(_c0,_c1){
if(typeof _c0=="string"){
return $.fn.pagination.methods[_c0](this,_c1);
}
_c0=_c0||{};
return this.each(function(){
var _c2;
var _c3=$.data(this,"pagination");
if(_c3){
_c2=$.extend(_c3.options,_c0);
}else{
_c2=$.extend({},$.fn.pagination.defaults,$.fn.pagination.parseOptions(this),_c0);
$.data(this,"pagination",{options:_c2});
}
_a1(this);
_b2(this);
});
};
$.fn.pagination.methods={options:function(jq){
return $.data(jq[0],"pagination").options;
},loading:function(jq){
return jq.each(function(){
_bb(this,true);
});
},loaded:function(jq){
return jq.each(function(){
_bb(this,false);
});
},refresh:function(jq,_c4){
return jq.each(function(){
_b2(this,_c4);
});
},select:function(jq,_c5){
return jq.each(function(){
_ae(this,_c5);
});
}};
$.fn.pagination.parseOptions=function(_c6){
var t=$(_c6);
return $.extend({},$.parser.parseOptions(_c6,[{total:"number",pageSize:"number",pageNumber:"number",links:"number"},{loading:"boolean",showPageList:"boolean",showRefresh:"boolean"}]),{pageList:(t.attr("pageList")?eval(t.attr("pageList")):undefined)});
};
$.fn.pagination.defaults={total:1,pageSize:10,pageNumber:1,pageList:[10,20,30,50],loading:false,buttons:null,showPageList:true,showRefresh:true,links:10,layout:["list","sep","first","prev","sep","manual","sep","next","last","sep","refresh"],onSelectPage:function(_c7,_c8){
},onBeforeRefresh:function(_c9,_ca){
},onRefresh:function(_cb,_cc){
},onChangePageSize:function(_cd){
},beforePageText:"Page",afterPageText:"of {pages}",displayMsg:"Displaying {from} to {to} of {total} items",nav:{first:{iconCls:"pagination-first",handler:function(){
var _ce=$(this).pagination("options");
if(_ce.pageNumber>1){
$(this).pagination("select",1);
}
}},prev:{iconCls:"pagination-prev",handler:function(){
var _cf=$(this).pagination("options");
if(_cf.pageNumber>1){
$(this).pagination("select",_cf.pageNumber-1);
}
}},next:{iconCls:"pagination-next",handler:function(){
var _d0=$(this).pagination("options");
var _d1=Math.ceil(_d0.total/_d0.pageSize);
if(_d0.pageNumber<_d1){
$(this).pagination("select",_d0.pageNumber+1);
}
}},last:{iconCls:"pagination-last",handler:function(){
var _d2=$(this).pagination("options");
var _d3=Math.ceil(_d2.total/_d2.pageSize);
if(_d2.pageNumber<_d3){
$(this).pagination("select",_d3);
}
}},refresh:{iconCls:"pagination-refresh",handler:function(){
var _d4=$(this).pagination("options");
if(_d4.onBeforeRefresh.call(this,_d4.pageNumber,_d4.pageSize)!=false){
$(this).pagination("select",_d4.pageNumber);
_d4.onRefresh.call(this,_d4.pageNumber,_d4.pageSize);
}
}}}};
})(jQuery);
(function($){
function _d5(_d6){
var _d7=$(_d6);
_d7.addClass("tree");
return _d7;
};
function _d8(_d9){
var _da=$.data(_d9,"tree").options;
$(_d9).unbind().bind("mouseover",function(e){
var tt=$(e.target);
var _db=tt.closest("div.tree-node");
if(!_db.length){
return;
}
_db.addClass("tree-node-hover");
if(tt.hasClass("tree-hit")){
if(tt.hasClass("tree-expanded")){
tt.addClass("tree-expanded-hover");
}else{
tt.addClass("tree-collapsed-hover");
}
}
e.stopPropagation();
}).bind("mouseout",function(e){
var tt=$(e.target);
var _dc=tt.closest("div.tree-node");
if(!_dc.length){
return;
}
_dc.removeClass("tree-node-hover");
if(tt.hasClass("tree-hit")){
if(tt.hasClass("tree-expanded")){
tt.removeClass("tree-expanded-hover");
}else{
tt.removeClass("tree-collapsed-hover");
}
}
e.stopPropagation();
}).bind("click",function(e){
var tt=$(e.target);
var _dd=tt.closest("div.tree-node");
if(!_dd.length){
return;
}
if(tt.hasClass("tree-hit")){
_144(_d9,_dd[0]);
return false;
}else{
if(tt.hasClass("tree-checkbox")){
_104(_d9,_dd[0]);
return false;
}else{
_18a(_d9,_dd[0]);
_da.onClick.call(_d9,_e0(_d9,_dd[0]));
}
}
e.stopPropagation();
}).bind("dblclick",function(e){
var _de=$(e.target).closest("div.tree-node");
if(!_de.length){
return;
}
_18a(_d9,_de[0]);
_da.onDblClick.call(_d9,_e0(_d9,_de[0]));
e.stopPropagation();
}).bind("contextmenu",function(e){
var _df=$(e.target).closest("div.tree-node");
if(!_df.length){
return;
}
_da.onContextMenu.call(_d9,e,_e0(_d9,_df[0]));
e.stopPropagation();
});
};
function _e1(_e2){
var _e3=$.data(_e2,"tree").options;
_e3.dnd=false;
var _e4=$(_e2).find("div.tree-node");
_e4.draggable("disable");
_e4.css("cursor","pointer");
};
function _e5(_e6){
var _e7=$.data(_e6,"tree");
var _e8=_e7.options;
var _e9=_e7.tree;
_e7.disabledNodes=[];
_e8.dnd=true;
_e9.find("div.tree-node").draggable({disabled:false,revert:true,cursor:"pointer",proxy:function(_ea){
var p=$("<div class=\"tree-node-proxy\"></div>").appendTo("body");
p.html("<span class=\"tree-dnd-icon tree-dnd-no\">&nbsp;</span>"+$(_ea).find(".tree-title").html());
p.hide();
return p;
},deltaX:15,deltaY:15,onBeforeDrag:function(e){
if(_e8.onBeforeDrag.call(_e6,_e0(_e6,this))==false){
return false;
}
if($(e.target).hasClass("tree-hit")||$(e.target).hasClass("tree-checkbox")){
return false;
}
if(e.which!=1){
return false;
}
var _eb=$(this).find("span.tree-indent");
if(_eb.length){
e.data.offsetWidth-=_eb.length*_eb.width();
}
},onStartDrag:function(e){
$(this).next("ul").find("div.tree-node").each(function(){
$(this).droppable("disable");
_e7.disabledNodes.push(this);
});
$(this).draggable("proxy").css({left:-10000,top:-10000});
_e8.onStartDrag.call(_e6,_e0(_e6,this));
var _ec=_e0(_e6,this);
if(_ec.id==undefined){
_ec.id="easyui_tree_node_id_temp";
_127(_e6,_ec);
}
_e7.draggingNodeId=_ec.id;
},onDrag:function(e){
var x1=e.pageX,y1=e.pageY,x2=e.data.startX,y2=e.data.startY;
var d=Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
if(d>3){
$(this).draggable("proxy").show();
}
this.pageY=e.pageY;
},onStopDrag:function(){
for(var i=0;i<_e7.disabledNodes.length;i++){
$(_e7.disabledNodes[i]).droppable("enable");
}
_e7.disabledNodes=[];
var _ed=_182(_e6,_e7.draggingNodeId);
if(_ed&&_ed.id=="easyui_tree_node_id_temp"){
_ed.id="";
_127(_e6,_ed);
}
_e8.onStopDrag.call(_e6,_ed);
}}).droppable({accept:"div.tree-node",onDragEnter:function(e,_ee){
if(_e8.onDragEnter.call(_e6,this,_ef(_ee))==false){
_f0(_ee,false);
$(this).removeClass("tree-node-append tree-node-top tree-node-bottom");
$(this).droppable("disable");
_e7.disabledNodes.push(this);
}
},onDragOver:function(e,_f1){
if($(this).droppable("options").disabled){
return;
}
var _f2=_f1.pageY;
var top=$(this).offset().top;
var _f3=top+$(this).outerHeight();
_f0(_f1,true);
$(this).removeClass("tree-node-append tree-node-top tree-node-bottom");
if(_f2>top+(_f3-top)/2){
if(_f3-_f2<5){
$(this).addClass("tree-node-bottom");
}else{
$(this).addClass("tree-node-append");
}
}else{
if(_f2-top<5){
$(this).addClass("tree-node-top");
}else{
$(this).addClass("tree-node-append");
}
}
if(_e8.onDragOver.call(_e6,this,_ef(_f1))==false){
_f0(_f1,false);
$(this).removeClass("tree-node-append tree-node-top tree-node-bottom");
$(this).droppable("disable");
_e7.disabledNodes.push(this);
}
},onDragLeave:function(e,_f4){
_f0(_f4,false);
$(this).removeClass("tree-node-append tree-node-top tree-node-bottom");
_e8.onDragLeave.call(_e6,this,_ef(_f4));
},onDrop:function(e,_f5){
var _f6=this;
var _f7,_f8;
if($(this).hasClass("tree-node-append")){
_f7=_f9;
_f8="append";
}else{
_f7=_fa;
_f8=$(this).hasClass("tree-node-top")?"top":"bottom";
}
if(_e8.onBeforeDrop.call(_e6,_f6,_ef(_f5),_f8)==false){
$(this).removeClass("tree-node-append tree-node-top tree-node-bottom");
return;
}
_f7(_f5,_f6,_f8);
$(this).removeClass("tree-node-append tree-node-top tree-node-bottom");
}});
function _ef(_fb,pop){
return $(_fb).closest("ul.tree").tree(pop?"pop":"getData",_fb);
};
function _f0(_fc,_fd){
var _fe=$(_fc).draggable("proxy").find("span.tree-dnd-icon");
_fe.removeClass("tree-dnd-yes tree-dnd-no").addClass(_fd?"tree-dnd-yes":"tree-dnd-no");
};
function _f9(_ff,dest){
if(_e0(_e6,dest).state=="closed"){
_13c(_e6,dest,function(){
_100();
});
}else{
_100();
}
function _100(){
var node=_ef(_ff,true);
$(_e6).tree("append",{parent:dest,data:[node]});
_e8.onDrop.call(_e6,dest,node,"append");
};
};
function _fa(_101,dest,_102){
var _103={};
if(_102=="top"){
_103.before=dest;
}else{
_103.after=dest;
}
var node=_ef(_101,true);
_103.data=node;
$(_e6).tree("insert",_103);
_e8.onDrop.call(_e6,dest,node,_102);
};
};
function _104(_105,_106,_107){
var _108=$.data(_105,"tree");
var opts=_108.options;
if(!opts.checkbox){
return;
}
var _109=_e0(_105,_106);
if(_107==undefined){
var ck=$(_106).find(".tree-checkbox");
if(ck.hasClass("tree-checkbox1")){
_107=false;
}else{
if(ck.hasClass("tree-checkbox0")){
_107=true;
}else{
if(_109._checked==undefined){
_109._checked=$(_106).find(".tree-checkbox").hasClass("tree-checkbox1");
}
_107=!_109._checked;
}
}
}
_109._checked=_107;
if(opts.onBeforeCheck.call(_105,_109,_107)==false){
return;
}
if(opts.cascadeCheck){
_10a(_109,_107);
_10b(_109,_107);
}else{
_10c($(_109.target),_107?"1":"0");
}
opts.onCheck.call(_105,_109,_107);
function _10c(node,flag){
var ck=node.find(".tree-checkbox");
ck.removeClass("tree-checkbox0 tree-checkbox1 tree-checkbox2");
ck.addClass("tree-checkbox"+flag);
};
function _10a(_10d,_10e){
if(opts.deepCheck){
var node=$("#"+_10d.domId);
var flag=_10e?"1":"0";
_10c(node,flag);
_10c(node.next(),flag);
}else{
_10f(_10d,_10e);
_12a(_10d.children||[],function(n){
_10f(n,_10e);
});
}
};
function _10f(_110,_111){
if(_110.hidden){
return;
}
var cls="tree-checkbox"+(_111?"1":"0");
var node=$("#"+_110.domId);
_10c(node,_111?"1":"0");
if(_110.children){
for(var i=0;i<_110.children.length;i++){
if(_110.children[i].hidden){
if(!$("#"+_110.children[i].domId).find("."+cls).length){
_10c(node,"2");
var _112=_14f(_105,node[0]);
while(_112){
_10c($(_112.target),"2");
_112=_14f(_105,_112[0]);
}
return;
}
}
}
}
};
function _10b(_113,_114){
var node=$("#"+_113.domId);
var _115=_14f(_105,node[0]);
if(_115){
var flag="";
if(_116(node,true)){
flag="1";
}else{
if(_116(node,false)){
flag="0";
}else{
flag="2";
}
}
_10c($(_115.target),flag);
_10b(_115,_114);
}
};
function _116(node,_117){
var cls="tree-checkbox"+(_117?"1":"0");
var ck=node.find(".tree-checkbox");
if(!ck.hasClass(cls)){
return false;
}
var b=true;
node.parent().siblings().each(function(){
var ck=$(this).children("div.tree-node").children(".tree-checkbox");
if(ck.length&&!ck.hasClass(cls)){
b=false;
return false;
}
});
return b;
};
};
function _118(_119,_11a){
var opts=$.data(_119,"tree").options;
if(!opts.checkbox){
return;
}
var node=$(_11a);
if(_11b(_119,_11a)){
var ck=node.find(".tree-checkbox");
if(ck.length){
if(ck.hasClass("tree-checkbox1")){
_104(_119,_11a,true);
}else{
_104(_119,_11a,false);
}
}else{
if(opts.onlyLeafCheck){
$("<span class=\"tree-checkbox tree-checkbox0\"></span>").insertBefore(node.find(".tree-title"));
}
}
}else{
var ck=node.find(".tree-checkbox");
if(opts.onlyLeafCheck){
ck.remove();
}else{
if(ck.hasClass("tree-checkbox1")){
_104(_119,_11a,true);
}else{
if(ck.hasClass("tree-checkbox2")){
var _11c=true;
var _11d=true;
var _11e=_11f(_119,_11a);
for(var i=0;i<_11e.length;i++){
if(_11e[i].checked){
_11d=false;
}else{
_11c=false;
}
}
if(_11c){
_104(_119,_11a,true);
}
if(_11d){
_104(_119,_11a,false);
}
}
}
}
}
};
function _120(_121,ul,data,_122){
var _123=$.data(_121,"tree");
var opts=_123.options;
var _124=$(ul).prevAll("div.tree-node:first");
data=opts.loadFilter.call(_121,data,_124[0]);
var _125=_126(_121,"domId",_124.attr("id"));
if(!_122){
_125?_125.children=data:_123.data=data;
$(ul).empty();
}else{
if(_125){
_125.children?_125.children=_125.children.concat(data):_125.children=data;
}else{
_123.data=_123.data.concat(data);
}
}
opts.view.render.call(opts.view,_121,ul,data);
if(opts.dnd){
_e5(_121);
}
if(_125){
_127(_121,_125);
}
var _128=[];
var _129=[];
for(var i=0;i<data.length;i++){
var node=data[i];
if(!node.checked){
_128.push(node);
}
}
_12a(data,function(node){
if(node.checked){
_129.push(node);
}
});
var _12b=opts.onCheck;
opts.onCheck=function(){
};
if(_128.length){
_104(_121,$("#"+_128[0].domId)[0],false);
}
for(var i=0;i<_129.length;i++){
_104(_121,$("#"+_129[i].domId)[0],true);
}
opts.onCheck=_12b;
setTimeout(function(){
_12c(_121,_121);
},0);
opts.onLoadSuccess.call(_121,_125,data);
};
function _12c(_12d,ul,_12e){
var opts=$.data(_12d,"tree").options;
if(opts.lines){
$(_12d).addClass("tree-lines");
}else{
$(_12d).removeClass("tree-lines");
return;
}
if(!_12e){
_12e=true;
$(_12d).find("span.tree-indent").removeClass("tree-line tree-join tree-joinbottom");
$(_12d).find("div.tree-node").removeClass("tree-node-last tree-root-first tree-root-one");
var _12f=$(_12d).tree("getRoots");
if(_12f.length>1){
$(_12f[0].target).addClass("tree-root-first");
}else{
if(_12f.length==1){
$(_12f[0].target).addClass("tree-root-one");
}
}
}
$(ul).children("li").each(function(){
var node=$(this).children("div.tree-node");
var ul=node.next("ul");
if(ul.length){
if($(this).next().length){
_130(node);
}
_12c(_12d,ul,_12e);
}else{
_131(node);
}
});
var _132=$(ul).children("li:last").children("div.tree-node").addClass("tree-node-last");
_132.children("span.tree-join").removeClass("tree-join").addClass("tree-joinbottom");
function _131(node,_133){
var icon=node.find("span.tree-icon");
icon.prev("span.tree-indent").addClass("tree-join");
};
function _130(node){
var _134=node.find("span.tree-indent, span.tree-hit").length;
node.next().find("div.tree-node").each(function(){
$(this).children("span:eq("+(_134-1)+")").addClass("tree-line");
});
};
};
function _135(_136,ul,_137,_138){
var opts=$.data(_136,"tree").options;
_137=$.extend({},opts.queryParams,_137||{});
var _139=null;
if(_136!=ul){
var node=$(ul).prev();
_139=_e0(_136,node[0]);
}
if(opts.onBeforeLoad.call(_136,_139,_137)==false){
return;
}
var _13a=$(ul).prev().children("span.tree-folder");
_13a.addClass("tree-loading");
var _13b=opts.loader.call(_136,_137,function(data){
_13a.removeClass("tree-loading");
_120(_136,ul,data);
if(_138){
_138();
}
},function(){
_13a.removeClass("tree-loading");
opts.onLoadError.apply(_136,arguments);
if(_138){
_138();
}
});
if(_13b==false){
_13a.removeClass("tree-loading");
}
};
function _13c(_13d,_13e,_13f){
var opts=$.data(_13d,"tree").options;
var hit=$(_13e).children("span.tree-hit");
if(hit.length==0){
return;
}
if(hit.hasClass("tree-expanded")){
return;
}
var node=_e0(_13d,_13e);
if(opts.onBeforeExpand.call(_13d,node)==false){
return;
}
hit.removeClass("tree-collapsed tree-collapsed-hover").addClass("tree-expanded");
hit.next().addClass("tree-folder-open");
var ul=$(_13e).next();
if(ul.length){
if(opts.animate){
ul.slideDown("normal",function(){
node.state="open";
opts.onExpand.call(_13d,node);
if(_13f){
_13f();
}
});
}else{
ul.css("display","block");
node.state="open";
opts.onExpand.call(_13d,node);
if(_13f){
_13f();
}
}
}else{
var _140=$("<ul style=\"display:none\"></ul>").insertAfter(_13e);
_135(_13d,_140[0],{id:node.id},function(){
if(_140.is(":empty")){
_140.remove();
}
if(opts.animate){
_140.slideDown("normal",function(){
node.state="open";
opts.onExpand.call(_13d,node);
if(_13f){
_13f();
}
});
}else{
_140.css("display","block");
node.state="open";
opts.onExpand.call(_13d,node);
if(_13f){
_13f();
}
}
});
}
};
function _141(_142,_143){
var opts=$.data(_142,"tree").options;
var hit=$(_143).children("span.tree-hit");
if(hit.length==0){
return;
}
if(hit.hasClass("tree-collapsed")){
return;
}
var node=_e0(_142,_143);
if(opts.onBeforeCollapse.call(_142,node)==false){
return;
}
hit.removeClass("tree-expanded tree-expanded-hover").addClass("tree-collapsed");
hit.next().removeClass("tree-folder-open");
var ul=$(_143).next();
if(opts.animate){
ul.slideUp("normal",function(){
node.state="closed";
opts.onCollapse.call(_142,node);
});
}else{
ul.css("display","none");
node.state="closed";
opts.onCollapse.call(_142,node);
}
};
function _144(_145,_146){
var hit=$(_146).children("span.tree-hit");
if(hit.length==0){
return;
}
if(hit.hasClass("tree-expanded")){
_141(_145,_146);
}else{
_13c(_145,_146);
}
};
function _147(_148,_149){
var _14a=_11f(_148,_149);
if(_149){
_14a.unshift(_e0(_148,_149));
}
for(var i=0;i<_14a.length;i++){
_13c(_148,_14a[i].target);
}
};
function _14b(_14c,_14d){
var _14e=[];
var p=_14f(_14c,_14d);
while(p){
_14e.unshift(p);
p=_14f(_14c,p.target);
}
for(var i=0;i<_14e.length;i++){
_13c(_14c,_14e[i].target);
}
};
function _150(_151,_152){
var c=$(_151).parent();
while(c[0].tagName!="BODY"&&c.css("overflow-y")!="auto"){
c=c.parent();
}
var n=$(_152);
var ntop=n.offset().top;
if(c[0].tagName!="BODY"){
var ctop=c.offset().top;
if(ntop<ctop){
c.scrollTop(c.scrollTop()+ntop-ctop);
}else{
if(ntop+n.outerHeight()>ctop+c.outerHeight()-18){
c.scrollTop(c.scrollTop()+ntop+n.outerHeight()-ctop-c.outerHeight()+18);
}
}
}else{
c.scrollTop(ntop);
}
};
function _153(_154,_155){
var _156=_11f(_154,_155);
if(_155){
_156.unshift(_e0(_154,_155));
}
for(var i=0;i<_156.length;i++){
_141(_154,_156[i].target);
}
};
function _157(_158,_159){
var node=$(_159.parent);
var data=_159.data;
if(!data){
return;
}
data=$.isArray(data)?data:[data];
if(!data.length){
return;
}
var ul;
if(node.length==0){
ul=$(_158);
}else{
if(_11b(_158,node[0])){
var _15a=node.find("span.tree-icon");
_15a.removeClass("tree-file").addClass("tree-folder tree-folder-open");
var hit=$("<span class=\"tree-hit tree-expanded\"></span>").insertBefore(_15a);
if(hit.prev().length){
hit.prev().remove();
}
}
ul=node.next();
if(!ul.length){
ul=$("<ul></ul>").insertAfter(node);
}
}
_120(_158,ul[0],data,true);
_118(_158,ul.prev());
};
function _15b(_15c,_15d){
var ref=_15d.before||_15d.after;
var _15e=_14f(_15c,ref);
var data=_15d.data;
if(!data){
return;
}
data=$.isArray(data)?data:[data];
if(!data.length){
return;
}
_157(_15c,{parent:(_15e?_15e.target:null),data:data});
var _15f=_15e?_15e.children:$(_15c).tree("getRoots");
for(var i=0;i<_15f.length;i++){
if(_15f[i].domId==$(ref).attr("id")){
for(var j=data.length-1;j>=0;j--){
_15f.splice((_15d.before?i:(i+1)),0,data[j]);
}
_15f.splice(_15f.length-data.length,data.length);
break;
}
}
var li=$();
for(var i=0;i<data.length;i++){
li=li.add($("#"+data[i].domId).parent());
}
if(_15d.before){
li.insertBefore($(ref).parent());
}else{
li.insertAfter($(ref).parent());
}
};
function _160(_161,_162){
var _163=del(_162);
$(_162).parent().remove();
if(_163){
if(!_163.children||!_163.children.length){
var node=$(_163.target);
node.find(".tree-icon").removeClass("tree-folder").addClass("tree-file");
node.find(".tree-hit").remove();
$("<span class=\"tree-indent\"></span>").prependTo(node);
node.next().remove();
}
_127(_161,_163);
_118(_161,_163.target);
}
_12c(_161,_161);
function del(_164){
var id=$(_164).attr("id");
var _165=_14f(_161,_164);
var cc=_165?_165.children:$.data(_161,"tree").data;
for(var i=0;i<cc.length;i++){
if(cc[i].domId==id){
cc.splice(i,1);
break;
}
}
return _165;
};
};
function _127(_166,_167){
var opts=$.data(_166,"tree").options;
var node=$(_167.target);
var data=_e0(_166,_167.target);
var _168=data.checked;
if(data.iconCls){
node.find(".tree-icon").removeClass(data.iconCls);
}
$.extend(data,_167);
node.find(".tree-title").html(opts.formatter.call(_166,data));
if(data.iconCls){
node.find(".tree-icon").addClass(data.iconCls);
}
if(_168!=data.checked){
_104(_166,_167.target,data.checked);
}
};
function _169(_16a,_16b){
if(_16b){
var p=_14f(_16a,_16b);
while(p){
_16b=p.target;
p=_14f(_16a,_16b);
}
return _e0(_16a,_16b);
}else{
var _16c=_16d(_16a);
return _16c.length?_16c[0]:null;
}
};
function _16d(_16e){
var _16f=$.data(_16e,"tree").data;
for(var i=0;i<_16f.length;i++){
_170(_16f[i]);
}
return _16f;
};
function _11f(_171,_172){
var _173=[];
var n=_e0(_171,_172);
var data=n?(n.children||[]):$.data(_171,"tree").data;
_12a(data,function(node){
_173.push(_170(node));
});
return _173;
};
function _14f(_174,_175){
var p=$(_175).closest("ul").prevAll("div.tree-node:first");
return _e0(_174,p[0]);
};
function _176(_177,_178){
_178=_178||"checked";
if(!$.isArray(_178)){
_178=[_178];
}
var _179=[];
for(var i=0;i<_178.length;i++){
var s=_178[i];
if(s=="checked"){
_179.push("span.tree-checkbox1");
}else{
if(s=="unchecked"){
_179.push("span.tree-checkbox0");
}else{
if(s=="indeterminate"){
_179.push("span.tree-checkbox2");
}
}
}
}
var _17a=[];
$(_177).find(_179.join(",")).each(function(){
var node=$(this).parent();
_17a.push(_e0(_177,node[0]));
});
return _17a;
};
function _17b(_17c){
var node=$(_17c).find("div.tree-node-selected");
return node.length?_e0(_17c,node[0]):null;
};
function _17d(_17e,_17f){
var data=_e0(_17e,_17f);
if(data&&data.children){
_12a(data.children,function(node){
_170(node);
});
}
return data;
};
function _e0(_180,_181){
return _126(_180,"domId",$(_181).attr("id"));
};
function _182(_183,id){
return _126(_183,"id",id);
};
function _126(_184,_185,_186){
var data=$.data(_184,"tree").data;
var _187=null;
_12a(data,function(node){
if(node[_185]==_186){
_187=_170(node);
return false;
}
});
return _187;
};
function _170(node){
var d=$("#"+node.domId);
node.target=d[0];
node.checked=d.find(".tree-checkbox").hasClass("tree-checkbox1");
return node;
};
function _12a(data,_188){
var _189=[];
for(var i=0;i<data.length;i++){
_189.push(data[i]);
}
while(_189.length){
var node=_189.shift();
if(_188(node)==false){
return;
}
if(node.children){
for(var i=node.children.length-1;i>=0;i--){
_189.unshift(node.children[i]);
}
}
}
};
function _18a(_18b,_18c){
var opts=$.data(_18b,"tree").options;
var node=_e0(_18b,_18c);
if(opts.onBeforeSelect.call(_18b,node)==false){
return;
}
$(_18b).find("div.tree-node-selected").removeClass("tree-node-selected");
$(_18c).addClass("tree-node-selected");
opts.onSelect.call(_18b,node);
};
function _11b(_18d,_18e){
return $(_18e).children("span.tree-hit").length==0;
};
function _18f(_190,_191){
var opts=$.data(_190,"tree").options;
var node=_e0(_190,_191);
if(opts.onBeforeEdit.call(_190,node)==false){
return;
}
$(_191).css("position","relative");
var nt=$(_191).find(".tree-title");
var _192=nt.outerWidth();
nt.empty();
var _193=$("<input class=\"tree-editor\">").appendTo(nt);
_193.val(node.text).focus();
_193.width(_192+20);
_193.height(document.compatMode=="CSS1Compat"?(18-(_193.outerHeight()-_193.height())):18);
_193.bind("click",function(e){
return false;
}).bind("mousedown",function(e){
e.stopPropagation();
}).bind("mousemove",function(e){
e.stopPropagation();
}).bind("keydown",function(e){
if(e.keyCode==13){
_194(_190,_191);
return false;
}else{
if(e.keyCode==27){
_198(_190,_191);
return false;
}
}
}).bind("blur",function(e){
e.stopPropagation();
_194(_190,_191);
});
};
function _194(_195,_196){
var opts=$.data(_195,"tree").options;
$(_196).css("position","");
var _197=$(_196).find("input.tree-editor");
var val=_197.val();
_197.remove();
var node=_e0(_195,_196);
node.text=val;
_127(_195,node);
opts.onAfterEdit.call(_195,node);
};
function _198(_199,_19a){
var opts=$.data(_199,"tree").options;
$(_19a).css("position","");
$(_19a).find("input.tree-editor").remove();
var node=_e0(_199,_19a);
_127(_199,node);
opts.onCancelEdit.call(_199,node);
};
function _19b(_19c,q){
var _19d=$.data(_19c,"tree");
var opts=_19d.options;
var ids={};
_12a(_19d.data,function(node){
if(opts.filter.call(_19c,q,node)){
$("#"+node.domId).removeClass("tree-node-hidden");
ids[node.domId]=1;
node.hidden=false;
}else{
$("#"+node.domId).addClass("tree-node-hidden");
node.hidden=true;
}
});
for(var id in ids){
_19e(id);
}
function _19e(_19f){
var p=$(_19c).tree("getParent",$("#"+_19f)[0]);
while(p){
$(p.target).removeClass("tree-node-hidden");
p.hidden=false;
p=$(_19c).tree("getParent",p.target);
}
};
};
$.fn.tree=function(_1a0,_1a1){
if(typeof _1a0=="string"){
return $.fn.tree.methods[_1a0](this,_1a1);
}
var _1a0=_1a0||{};
return this.each(function(){
var _1a2=$.data(this,"tree");
var opts;
if(_1a2){
opts=$.extend(_1a2.options,_1a0);
_1a2.options=opts;
}else{
opts=$.extend({},$.fn.tree.defaults,$.fn.tree.parseOptions(this),_1a0);
$.data(this,"tree",{options:opts,tree:_d5(this),data:[]});
var data=$.fn.tree.parseData(this);
if(data.length){
_120(this,this,data);
}
}
_d8(this);
if(opts.data){
_120(this,this,$.extend(true,[],opts.data));
}
_135(this,this);
});
};
$.fn.tree.methods={options:function(jq){
return $.data(jq[0],"tree").options;
},loadData:function(jq,data){
return jq.each(function(){
_120(this,this,data);
});
},getNode:function(jq,_1a3){
return _e0(jq[0],_1a3);
},getData:function(jq,_1a4){
return _17d(jq[0],_1a4);
},reload:function(jq,_1a5){
return jq.each(function(){
if(_1a5){
var node=$(_1a5);
var hit=node.children("span.tree-hit");
hit.removeClass("tree-expanded tree-expanded-hover").addClass("tree-collapsed");
node.next().remove();
_13c(this,_1a5);
}else{
$(this).empty();
_135(this,this);
}
});
},getRoot:function(jq,_1a6){
return _169(jq[0],_1a6);
},getRoots:function(jq){
return _16d(jq[0]);
},getParent:function(jq,_1a7){
return _14f(jq[0],_1a7);
},getChildren:function(jq,_1a8){
return _11f(jq[0],_1a8);
},getChecked:function(jq,_1a9){
return _176(jq[0],_1a9);
},getSelected:function(jq){
return _17b(jq[0]);
},isLeaf:function(jq,_1aa){
return _11b(jq[0],_1aa);
},find:function(jq,id){
return _182(jq[0],id);
},select:function(jq,_1ab){
return jq.each(function(){
_18a(this,_1ab);
});
},check:function(jq,_1ac){
return jq.each(function(){
_104(this,_1ac,true);
});
},uncheck:function(jq,_1ad){
return jq.each(function(){
_104(this,_1ad,false);
});
},collapse:function(jq,_1ae){
return jq.each(function(){
_141(this,_1ae);
});
},expand:function(jq,_1af){
return jq.each(function(){
_13c(this,_1af);
});
},collapseAll:function(jq,_1b0){
return jq.each(function(){
_153(this,_1b0);
});
},expandAll:function(jq,_1b1){
return jq.each(function(){
_147(this,_1b1);
});
},expandTo:function(jq,_1b2){
return jq.each(function(){
_14b(this,_1b2);
});
},scrollTo:function(jq,_1b3){
return jq.each(function(){
_150(this,_1b3);
});
},toggle:function(jq,_1b4){
return jq.each(function(){
_144(this,_1b4);
});
},append:function(jq,_1b5){
return jq.each(function(){
_157(this,_1b5);
});
},insert:function(jq,_1b6){
return jq.each(function(){
_15b(this,_1b6);
});
},remove:function(jq,_1b7){
return jq.each(function(){
_160(this,_1b7);
});
},pop:function(jq,_1b8){
var node=jq.tree("getData",_1b8);
jq.tree("remove",_1b8);
return node;
},update:function(jq,_1b9){
return jq.each(function(){
_127(this,_1b9);
});
},enableDnd:function(jq){
return jq.each(function(){
_e5(this);
});
},disableDnd:function(jq){
return jq.each(function(){
_e1(this);
});
},beginEdit:function(jq,_1ba){
return jq.each(function(){
_18f(this,_1ba);
});
},endEdit:function(jq,_1bb){
return jq.each(function(){
_194(this,_1bb);
});
},cancelEdit:function(jq,_1bc){
return jq.each(function(){
_198(this,_1bc);
});
},doFilter:function(jq,q){
return jq.each(function(){
_19b(this,q);
});
}};
$.fn.tree.parseOptions=function(_1bd){
var t=$(_1bd);
return $.extend({},$.parser.parseOptions(_1bd,["url","method",{checkbox:"boolean",cascadeCheck:"boolean",onlyLeafCheck:"boolean"},{animate:"boolean",lines:"boolean",dnd:"boolean"}]));
};
$.fn.tree.parseData=function(_1be){
var data=[];
_1bf(data,$(_1be));
return data;
function _1bf(aa,tree){
tree.children("li").each(function(){
var node=$(this);
var item=$.extend({},$.parser.parseOptions(this,["id","iconCls","state"]),{checked:(node.attr("checked")?true:undefined)});
item.text=node.children("span").html();
if(!item.text){
item.text=node.html();
}
var _1c0=node.children("ul");
if(_1c0.length){
item.children=[];
_1bf(item.children,_1c0);
}
aa.push(item);
});
};
};
var _1c1=1;
var _1c2={render:function(_1c3,ul,data){
var opts=$.data(_1c3,"tree").options;
var _1c4=$(ul).prev("div.tree-node").find("span.tree-indent, span.tree-hit").length;
var cc=_1c5(_1c4,data);
$(ul).append(cc.join(""));
function _1c5(_1c6,_1c7){
var cc=[];
for(var i=0;i<_1c7.length;i++){
var item=_1c7[i];
if(item.state!="open"&&item.state!="closed"){
item.state="open";
}
item.domId="_easyui_tree_"+_1c1++;
cc.push("<li>");
cc.push("<div id=\""+item.domId+"\" class=\"tree-node\">");
for(var j=0;j<_1c6;j++){
cc.push("<span class=\"tree-indent\"></span>");
}
var _1c8=false;
if(item.state=="closed"){
cc.push("<span class=\"tree-hit tree-collapsed\"></span>");
cc.push("<span class=\"tree-icon tree-folder "+(item.iconCls?item.iconCls:"")+"\"></span>");
}else{
if(item.children&&item.children.length){
cc.push("<span class=\"tree-hit tree-expanded\"></span>");
cc.push("<span class=\"tree-icon tree-folder tree-folder-open "+(item.iconCls?item.iconCls:"")+"\"></span>");
}else{
cc.push("<span class=\"tree-indent\"></span>");
cc.push("<span class=\"tree-icon tree-file "+(item.iconCls?item.iconCls:"")+"\"></span>");
_1c8=true;
}
}
if(opts.checkbox){
if((!opts.onlyLeafCheck)||_1c8){
cc.push("<span class=\"tree-checkbox tree-checkbox0\"></span>");
}
}
cc.push("<span class=\"tree-title\">"+opts.formatter.call(_1c3,item)+"</span>");
cc.push("</div>");
if(item.children&&item.children.length){
var tmp=_1c5(_1c6+1,item.children);
cc.push("<ul style=\"display:"+(item.state=="closed"?"none":"block")+"\">");
cc=cc.concat(tmp);
cc.push("</ul>");
}
cc.push("</li>");
}
return cc;
};
}};
$.fn.tree.defaults={url:null,method:"post",animate:false,checkbox:false,cascadeCheck:true,onlyLeafCheck:false,lines:false,dnd:false,data:null,queryParams:{},formatter:function(node){
return node.text;
},filter:function(q,node){
return node.text.toLowerCase().indexOf(q.toLowerCase())>=0;
},loader:function(_1c9,_1ca,_1cb){
var opts=$(this).tree("options");
if(!opts.url){
return false;
}
$.ajax({type:opts.method,url:opts.url,data:_1c9,dataType:"json",success:function(data){
_1ca(data);
},error:function(){
_1cb.apply(this,arguments);
}});
},loadFilter:function(data,_1cc){
return data;
},view:_1c2,onBeforeLoad:function(node,_1cd){
},onLoadSuccess:function(node,data){
},onLoadError:function(){
},onClick:function(node){
},onDblClick:function(node){
},onBeforeExpand:function(node){
},onExpand:function(node){
},onBeforeCollapse:function(node){
},onCollapse:function(node){
},onBeforeCheck:function(node,_1ce){
},onCheck:function(node,_1cf){
},onBeforeSelect:function(node){
},onSelect:function(node){
},onContextMenu:function(e,node){
},onBeforeDrag:function(node){
},onStartDrag:function(node){
},onStopDrag:function(node){
},onDragEnter:function(_1d0,_1d1){
},onDragOver:function(_1d2,_1d3){
},onDragLeave:function(_1d4,_1d5){
},onBeforeDrop:function(_1d6,_1d7,_1d8){
},onDrop:function(_1d9,_1da,_1db){
},onBeforeEdit:function(node){
},onAfterEdit:function(node){
},onCancelEdit:function(node){
}};
})(jQuery);
(function($){
function init(_1dc){
$(_1dc).addClass("progressbar");
$(_1dc).html("<div class=\"progressbar-text\"></div><div class=\"progressbar-value\"><div class=\"progressbar-text\"></div></div>");
$(_1dc).bind("_resize",function(e,_1dd){
if($(this).hasClass("easyui-fluid")||_1dd){
_1de(_1dc);
}
return false;
});
return $(_1dc);
};
function _1de(_1df,_1e0){
var opts=$.data(_1df,"progressbar").options;
var bar=$.data(_1df,"progressbar").bar;
if(_1e0){
opts.width=_1e0;
}
bar._size(opts);
bar.find("div.progressbar-text").css("width",bar.width());
bar.find("div.progressbar-text,div.progressbar-value").css({height:bar.height()+"px",lineHeight:bar.height()+"px"});
};
$.fn.progressbar=function(_1e1,_1e2){
if(typeof _1e1=="string"){
var _1e3=$.fn.progressbar.methods[_1e1];
if(_1e3){
return _1e3(this,_1e2);
}
}
_1e1=_1e1||{};
return this.each(function(){
var _1e4=$.data(this,"progressbar");
if(_1e4){
$.extend(_1e4.options,_1e1);
}else{
_1e4=$.data(this,"progressbar",{options:$.extend({},$.fn.progressbar.defaults,$.fn.progressbar.parseOptions(this),_1e1),bar:init(this)});
}
$(this).progressbar("setValue",_1e4.options.value);
_1de(this);
});
};
$.fn.progressbar.methods={options:function(jq){
return $.data(jq[0],"progressbar").options;
},resize:function(jq,_1e5){
return jq.each(function(){
_1de(this,_1e5);
});
},getValue:function(jq){
return $.data(jq[0],"progressbar").options.value;
},setValue:function(jq,_1e6){
if(_1e6<0){
_1e6=0;
}
if(_1e6>100){
_1e6=100;
}
return jq.each(function(){
var opts=$.data(this,"progressbar").options;
var text=opts.text.replace(/{value}/,_1e6);
var _1e7=opts.value;
opts.value=_1e6;
$(this).find("div.progressbar-value").width(_1e6+"%");
$(this).find("div.progressbar-text").html(text);
if(_1e7!=_1e6){
opts.onChange.call(this,_1e6,_1e7);
}
});
}};
$.fn.progressbar.parseOptions=function(_1e8){
return $.extend({},$.parser.parseOptions(_1e8,["width","height","text",{value:"number"}]));
};
$.fn.progressbar.defaults={width:"auto",height:22,value:0,text:"{value}%",onChange:function(_1e9,_1ea){
}};
})(jQuery);
(function($){
function init(_1eb){
$(_1eb).addClass("tooltip-f");
};
function _1ec(_1ed){
var opts=$.data(_1ed,"tooltip").options;
$(_1ed).unbind(".tooltip").bind(opts.showEvent+".tooltip",function(e){
$(_1ed).tooltip("show",e);
}).bind(opts.hideEvent+".tooltip",function(e){
$(_1ed).tooltip("hide",e);
}).bind("mousemove.tooltip",function(e){
if(opts.trackMouse){
opts.trackMouseX=e.pageX;
opts.trackMouseY=e.pageY;
$(_1ed).tooltip("reposition");
}
});
};
function _1ee(_1ef){
var _1f0=$.data(_1ef,"tooltip");
if(_1f0.showTimer){
clearTimeout(_1f0.showTimer);
_1f0.showTimer=null;
}
if(_1f0.hideTimer){
clearTimeout(_1f0.hideTimer);
_1f0.hideTimer=null;
}
};
function _1f1(_1f2){
var _1f3=$.data(_1f2,"tooltip");
if(!_1f3||!_1f3.tip){
return;
}
var opts=_1f3.options;
var tip=_1f3.tip;
var pos={left:-100000,top:-100000};
if($(_1f2).is(":visible")){
pos=_1f4(opts.position);
if(opts.position=="top"&&pos.top<0){
pos=_1f4("bottom");
}else{
if((opts.position=="bottom")&&(pos.top+tip._outerHeight()>$(window)._outerHeight()+$(document).scrollTop())){
pos=_1f4("top");
}
}
if(pos.left<0){
if(opts.position=="left"){
pos=_1f4("right");
}else{
$(_1f2).tooltip("arrow").css("left",tip._outerWidth()/2+pos.left);
pos.left=0;
}
}else{
if(pos.left+tip._outerWidth()>$(window)._outerWidth()+$(document)._scrollLeft()){
if(opts.position=="right"){
pos=_1f4("left");
}else{
var left=pos.left;
pos.left=$(window)._outerWidth()+$(document)._scrollLeft()-tip._outerWidth();
$(_1f2).tooltip("arrow").css("left",tip._outerWidth()/2-(pos.left-left));
}
}
}
}
tip.css({left:pos.left,top:pos.top,zIndex:(opts.zIndex!=undefined?opts.zIndex:($.fn.window?$.fn.window.defaults.zIndex++:""))});
opts.onPosition.call(_1f2,pos.left,pos.top);
function _1f4(_1f5){
opts.position=_1f5||"bottom";
tip.removeClass("tooltip-top tooltip-bottom tooltip-left tooltip-right").addClass("tooltip-"+opts.position);
var left,top;
if(opts.trackMouse){
t=$();
left=opts.trackMouseX+opts.deltaX;
top=opts.trackMouseY+opts.deltaY;
}else{
var t=$(_1f2);
left=t.offset().left+opts.deltaX;
top=t.offset().top+opts.deltaY;
}
switch(opts.position){
case "right":
left+=t._outerWidth()+12+(opts.trackMouse?12:0);
top-=(tip._outerHeight()-t._outerHeight())/2;
break;
case "left":
left-=tip._outerWidth()+12+(opts.trackMouse?12:0);
top-=(tip._outerHeight()-t._outerHeight())/2;
break;
case "top":
left-=(tip._outerWidth()-t._outerWidth())/2;
top-=tip._outerHeight()+12+(opts.trackMouse?12:0);
break;
case "bottom":
left-=(tip._outerWidth()-t._outerWidth())/2;
top+=t._outerHeight()+12+(opts.trackMouse?12:0);
break;
}
return {left:left,top:top};
};
};
function _1f6(_1f7,e){
var _1f8=$.data(_1f7,"tooltip");
var opts=_1f8.options;
var tip=_1f8.tip;
if(!tip){
tip=$("<div tabindex=\"-1\" class=\"tooltip\">"+"<div class=\"tooltip-content\"></div>"+"<div class=\"tooltip-arrow-outer\"></div>"+"<div class=\"tooltip-arrow\"></div>"+"</div>").appendTo("body");
_1f8.tip=tip;
_1f9(_1f7);
}
_1ee(_1f7);
_1f8.showTimer=setTimeout(function(){
$(_1f7).tooltip("reposition");
tip.show();
opts.onShow.call(_1f7,e);
var _1fa=tip.children(".tooltip-arrow-outer");
var _1fb=tip.children(".tooltip-arrow");
var bc="border-"+opts.position+"-color";
_1fa.add(_1fb).css({borderTopColor:"",borderBottomColor:"",borderLeftColor:"",borderRightColor:""});
_1fa.css(bc,tip.css(bc));
_1fb.css(bc,tip.css("backgroundColor"));
},opts.showDelay);
};
function _1fc(_1fd,e){
var _1fe=$.data(_1fd,"tooltip");
if(_1fe&&_1fe.tip){
_1ee(_1fd);
_1fe.hideTimer=setTimeout(function(){
_1fe.tip.hide();
_1fe.options.onHide.call(_1fd,e);
},_1fe.options.hideDelay);
}
};
function _1f9(_1ff,_200){
var _201=$.data(_1ff,"tooltip");
var opts=_201.options;
if(_200){
opts.content=_200;
}
if(!_201.tip){
return;
}
var cc=typeof opts.content=="function"?opts.content.call(_1ff):opts.content;
_201.tip.children(".tooltip-content").html(cc);
opts.onUpdate.call(_1ff,cc);
};
function _202(_203){
var _204=$.data(_203,"tooltip");
if(_204){
_1ee(_203);
var opts=_204.options;
if(_204.tip){
_204.tip.remove();
}
if(opts._title){
$(_203).attr("title",opts._title);
}
$.removeData(_203,"tooltip");
$(_203).unbind(".tooltip").removeClass("tooltip-f");
opts.onDestroy.call(_203);
}
};
$.fn.tooltip=function(_205,_206){
if(typeof _205=="string"){
return $.fn.tooltip.methods[_205](this,_206);
}
_205=_205||{};
return this.each(function(){
var _207=$.data(this,"tooltip");
if(_207){
$.extend(_207.options,_205);
}else{
$.data(this,"tooltip",{options:$.extend({},$.fn.tooltip.defaults,$.fn.tooltip.parseOptions(this),_205)});
init(this);
}
_1ec(this);
_1f9(this);
});
};
$.fn.tooltip.methods={options:function(jq){
return $.data(jq[0],"tooltip").options;
},tip:function(jq){
return $.data(jq[0],"tooltip").tip;
},arrow:function(jq){
return jq.tooltip("tip").children(".tooltip-arrow-outer,.tooltip-arrow");
},show:function(jq,e){
return jq.each(function(){
_1f6(this,e);
});
},hide:function(jq,e){
return jq.each(function(){
_1fc(this,e);
});
},update:function(jq,_208){
return jq.each(function(){
_1f9(this,_208);
});
},reposition:function(jq){
return jq.each(function(){
_1f1(this);
});
},destroy:function(jq){
return jq.each(function(){
_202(this);
});
}};
$.fn.tooltip.parseOptions=function(_209){
var t=$(_209);
var opts=$.extend({},$.parser.parseOptions(_209,["position","showEvent","hideEvent","content",{trackMouse:"boolean",deltaX:"number",deltaY:"number",showDelay:"number",hideDelay:"number"}]),{_title:t.attr("title")});
t.attr("title","");
if(!opts.content){
opts.content=opts._title;
}
return opts;
};
$.fn.tooltip.defaults={position:"bottom",content:null,trackMouse:false,deltaX:0,deltaY:0,showEvent:"mouseenter",hideEvent:"mouseleave",showDelay:200,hideDelay:100,onShow:function(e){
},onHide:function(e){
},onUpdate:function(_20a){
},onPosition:function(left,top){
},onDestroy:function(){
}};
})(jQuery);
(function($){
$.fn._remove=function(){
return this.each(function(){
$(this).remove();
try{
this.outerHTML="";
}
catch(err){
}
});
};
function _20b(node){
node._remove();
};
function _20c(_20d,_20e){
var _20f=$.data(_20d,"panel");
var opts=_20f.options;
var _210=_20f.panel;
var _211=_210.children(".panel-header");
var _212=_210.children(".panel-body");
var _213=_210.children(".panel-footer");
if(_20e){
$.extend(opts,{width:_20e.width,height:_20e.height,minWidth:_20e.minWidth,maxWidth:_20e.maxWidth,minHeight:_20e.minHeight,maxHeight:_20e.maxHeight,left:_20e.left,top:_20e.top});
}
_210._size(opts);
_211.add(_212)._outerWidth(_210.width());
if(!isNaN(parseInt(opts.height))){
_212._outerHeight(_210.height()-_211._outerHeight()-_213._outerHeight());
}else{
_212.css("height","");
var min=$.parser.parseValue("minHeight",opts.minHeight,_210.parent());
var max=$.parser.parseValue("maxHeight",opts.maxHeight,_210.parent());
var _214=_211._outerHeight()+_213._outerHeight()+_210._outerHeight()-_210.height();
_212._size("minHeight",min?(min-_214):"");
_212._size("maxHeight",max?(max-_214):"");
}
_210.css({height:"",minHeight:"",maxHeight:"",left:opts.left,top:opts.top});
opts.onResize.apply(_20d,[opts.width,opts.height]);
$(_20d).panel("doLayout");
};
function _215(_216,_217){
var opts=$.data(_216,"panel").options;
var _218=$.data(_216,"panel").panel;
if(_217){
if(_217.left!=null){
opts.left=_217.left;
}
if(_217.top!=null){
opts.top=_217.top;
}
}
_218.css({left:opts.left,top:opts.top});
opts.onMove.apply(_216,[opts.left,opts.top]);
};
function _219(_21a){
$(_21a).addClass("panel-body")._size("clear");
var _21b=$("<div class=\"panel\"></div>").insertBefore(_21a);
_21b[0].appendChild(_21a);
_21b.bind("_resize",function(e,_21c){
if($(this).hasClass("easyui-fluid")||_21c){
_20c(_21a);
}
return false;
});
return _21b;
};
function _21d(_21e){
var _21f=$.data(_21e,"panel");
var opts=_21f.options;
var _220=_21f.panel;
_220.css(opts.style);
_220.addClass(opts.cls);
_221();
_222();
var _223=$(_21e).panel("header");
var body=$(_21e).panel("body");
var _224=$(_21e).siblings(".panel-footer");
if(opts.border){
_223.removeClass("panel-header-noborder");
body.removeClass("panel-body-noborder");
_224.removeClass("panel-footer-noborder");
}else{
_223.addClass("panel-header-noborder");
body.addClass("panel-body-noborder");
_224.addClass("panel-footer-noborder");
}
_223.addClass(opts.headerCls);
body.addClass(opts.bodyCls);
$(_21e).attr("id",opts.id||"");
if(opts.content){
$(_21e).panel("clear");
$(_21e).html(opts.content);
$.parser.parse($(_21e));
}
function _221(){
if(opts.noheader||(!opts.title&&!opts.header)){
_20b(_220.children(".panel-header"));
_220.children(".panel-body").addClass("panel-body-noheader");
}else{
if(opts.header){
$(opts.header).addClass("panel-header").prependTo(_220);
}else{
var _225=_220.children(".panel-header");
if(!_225.length){
_225=$("<div class=\"panel-header\"></div>").prependTo(_220);
}
if(!$.isArray(opts.tools)){
_225.find("div.panel-tool .panel-tool-a").appendTo(opts.tools);
}
_225.empty();
var _226=$("<div class=\"panel-title\"></div>").html(opts.title).appendTo(_225);
if(opts.iconCls){
_226.addClass("panel-with-icon");
$("<div class=\"panel-icon\"></div>").addClass(opts.iconCls).appendTo(_225);
}
var tool=$("<div class=\"panel-tool\"></div>").appendTo(_225);
tool.bind("click",function(e){
e.stopPropagation();
});
if(opts.tools){
if($.isArray(opts.tools)){
$.map(opts.tools,function(t){
_227(tool,t.iconCls,eval(t.handler));
});
}else{
$(opts.tools).children().each(function(){
$(this).addClass($(this).attr("iconCls")).addClass("panel-tool-a").appendTo(tool);
});
}
}
if(opts.collapsible){
_227(tool,"panel-tool-collapse",function(){
if(opts.collapsed==true){
_245(_21e,true);
}else{
_238(_21e,true);
}
});
}
if(opts.minimizable){
_227(tool,"panel-tool-min",function(){
_24b(_21e);
});
}
if(opts.maximizable){
_227(tool,"panel-tool-max",function(){
if(opts.maximized==true){
_24e(_21e);
}else{
_237(_21e);
}
});
}
if(opts.closable){
_227(tool,"panel-tool-close",function(){
_239(_21e);
});
}
}
_220.children("div.panel-body").removeClass("panel-body-noheader");
}
};
function _227(c,icon,_228){
var a=$("<a href=\"javascript:void(0)\"></a>").addClass(icon).appendTo(c);
a.bind("click",_228);
};
function _222(){
if(opts.footer){
$(opts.footer).addClass("panel-footer").appendTo(_220);
$(_21e).addClass("panel-body-nobottom");
}else{
_220.children(".panel-footer").remove();
$(_21e).removeClass("panel-body-nobottom");
}
};
};
function _229(_22a,_22b){
var _22c=$.data(_22a,"panel");
var opts=_22c.options;
if(_22d){
opts.queryParams=_22b;
}
if(!opts.href){
return;
}
if(!_22c.isLoaded||!opts.cache){
var _22d=$.extend({},opts.queryParams);
if(opts.onBeforeLoad.call(_22a,_22d)==false){
return;
}
_22c.isLoaded=false;
$(_22a).panel("clear");
if(opts.loadingMessage){
$(_22a).html($("<div class=\"panel-loading\"></div>").html(opts.loadingMessage));
}
opts.loader.call(_22a,_22d,function(data){
var _22e=opts.extractor.call(_22a,data);
$(_22a).html(_22e);
$.parser.parse($(_22a));
opts.onLoad.apply(_22a,arguments);
_22c.isLoaded=true;
},function(){
opts.onLoadError.apply(_22a,arguments);
});
}
};
function _22f(_230){
var t=$(_230);
t.find(".combo-f").each(function(){
$(this).combo("destroy");
});
t.find(".m-btn").each(function(){
$(this).menubutton("destroy");
});
t.find(".s-btn").each(function(){
$(this).splitbutton("destroy");
});
t.find(".tooltip-f").each(function(){
$(this).tooltip("destroy");
});
t.children("div").each(function(){
$(this)._size("unfit");
});
t.empty();
};
function _231(_232){
$(_232).panel("doLayout",true);
};
function _233(_234,_235){
var opts=$.data(_234,"panel").options;
var _236=$.data(_234,"panel").panel;
if(_235!=true){
if(opts.onBeforeOpen.call(_234)==false){
return;
}
}
_236.stop(true,true);
if($.isFunction(opts.openAnimation)){
opts.openAnimation.call(_234,cb);
}else{
switch(opts.openAnimation){
case "slide":
_236.slideDown(opts.openDuration,cb);
break;
case "fade":
_236.fadeIn(opts.openDuration,cb);
break;
case "show":
_236.show(opts.openDuration,cb);
break;
default:
_236.show();
cb();
}
}
function cb(){
opts.closed=false;
opts.minimized=false;
var tool=_236.children(".panel-header").find("a.panel-tool-restore");
if(tool.length){
opts.maximized=true;
}
opts.onOpen.call(_234);
if(opts.maximized==true){
opts.maximized=false;
_237(_234);
}
if(opts.collapsed==true){
opts.collapsed=false;
_238(_234);
}
if(!opts.collapsed){
_229(_234);
_231(_234);
}
};
};
function _239(_23a,_23b){
var opts=$.data(_23a,"panel").options;
var _23c=$.data(_23a,"panel").panel;
if(_23b!=true){
if(opts.onBeforeClose.call(_23a)==false){
return;
}
}
_23c.stop(true,true);
_23c._size("unfit");
if($.isFunction(opts.closeAnimation)){
opts.closeAnimation.call(_23a,cb);
}else{
switch(opts.closeAnimation){
case "slide":
_23c.slideUp(opts.closeDuration,cb);
break;
case "fade":
_23c.fadeOut(opts.closeDuration,cb);
break;
case "hide":
_23c.hide(opts.closeDuration,cb);
break;
default:
_23c.hide();
cb();
}
}
function cb(){
opts.closed=true;
opts.onClose.call(_23a);
};
};
function _23d(_23e,_23f){
var _240=$.data(_23e,"panel");
var opts=_240.options;
var _241=_240.panel;
if(_23f!=true){
if(opts.onBeforeDestroy.call(_23e)==false){
return;
}
}
$(_23e).panel("clear").panel("clear","footer");
_20b(_241);
opts.onDestroy.call(_23e);
};
function _238(_242,_243){
var opts=$.data(_242,"panel").options;
var _244=$.data(_242,"panel").panel;
var body=_244.children(".panel-body");
var tool=_244.children(".panel-header").find("a.panel-tool-collapse");
if(opts.collapsed==true){
return;
}
body.stop(true,true);
if(opts.onBeforeCollapse.call(_242)==false){
return;
}
tool.addClass("panel-tool-expand");
if(_243==true){
body.slideUp("normal",function(){
opts.collapsed=true;
opts.onCollapse.call(_242);
});
}else{
body.hide();
opts.collapsed=true;
opts.onCollapse.call(_242);
}
};
function _245(_246,_247){
var opts=$.data(_246,"panel").options;
var _248=$.data(_246,"panel").panel;
var body=_248.children(".panel-body");
var tool=_248.children(".panel-header").find("a.panel-tool-collapse");
if(opts.collapsed==false){
return;
}
body.stop(true,true);
if(opts.onBeforeExpand.call(_246)==false){
return;
}
tool.removeClass("panel-tool-expand");
if(_247==true){
body.slideDown("normal",function(){
opts.collapsed=false;
opts.onExpand.call(_246);
_229(_246);
_231(_246);
});
}else{
body.show();
opts.collapsed=false;
opts.onExpand.call(_246);
_229(_246);
_231(_246);
}
};
function _237(_249){
var opts=$.data(_249,"panel").options;
var _24a=$.data(_249,"panel").panel;
var tool=_24a.children(".panel-header").find("a.panel-tool-max");
if(opts.maximized==true){
return;
}
tool.addClass("panel-tool-restore");
if(!$.data(_249,"panel").original){
$.data(_249,"panel").original={width:opts.width,height:opts.height,left:opts.left,top:opts.top,fit:opts.fit};
}
opts.left=0;
opts.top=0;
opts.fit=true;
_20c(_249);
opts.minimized=false;
opts.maximized=true;
opts.onMaximize.call(_249);
};
function _24b(_24c){
var opts=$.data(_24c,"panel").options;
var _24d=$.data(_24c,"panel").panel;
_24d._size("unfit");
_24d.hide();
opts.minimized=true;
opts.maximized=false;
opts.onMinimize.call(_24c);
};
function _24e(_24f){
var opts=$.data(_24f,"panel").options;
var _250=$.data(_24f,"panel").panel;
var tool=_250.children(".panel-header").find("a.panel-tool-max");
if(opts.maximized==false){
return;
}
_250.show();
tool.removeClass("panel-tool-restore");
$.extend(opts,$.data(_24f,"panel").original);
_20c(_24f);
opts.minimized=false;
opts.maximized=false;
$.data(_24f,"panel").original=null;
opts.onRestore.call(_24f);
};
function _251(_252,_253){
$.data(_252,"panel").options.title=_253;
$(_252).panel("header").find("div.panel-title").html(_253);
};
var _254=null;
$(window).unbind(".panel").bind("resize.panel",function(){
if(_254){
clearTimeout(_254);
}
_254=setTimeout(function(){
var _255=$("body.layout");
if(_255.length){
_255.layout("resize");
$("body").children(".easyui-fluid:visible").each(function(){
$(this).triggerHandler("_resize");
});
}else{
$("body").panel("doLayout");
}
_254=null;
},100);
});
$.fn.panel=function(_256,_257){
if(typeof _256=="string"){
return $.fn.panel.methods[_256](this,_257);
}
_256=_256||{};
return this.each(function(){
var _258=$.data(this,"panel");
var opts;
if(_258){
opts=$.extend(_258.options,_256);
_258.isLoaded=false;
}else{
opts=$.extend({},$.fn.panel.defaults,$.fn.panel.parseOptions(this),_256);
$(this).attr("title","");
_258=$.data(this,"panel",{options:opts,panel:_219(this),isLoaded:false});
}
_21d(this);
if(opts.doSize==true){
_258.panel.css("display","block");
_20c(this);
}
if(opts.closed==true||opts.minimized==true){
_258.panel.hide();
}else{
_233(this);
}
});
};
$.fn.panel.methods={options:function(jq){
return $.data(jq[0],"panel").options;
},panel:function(jq){
return $.data(jq[0],"panel").panel;
},header:function(jq){
return $.data(jq[0],"panel").panel.children(".panel-header");
},footer:function(jq){
return jq.panel("panel").children(".panel-footer");
},body:function(jq){
return $.data(jq[0],"panel").panel.children(".panel-body");
},setTitle:function(jq,_259){
return jq.each(function(){
_251(this,_259);
});
},open:function(jq,_25a){
return jq.each(function(){
_233(this,_25a);
});
},close:function(jq,_25b){
return jq.each(function(){
_239(this,_25b);
});
},destroy:function(jq,_25c){
return jq.each(function(){
_23d(this,_25c);
});
},clear:function(jq,type){
return jq.each(function(){
_22f(type=="footer"?$(this).panel("footer"):this);
});
},refresh:function(jq,href){
return jq.each(function(){
var _25d=$.data(this,"panel");
_25d.isLoaded=false;
if(href){
if(typeof href=="string"){
_25d.options.href=href;
}else{
_25d.options.queryParams=href;
}
}
_229(this);
});
},resize:function(jq,_25e){
return jq.each(function(){
_20c(this,_25e);
});
},doLayout:function(jq,all){
return jq.each(function(){
_25f(this,"body");
_25f($(this).siblings(".panel-footer")[0],"footer");
function _25f(_260,type){
if(!_260){
return;
}
var _261=_260==$("body")[0];
var s=$(_260).find("div.panel:visible,div.accordion:visible,div.tabs-container:visible,div.layout:visible,.easyui-fluid:visible").filter(function(_262,el){
var p=$(el).parents(".panel-"+type+":first");
return _261?p.length==0:p[0]==_260;
});
s.each(function(){
$(this).triggerHandler("_resize",[all||false]);
});
};
});
},move:function(jq,_263){
return jq.each(function(){
_215(this,_263);
});
},maximize:function(jq){
return jq.each(function(){
_237(this);
});
},minimize:function(jq){
return jq.each(function(){
_24b(this);
});
},restore:function(jq){
return jq.each(function(){
_24e(this);
});
},collapse:function(jq,_264){
return jq.each(function(){
_238(this,_264);
});
},expand:function(jq,_265){
return jq.each(function(){
_245(this,_265);
});
}};
$.fn.panel.parseOptions=function(_266){
var t=$(_266);
var hh=t.children(".panel-header,header");
var ff=t.children(".panel-footer,footer");
return $.extend({},$.parser.parseOptions(_266,["id","width","height","left","top","title","iconCls","cls","headerCls","bodyCls","tools","href","method","header","footer",{cache:"boolean",fit:"boolean",border:"boolean",noheader:"boolean"},{collapsible:"boolean",minimizable:"boolean",maximizable:"boolean"},{closable:"boolean",collapsed:"boolean",minimized:"boolean",maximized:"boolean",closed:"boolean"},"openAnimation","closeAnimation",{openDuration:"number",closeDuration:"number"},]),{loadingMessage:(t.attr("loadingMessage")!=undefined?t.attr("loadingMessage"):undefined),header:(hh.length?hh.removeClass("panel-header"):undefined),footer:(ff.length?ff.removeClass("panel-footer"):undefined)});
};
$.fn.panel.defaults={id:null,title:null,iconCls:null,width:"auto",height:"auto",left:null,top:null,cls:null,headerCls:null,bodyCls:null,style:{},href:null,cache:true,fit:false,border:true,doSize:true,noheader:false,content:null,collapsible:false,minimizable:false,maximizable:false,closable:false,collapsed:false,minimized:false,maximized:false,closed:false,openAnimation:false,openDuration:400,closeAnimation:false,closeDuration:400,tools:null,footer:null,header:null,queryParams:{},method:"get",href:null,loadingMessage:"Loading...",loader:function(_267,_268,_269){
var opts=$(this).panel("options");
if(!opts.href){
return false;
}
$.ajax({type:opts.method,url:opts.href,cache:false,data:_267,dataType:"html",success:function(data){
_268(data);
},error:function(){
_269.apply(this,arguments);
}});
},extractor:function(data){
var _26a=/<body[^>]*>((.|[\n\r])*)<\/body>/im;
var _26b=_26a.exec(data);
if(_26b){
return _26b[1];
}else{
return data;
}
},onBeforeLoad:function(_26c){
},onLoad:function(){
},onLoadError:function(){
},onBeforeOpen:function(){
},onOpen:function(){
},onBeforeClose:function(){
},onClose:function(){
},onBeforeDestroy:function(){
},onDestroy:function(){
},onResize:function(_26d,_26e){
},onMove:function(left,top){
},onMaximize:function(){
},onRestore:function(){
},onMinimize:function(){
},onBeforeCollapse:function(){
},onBeforeExpand:function(){
},onCollapse:function(){
},onExpand:function(){
}};
})(jQuery);
(function($){
function _26f(_270,_271){
var _272=$.data(_270,"window");
if(_271){
if(_271.left!=null){
_272.options.left=_271.left;
}
if(_271.top!=null){
_272.options.top=_271.top;
}
}
$(_270).panel("move",_272.options);
if(_272.shadow){
_272.shadow.css({left:_272.options.left,top:_272.options.top});
}
};
function _273(_274,_275){
var opts=$.data(_274,"window").options;
var pp=$(_274).window("panel");
var _276=pp._outerWidth();
if(opts.inline){
var _277=pp.parent();
opts.left=Math.ceil((_277.width()-_276)/2+_277.scrollLeft());
}else{
opts.left=Math.ceil(($(window)._outerWidth()-_276)/2+$(document).scrollLeft());
}
if(_275){
_26f(_274);
}
};
function _278(_279,_27a){
var opts=$.data(_279,"window").options;
var pp=$(_279).window("panel");
var _27b=pp._outerHeight();
if(opts.inline){
var _27c=pp.parent();
opts.top=Math.ceil((_27c.height()-_27b)/2+_27c.scrollTop());
}else{
opts.top=Math.ceil(($(window)._outerHeight()-_27b)/2+$(document).scrollTop());
}
if(_27a){
_26f(_279);
}
};
function _27d(_27e){
var _27f=$.data(_27e,"window");
var opts=_27f.options;
var win=$(_27e).panel($.extend({},_27f.options,{border:false,doSize:true,closed:true,cls:"window",headerCls:"window-header",bodyCls:"window-body "+(opts.noheader?"window-body-noheader":""),onBeforeDestroy:function(){
if(opts.onBeforeDestroy.call(_27e)==false){
return false;
}
if(_27f.shadow){
_27f.shadow.remove();
}
if(_27f.mask){
_27f.mask.remove();
}
},onClose:function(){
if(_27f.shadow){
_27f.shadow.hide();
}
if(_27f.mask){
_27f.mask.hide();
}
opts.onClose.call(_27e);
},onOpen:function(){
if(_27f.mask){
_27f.mask.css($.extend({display:"block",zIndex:$.fn.window.defaults.zIndex++},$.fn.window.getMaskSize(_27e)));
}
if(_27f.shadow){
_27f.shadow.css({display:"block",zIndex:$.fn.window.defaults.zIndex++,left:opts.left,top:opts.top,width:_27f.window._outerWidth(),height:_27f.window._outerHeight()});
}
_27f.window.css("z-index",$.fn.window.defaults.zIndex++);
opts.onOpen.call(_27e);
},onResize:function(_280,_281){
var _282=$(this).panel("options");
$.extend(opts,{width:_282.width,height:_282.height,left:_282.left,top:_282.top});
if(_27f.shadow){
_27f.shadow.css({left:opts.left,top:opts.top,width:_27f.window._outerWidth(),height:_27f.window._outerHeight()});
}
opts.onResize.call(_27e,_280,_281);
},onMinimize:function(){
if(_27f.shadow){
_27f.shadow.hide();
}
if(_27f.mask){
_27f.mask.hide();
}
_27f.options.onMinimize.call(_27e);
},onBeforeCollapse:function(){
if(opts.onBeforeCollapse.call(_27e)==false){
return false;
}
if(_27f.shadow){
_27f.shadow.hide();
}
},onExpand:function(){
if(_27f.shadow){
_27f.shadow.show();
}
opts.onExpand.call(_27e);
}}));
_27f.window=win.panel("panel");
if(_27f.mask){
_27f.mask.remove();
}
if(opts.modal==true){
_27f.mask=$("<div class=\"window-mask\" style=\"display:none\"></div>").insertAfter(_27f.window);
}
if(_27f.shadow){
_27f.shadow.remove();
}
if(opts.shadow==true){
_27f.shadow=$("<div class=\"window-shadow\" style=\"display:none\"></div>").insertAfter(_27f.window);
}
if(opts.left==null){
_273(_27e);
}
if(opts.top==null){
_278(_27e);
}
_26f(_27e);
if(!opts.closed){
win.window("open");
}
};
function _283(_284){
var _285=$.data(_284,"window");
_285.window.draggable({handle:">div.panel-header>div.panel-title",disabled:_285.options.draggable==false,onStartDrag:function(e){
if(_285.mask){
_285.mask.css("z-index",$.fn.window.defaults.zIndex++);
}
if(_285.shadow){
_285.shadow.css("z-index",$.fn.window.defaults.zIndex++);
}
_285.window.css("z-index",$.fn.window.defaults.zIndex++);
if(!_285.proxy){
_285.proxy=$("<div class=\"window-proxy\"></div>").insertAfter(_285.window);
}
_285.proxy.css({display:"none",zIndex:$.fn.window.defaults.zIndex++,left:e.data.left,top:e.data.top});
_285.proxy._outerWidth(_285.window._outerWidth());
_285.proxy._outerHeight(_285.window._outerHeight());
setTimeout(function(){
if(_285.proxy){
_285.proxy.show();
}
},500);
},onDrag:function(e){
_285.proxy.css({display:"block",left:e.data.left,top:e.data.top});
return false;
},onStopDrag:function(e){
_285.options.left=e.data.left;
_285.options.top=e.data.top;
$(_284).window("move");
_285.proxy.remove();
_285.proxy=null;
}});
_285.window.resizable({disabled:_285.options.resizable==false,onStartResize:function(e){
if(_285.pmask){
_285.pmask.remove();
}
_285.pmask=$("<div class=\"window-proxy-mask\"></div>").insertAfter(_285.window);
_285.pmask.css({zIndex:$.fn.window.defaults.zIndex++,left:e.data.left,top:e.data.top,width:_285.window._outerWidth(),height:_285.window._outerHeight()});
if(_285.proxy){
_285.proxy.remove();
}
_285.proxy=$("<div class=\"window-proxy\"></div>").insertAfter(_285.window);
_285.proxy.css({zIndex:$.fn.window.defaults.zIndex++,left:e.data.left,top:e.data.top});
_285.proxy._outerWidth(e.data.width)._outerHeight(e.data.height);
},onResize:function(e){
_285.proxy.css({left:e.data.left,top:e.data.top});
_285.proxy._outerWidth(e.data.width);
_285.proxy._outerHeight(e.data.height);
return false;
},onStopResize:function(e){
$(_284).window("resize",e.data);
_285.pmask.remove();
_285.pmask=null;
_285.proxy.remove();
_285.proxy=null;
}});
};
$(window).resize(function(){
$("body>div.window-mask").css({width:$(window)._outerWidth(),height:$(window)._outerHeight()});
setTimeout(function(){
$("body>div.window-mask").css($.fn.window.getMaskSize());
},50);
});
$.fn.window=function(_286,_287){
if(typeof _286=="string"){
var _288=$.fn.window.methods[_286];
if(_288){
return _288(this,_287);
}else{
return this.panel(_286,_287);
}
}
_286=_286||{};
return this.each(function(){
var _289=$.data(this,"window");
if(_289){
$.extend(_289.options,_286);
}else{
_289=$.data(this,"window",{options:$.extend({},$.fn.window.defaults,$.fn.window.parseOptions(this),_286)});
if(!_289.options.inline){
document.body.appendChild(this);
}
}
_27d(this);
_283(this);
});
};
$.fn.window.methods={options:function(jq){
var _28a=jq.panel("options");
var _28b=$.data(jq[0],"window").options;
return $.extend(_28b,{closed:_28a.closed,collapsed:_28a.collapsed,minimized:_28a.minimized,maximized:_28a.maximized});
},window:function(jq){
return $.data(jq[0],"window").window;
},move:function(jq,_28c){
return jq.each(function(){
_26f(this,_28c);
});
},hcenter:function(jq){
return jq.each(function(){
_273(this,true);
});
},vcenter:function(jq){
return jq.each(function(){
_278(this,true);
});
},center:function(jq){
return jq.each(function(){
_273(this);
_278(this);
_26f(this);
});
}};
$.fn.window.getMaskSize=function(_28d){
var _28e=$(_28d).data("window");
var _28f=(_28e&&_28e.options.inline);
return {width:(_28f?"100%":$(document).width()),height:(_28f?"100%":$(document).height())};
};
$.fn.window.parseOptions=function(_290){
return $.extend({},$.fn.panel.parseOptions(_290),$.parser.parseOptions(_290,[{draggable:"boolean",resizable:"boolean",shadow:"boolean",modal:"boolean",inline:"boolean"}]));
};
$.fn.window.defaults=$.extend({},$.fn.panel.defaults,{zIndex:9000,draggable:true,resizable:true,shadow:true,modal:false,inline:false,title:"New Window",collapsible:true,minimizable:true,maximizable:true,closable:true,closed:false});
})(jQuery);
(function($){
function _291(_292){
var opts=$.data(_292,"dialog").options;
opts.inited=false;
$(_292).window($.extend({},opts,{onResize:function(w,h){
if(opts.inited){
_297(this);
opts.onResize.call(this,w,h);
}
}}));
var win=$(_292).window("window");
if(opts.toolbar){
if($.isArray(opts.toolbar)){
$(_292).siblings("div.dialog-toolbar").remove();
var _293=$("<div class=\"dialog-toolbar\"><table cellspacing=\"0\" cellpadding=\"0\"><tr></tr></table></div>").appendTo(win);
var tr=_293.find("tr");
for(var i=0;i<opts.toolbar.length;i++){
var btn=opts.toolbar[i];
if(btn=="-"){
$("<td><div class=\"dialog-tool-separator\"></div></td>").appendTo(tr);
}else{
var td=$("<td></td>").appendTo(tr);
var tool=$("<a href=\"javascript:void(0)\"></a>").appendTo(td);
tool[0].onclick=eval(btn.handler||function(){
});
tool.linkbutton($.extend({},btn,{plain:true}));
}
}
}else{
$(opts.toolbar).addClass("dialog-toolbar").appendTo(win);
$(opts.toolbar).show();
}
}else{
$(_292).siblings("div.dialog-toolbar").remove();
}
if(opts.buttons){
if($.isArray(opts.buttons)){
$(_292).siblings("div.dialog-button").remove();
var _294=$("<div class=\"dialog-button\"></div>").appendTo(win);
for(var i=0;i<opts.buttons.length;i++){
var p=opts.buttons[i];
var _295=$("<a href=\"javascript:void(0)\"></a>").appendTo(_294);
if(p.handler){
_295[0].onclick=p.handler;
}
_295.linkbutton(p);
}
}else{
$(opts.buttons).addClass("dialog-button").appendTo(win);
$(opts.buttons).show();
}
}else{
$(_292).siblings("div.dialog-button").remove();
}
opts.inited=true;
var _296=opts.closed;
win.show();
$(_292).window("resize");
if(_296){
win.hide();
}
};
function _297(_298,_299){
var t=$(_298);
var opts=t.dialog("options");
var _29a=opts.noheader;
var tb=t.siblings(".dialog-toolbar");
var bb=t.siblings(".dialog-button");
tb.insertBefore(_298).css({position:"relative",borderTopWidth:(_29a?1:0),top:(_29a?tb.length:0)});
bb.insertAfter(_298).css({position:"relative",top:-1});
tb.add(bb)._outerWidth(t._outerWidth()).find(".easyui-fluid:visible").each(function(){
$(this).triggerHandler("_resize");
});
if(!isNaN(parseInt(opts.height))){
t._outerHeight(t._outerHeight()-tb._outerHeight()-bb._outerHeight());
}
var _29b=$.data(_298,"window").shadow;
if(_29b){
var cc=t.panel("panel");
_29b.css({width:cc._outerWidth(),height:cc._outerHeight()});
}
};
$.fn.dialog=function(_29c,_29d){
if(typeof _29c=="string"){
var _29e=$.fn.dialog.methods[_29c];
if(_29e){
return _29e(this,_29d);
}else{
return this.window(_29c,_29d);
}
}
_29c=_29c||{};
return this.each(function(){
var _29f=$.data(this,"dialog");
if(_29f){
$.extend(_29f.options,_29c);
}else{
$.data(this,"dialog",{options:$.extend({},$.fn.dialog.defaults,$.fn.dialog.parseOptions(this),_29c)});
}
_291(this);
});
};
$.fn.dialog.methods={options:function(jq){
var _2a0=$.data(jq[0],"dialog").options;
var _2a1=jq.panel("options");
$.extend(_2a0,{width:_2a1.width,height:_2a1.height,left:_2a1.left,top:_2a1.top,closed:_2a1.closed,collapsed:_2a1.collapsed,minimized:_2a1.minimized,maximized:_2a1.maximized});
return _2a0;
},dialog:function(jq){
return jq.window("window");
}};
$.fn.dialog.parseOptions=function(_2a2){
var t=$(_2a2);
return $.extend({},$.fn.window.parseOptions(_2a2),$.parser.parseOptions(_2a2,["toolbar","buttons"]),{toolbar:(t.children(".dialog-toolbar").length?t.children(".dialog-toolbar").removeClass("dialog-toolbar"):undefined),buttons:(t.children(".dialog-button").length?t.children(".dialog-button").removeClass("dialog-button"):undefined)});
};
$.fn.dialog.defaults=$.extend({},$.fn.window.defaults,{title:"New Dialog",collapsible:false,minimizable:false,maximizable:false,resizable:false,toolbar:null,buttons:null});
})(jQuery);
(function($){
function _2a3(){
$(document).unbind(".messager").bind("keydown.messager",function(e){
if(e.keyCode==27){
$("body").children("div.messager-window").children("div.messager-body").each(function(){
$(this).window("close");
});
}else{
if(e.keyCode==9){
var win=$("body").children("div.messager-window").children("div.messager-body");
if(!win.length){
return;
}
var _2a4=win.find(".messager-input,.messager-button .l-btn");
for(var i=0;i<_2a4.length;i++){
if($(_2a4[i]).is(":focus")){
$(_2a4[i>=_2a4.length-1?0:i+1]).focus();
return false;
}
}
}
}
});
};
function _2a5(){
$(document).unbind(".messager");
};
function _2a6(_2a7){
var opts=$.extend({},$.messager.defaults,{modal:false,shadow:false,draggable:false,resizable:false,closed:true,style:{left:"",top:"",right:0,zIndex:$.fn.window.defaults.zIndex++,bottom:-document.body.scrollTop-document.documentElement.scrollTop},title:"",width:250,height:100,showType:"slide",showSpeed:600,msg:"",timeout:4000},_2a7);
var win=$("<div class=\"messager-body\"></div>").html(opts.msg).appendTo("body");
win.window($.extend({},opts,{openAnimation:(opts.showType),closeAnimation:(opts.showType=="show"?"hide":opts.showType),openDuration:opts.showSpeed,closeDuration:opts.showSpeed,onOpen:function(){
win.window("window").hover(function(){
if(opts.timer){
clearTimeout(opts.timer);
}
},function(){
_2a8();
});
_2a8();
function _2a8(){
if(opts.timeout>0){
opts.timer=setTimeout(function(){
if(win.length&&win.data("window")){
win.window("close");
}
},opts.timeout);
}
};
if(_2a7.onOpen){
_2a7.onOpen.call(this);
}else{
opts.onOpen.call(this);
}
},onClose:function(){
if(opts.timer){
clearTimeout(opts.timer);
}
if(_2a7.onClose){
_2a7.onClose.call(this);
}else{
opts.onClose.call(this);
}
win.window("destroy");
}}));
win.window("window").css(opts.style);
win.window("open");
return win;
};
function _2a9(_2aa){
_2a3();
var win=$("<div class=\"messager-body\"></div>").appendTo("body");
win.window($.extend({},_2aa,{doSize:false,noheader:(_2aa.title?false:true),onClose:function(){
_2a5();
if(_2aa.onClose){
_2aa.onClose.call(this);
}
setTimeout(function(){
win.window("destroy");
},100);
}}));
if(_2aa.buttons&&_2aa.buttons.length){
var tb=$("<div class=\"messager-button\"></div>").appendTo(win);
$.map(_2aa.buttons,function(btn){
$("<a href=\"javascript:void(0)\" style=\"margin-left:10px\"></a>").appendTo(tb).linkbutton(btn);
});
}
win.window("window").addClass("messager-window");
win.window("resize");
win.children("div.messager-button").children("a:first").focus();
return win;
};
$.messager={show:function(_2ab){
return _2a6(_2ab);
},alert:function(_2ac,msg,icon,fn){
var opts=typeof _2ac=="object"?_2ac:{title:_2ac,msg:msg,icon:icon,fn:fn};
var cls=opts.icon?"messager-icon messager-"+opts.icon:"";
opts=$.extend({},$.messager.defaults,{content:"<div class=\""+cls+"\"></div>"+"<div>"+opts.msg+"</div>"+"<div style=\"clear:both;\"/>",buttons:[{text:$.messager.defaults.ok,onClick:function(){
win.window("close");
opts.fn();
}}]},opts);
var win=_2a9(opts);
return win;
},confirm:function(_2ad,msg,fn){
var opts=typeof _2ad=="object"?_2ad:{title:_2ad,msg:msg,fn:fn};
opts=$.extend({},$.messager.defaults,{content:"<div class=\"messager-icon messager-question\"></div>"+"<div>"+opts.msg+"</div>"+"<div style=\"clear:both;\"/>",buttons:[{text:$.messager.defaults.ok,onClick:function(){
win.window("close");
opts.fn(true);
}},{text:$.messager.defaults.cancel,onClick:function(){
win.window("close");
opts.fn(false);
}}]},opts);
var win=_2a9(opts);
return win;
},prompt:function(_2ae,msg,fn){
var opts=typeof _2ae=="object"?_2ae:{title:_2ae,msg:msg,fn:fn};
opts=$.extend({},$.messager.defaults,{content:"<div class=\"messager-icon messager-question\"></div>"+"<div>"+opts.msg+"</div>"+"<br/>"+"<div style=\"clear:both;\"/>"+"<div><input class=\"messager-input\" type=\"text\"/></div>",buttons:[{text:$.messager.defaults.ok,onClick:function(){
win.window("close");
opts.fn(win.find(".messager-input").val());
}},{text:$.messager.defaults.cancel,onClick:function(){
win.window("close");
opts.fn();
}}]},opts);
var win=_2a9(opts);
win.find("input.messager-input").focus();
return win;
},progress:function(_2af){
var _2b0={bar:function(){
return $("body>div.messager-window").find("div.messager-p-bar");
},close:function(){
var win=$("body>div.messager-window>div.messager-body:has(div.messager-progress)");
if(win.length){
win.window("close");
}
}};
if(typeof _2af=="string"){
var _2b1=_2b0[_2af];
return _2b1();
}
var opts=$.extend({},{title:"",content:undefined,msg:"",text:undefined,interval:300},_2af||{});
var win=_2a9($.extend({},$.messager.defaults,{content:"<div class=\"messager-progress\"><div class=\"messager-p-msg\">"+opts.msg+"</div><div class=\"messager-p-bar\"></div></div>",closable:false,doSize:false},opts,{onClose:function(){
if(this.timer){
clearInterval(this.timer);
}
if(_2af.onClose){
_2af.onClose.call(this);
}else{
$.messager.defaults.onClose.call(this);
}
}}));
var bar=win.find("div.messager-p-bar");
bar.progressbar({text:opts.text});
win.window("resize");
if(opts.interval){
win[0].timer=setInterval(function(){
var v=bar.progressbar("getValue");
v+=10;
if(v>100){
v=0;
}
bar.progressbar("setValue",v);
},opts.interval);
}
return win;
}};
$.messager.defaults=$.extend({},$.fn.window.defaults,{ok:"Ok",cancel:"Cancel",width:300,height:"auto",modal:true,collapsible:false,minimizable:false,maximizable:false,resizable:false,fn:function(){
}});
})(jQuery);
(function($){
function _2b2(_2b3,_2b4){
var _2b5=$.data(_2b3,"accordion");
var opts=_2b5.options;
var _2b6=_2b5.panels;
var cc=$(_2b3);
if(_2b4){
$.extend(opts,{width:_2b4.width,height:_2b4.height});
}
cc._size(opts);
var _2b7=0;
var _2b8="auto";
var _2b9=cc.find(">.panel>.accordion-header");
if(_2b9.length){
_2b7=$(_2b9[0]).css("height","")._outerHeight();
}
if(!isNaN(parseInt(opts.height))){
_2b8=cc.height()-_2b7*_2b9.length;
}
_2ba(true,_2b8-_2ba(false)+1);
function _2ba(_2bb,_2bc){
var _2bd=0;
for(var i=0;i<_2b6.length;i++){
var p=_2b6[i];
var h=p.panel("header")._outerHeight(_2b7);
if(p.panel("options").collapsible==_2bb){
var _2be=isNaN(_2bc)?undefined:(_2bc+_2b7*h.length);
p.panel("resize",{width:cc.width(),height:(_2bb?_2be:undefined)});
_2bd+=p.panel("panel").outerHeight()-_2b7*h.length;
}
}
return _2bd;
};
};
function _2bf(_2c0,_2c1,_2c2,all){
var _2c3=$.data(_2c0,"accordion").panels;
var pp=[];
for(var i=0;i<_2c3.length;i++){
var p=_2c3[i];
if(_2c1){
if(p.panel("options")[_2c1]==_2c2){
pp.push(p);
}
}else{
if(p[0]==$(_2c2)[0]){
return i;
}
}
}
if(_2c1){
return all?pp:(pp.length?pp[0]:null);
}else{
return -1;
}
};
function _2c4(_2c5){
return _2bf(_2c5,"collapsed",false,true);
};
function _2c6(_2c7){
var pp=_2c4(_2c7);
return pp.length?pp[0]:null;
};
function _2c8(_2c9,_2ca){
return _2bf(_2c9,null,_2ca);
};
function _2cb(_2cc,_2cd){
var _2ce=$.data(_2cc,"accordion").panels;
if(typeof _2cd=="number"){
if(_2cd<0||_2cd>=_2ce.length){
return null;
}else{
return _2ce[_2cd];
}
}
return _2bf(_2cc,"title",_2cd);
};
function _2cf(_2d0){
var opts=$.data(_2d0,"accordion").options;
var cc=$(_2d0);
if(opts.border){
cc.removeClass("accordion-noborder");
}else{
cc.addClass("accordion-noborder");
}
};
function init(_2d1){
var _2d2=$.data(_2d1,"accordion");
var cc=$(_2d1);
cc.addClass("accordion");
_2d2.panels=[];
cc.children("div").each(function(){
var opts=$.extend({},$.parser.parseOptions(this),{selected:($(this).attr("selected")?true:undefined)});
var pp=$(this);
_2d2.panels.push(pp);
_2d4(_2d1,pp,opts);
});
cc.bind("_resize",function(e,_2d3){
if($(this).hasClass("easyui-fluid")||_2d3){
_2b2(_2d1);
}
return false;
});
};
function _2d4(_2d5,pp,_2d6){
var opts=$.data(_2d5,"accordion").options;
pp.panel($.extend({},{collapsible:true,minimizable:false,maximizable:false,closable:false,doSize:false,collapsed:true,headerCls:"accordion-header",bodyCls:"accordion-body"},_2d6,{onBeforeExpand:function(){
if(_2d6.onBeforeExpand){
if(_2d6.onBeforeExpand.call(this)==false){
return false;
}
}
if(!opts.multiple){
var all=$.grep(_2c4(_2d5),function(p){
return p.panel("options").collapsible;
});
for(var i=0;i<all.length;i++){
_2de(_2d5,_2c8(_2d5,all[i]));
}
}
var _2d7=$(this).panel("header");
_2d7.addClass("accordion-header-selected");
_2d7.find(".accordion-collapse").removeClass("accordion-expand");
},onExpand:function(){
if(_2d6.onExpand){
_2d6.onExpand.call(this);
}
opts.onSelect.call(_2d5,$(this).panel("options").title,_2c8(_2d5,this));
},onBeforeCollapse:function(){
if(_2d6.onBeforeCollapse){
if(_2d6.onBeforeCollapse.call(this)==false){
return false;
}
}
var _2d8=$(this).panel("header");
_2d8.removeClass("accordion-header-selected");
_2d8.find(".accordion-collapse").addClass("accordion-expand");
},onCollapse:function(){
if(_2d6.onCollapse){
_2d6.onCollapse.call(this);
}
opts.onUnselect.call(_2d5,$(this).panel("options").title,_2c8(_2d5,this));
}}));
var _2d9=pp.panel("header");
var tool=_2d9.children("div.panel-tool");
tool.children("a.panel-tool-collapse").hide();
var t=$("<a href=\"javascript:void(0)\"></a>").addClass("accordion-collapse accordion-expand").appendTo(tool);
t.bind("click",function(){
_2da(pp);
return false;
});
pp.panel("options").collapsible?t.show():t.hide();
_2d9.click(function(){
_2da(pp);
return false;
});
function _2da(p){
var _2db=p.panel("options");
if(_2db.collapsible){
var _2dc=_2c8(_2d5,p);
if(_2db.collapsed){
_2dd(_2d5,_2dc);
}else{
_2de(_2d5,_2dc);
}
}
};
};
function _2dd(_2df,_2e0){
var p=_2cb(_2df,_2e0);
if(!p){
return;
}
_2e1(_2df);
var opts=$.data(_2df,"accordion").options;
p.panel("expand",opts.animate);
};
function _2de(_2e2,_2e3){
var p=_2cb(_2e2,_2e3);
if(!p){
return;
}
_2e1(_2e2);
var opts=$.data(_2e2,"accordion").options;
p.panel("collapse",opts.animate);
};
function _2e4(_2e5){
var opts=$.data(_2e5,"accordion").options;
var p=_2bf(_2e5,"selected",true);
if(p){
_2e6(_2c8(_2e5,p));
}else{
_2e6(opts.selected);
}
function _2e6(_2e7){
var _2e8=opts.animate;
opts.animate=false;
_2dd(_2e5,_2e7);
opts.animate=_2e8;
};
};
function _2e1(_2e9){
var _2ea=$.data(_2e9,"accordion").panels;
for(var i=0;i<_2ea.length;i++){
_2ea[i].stop(true,true);
}
};
function add(_2eb,_2ec){
var _2ed=$.data(_2eb,"accordion");
var opts=_2ed.options;
var _2ee=_2ed.panels;
if(_2ec.selected==undefined){
_2ec.selected=true;
}
_2e1(_2eb);
var pp=$("<div></div>").appendTo(_2eb);
_2ee.push(pp);
_2d4(_2eb,pp,_2ec);
_2b2(_2eb);
opts.onAdd.call(_2eb,_2ec.title,_2ee.length-1);
if(_2ec.selected){
_2dd(_2eb,_2ee.length-1);
}
};
function _2ef(_2f0,_2f1){
var _2f2=$.data(_2f0,"accordion");
var opts=_2f2.options;
var _2f3=_2f2.panels;
_2e1(_2f0);
var _2f4=_2cb(_2f0,_2f1);
var _2f5=_2f4.panel("options").title;
var _2f6=_2c8(_2f0,_2f4);
if(!_2f4){
return;
}
if(opts.onBeforeRemove.call(_2f0,_2f5,_2f6)==false){
return;
}
_2f3.splice(_2f6,1);
_2f4.panel("destroy");
if(_2f3.length){
_2b2(_2f0);
var curr=_2c6(_2f0);
if(!curr){
_2dd(_2f0,0);
}
}
opts.onRemove.call(_2f0,_2f5,_2f6);
};
$.fn.accordion=function(_2f7,_2f8){
if(typeof _2f7=="string"){
return $.fn.accordion.methods[_2f7](this,_2f8);
}
_2f7=_2f7||{};
return this.each(function(){
var _2f9=$.data(this,"accordion");
if(_2f9){
$.extend(_2f9.options,_2f7);
}else{
$.data(this,"accordion",{options:$.extend({},$.fn.accordion.defaults,$.fn.accordion.parseOptions(this),_2f7),accordion:$(this).addClass("accordion"),panels:[]});
init(this);
}
_2cf(this);
_2b2(this);
_2e4(this);
});
};
$.fn.accordion.methods={options:function(jq){
return $.data(jq[0],"accordion").options;
},panels:function(jq){
return $.data(jq[0],"accordion").panels;
},resize:function(jq,_2fa){
return jq.each(function(){
_2b2(this,_2fa);
});
},getSelections:function(jq){
return _2c4(jq[0]);
},getSelected:function(jq){
return _2c6(jq[0]);
},getPanel:function(jq,_2fb){
return _2cb(jq[0],_2fb);
},getPanelIndex:function(jq,_2fc){
return _2c8(jq[0],_2fc);
},select:function(jq,_2fd){
return jq.each(function(){
_2dd(this,_2fd);
});
},unselect:function(jq,_2fe){
return jq.each(function(){
_2de(this,_2fe);
});
},add:function(jq,_2ff){
return jq.each(function(){
add(this,_2ff);
});
},remove:function(jq,_300){
return jq.each(function(){
_2ef(this,_300);
});
}};
$.fn.accordion.parseOptions=function(_301){
var t=$(_301);
return $.extend({},$.parser.parseOptions(_301,["width","height",{fit:"boolean",border:"boolean",animate:"boolean",multiple:"boolean",selected:"number"}]));
};
$.fn.accordion.defaults={width:"auto",height:"auto",fit:false,border:true,animate:true,multiple:false,selected:0,onSelect:function(_302,_303){
},onUnselect:function(_304,_305){
},onAdd:function(_306,_307){
},onBeforeRemove:function(_308,_309){
},onRemove:function(_30a,_30b){
}};
})(jQuery);
(function($){
function _30c(c){
var w=0;
$(c).children().each(function(){
w+=$(this).outerWidth(true);
});
return w;
};
function _30d(_30e){
var opts=$.data(_30e,"tabs").options;
if(opts.tabPosition=="left"||opts.tabPosition=="right"||!opts.showHeader){
return;
}
var _30f=$(_30e).children("div.tabs-header");
var tool=_30f.children("div.tabs-tool:not(.tabs-tool-hidden)");
var _310=_30f.children("div.tabs-scroller-left");
var _311=_30f.children("div.tabs-scroller-right");
var wrap=_30f.children("div.tabs-wrap");
var _312=_30f.outerHeight();
if(opts.plain){
_312-=_312-_30f.height();
}
tool._outerHeight(_312);
var _313=_30c(_30f.find("ul.tabs"));
var _314=_30f.width()-tool._outerWidth();
if(_313>_314){
_310.add(_311).show()._outerHeight(_312);
if(opts.toolPosition=="left"){
tool.css({left:_310.outerWidth(),right:""});
wrap.css({marginLeft:_310.outerWidth()+tool._outerWidth(),marginRight:_311._outerWidth(),width:_314-_310.outerWidth()-_311.outerWidth()});
}else{
tool.css({left:"",right:_311.outerWidth()});
wrap.css({marginLeft:_310.outerWidth(),marginRight:_311.outerWidth()+tool._outerWidth(),width:_314-_310.outerWidth()-_311.outerWidth()});
}
}else{
_310.add(_311).hide();
if(opts.toolPosition=="left"){
tool.css({left:0,right:""});
wrap.css({marginLeft:tool._outerWidth(),marginRight:0,width:_314});
}else{
tool.css({left:"",right:0});
wrap.css({marginLeft:0,marginRight:tool._outerWidth(),width:_314});
}
}
};
function _315(_316){
var opts=$.data(_316,"tabs").options;
var _317=$(_316).children("div.tabs-header");
if(opts.tools){
if(typeof opts.tools=="string"){
$(opts.tools).addClass("tabs-tool").appendTo(_317);
$(opts.tools).show();
}else{
_317.children("div.tabs-tool").remove();
var _318=$("<div class=\"tabs-tool\"><table cellspacing=\"0\" cellpadding=\"0\" style=\"height:100%\"><tr></tr></table></div>").appendTo(_317);
var tr=_318.find("tr");
for(var i=0;i<opts.tools.length;i++){
var td=$("<td></td>").appendTo(tr);
var tool=$("<a href=\"javascript:void(0);\"></a>").appendTo(td);
tool[0].onclick=eval(opts.tools[i].handler||function(){
});
tool.linkbutton($.extend({},opts.tools[i],{plain:true}));
}
}
}else{
_317.children("div.tabs-tool").remove();
}
};
function _319(_31a,_31b){
var _31c=$.data(_31a,"tabs");
var opts=_31c.options;
var cc=$(_31a);
if(!opts.doSize){
return;
}
if(_31b){
$.extend(opts,{width:_31b.width,height:_31b.height});
}
cc._size(opts);
var _31d=cc.children("div.tabs-header");
var _31e=cc.children("div.tabs-panels");
var wrap=_31d.find("div.tabs-wrap");
var ul=wrap.find(".tabs");
ul.children("li").removeClass("tabs-first tabs-last");
ul.children("li:first").addClass("tabs-first");
ul.children("li:last").addClass("tabs-last");
if(opts.tabPosition=="left"||opts.tabPosition=="right"){
_31d._outerWidth(opts.showHeader?opts.headerWidth:0);
_31e._outerWidth(cc.width()-_31d.outerWidth());
_31d.add(_31e)._outerHeight(opts.height);
wrap._outerWidth(_31d.width());
ul._outerWidth(wrap.width()).css("height","");
}else{
_31d.children("div.tabs-scroller-left,div.tabs-scroller-right,div.tabs-tool:not(.tabs-tool-hidden)").css("display",opts.showHeader?"block":"none");
_31d._outerWidth(cc.width()).css("height","");
if(opts.showHeader){
_31d.css("background-color","");
wrap.css("height","");
}else{
_31d.css("background-color","transparent");
_31d._outerHeight(0);
wrap._outerHeight(0);
}
ul._outerHeight(opts.tabHeight).css("width","");
ul._outerHeight(ul.outerHeight()-ul.height()-1+opts.tabHeight).css("width","");
_31e._size("height",isNaN(opts.height)?"":(opts.height-_31d.outerHeight()));
_31e._size("width",isNaN(opts.width)?"":opts.width);
}
if(_31c.tabs.length){
var d1=ul.outerWidth(true)-ul.width();
var li=ul.children("li:first");
var d2=li.outerWidth(true)-li.width();
var _31f=_31d.width()-_31d.children(".tabs-tool:not(.tabs-tool-hidden)")._outerWidth();
var _320=Math.floor((_31f-d1-d2*_31c.tabs.length)/_31c.tabs.length);
$.map(_31c.tabs,function(p){
_321(p,(opts.justified&&$.inArray(opts.tabPosition,["top","bottom"])>=0)?_320:undefined);
});
if(opts.justified&&$.inArray(opts.tabPosition,["top","bottom"])>=0){
var _322=_31f-d1-_30c(ul);
_321(_31c.tabs[_31c.tabs.length-1],_320+_322);
}
}
_30d(_31a);
function _321(p,_323){
var _324=p.panel("options");
var p_t=_324.tab.find("a.tabs-inner");
var _323=_323?_323:(parseInt(_324.tabWidth||opts.tabWidth||undefined));
if(_323){
p_t._outerWidth(_323);
}else{
p_t.css("width","");
}
p_t._outerHeight(opts.tabHeight);
p_t.css("lineHeight",p_t.height()+"px");
p_t.find(".easyui-fluid:visible").triggerHandler("_resize");
};
};
function _325(_326){
var opts=$.data(_326,"tabs").options;
var tab=_327(_326);
if(tab){
var _328=$(_326).children("div.tabs-panels");
var _329=opts.width=="auto"?"auto":_328.width();
var _32a=opts.height=="auto"?"auto":_328.height();
tab.panel("resize",{width:_329,height:_32a});
}
};
function _32b(_32c){
var tabs=$.data(_32c,"tabs").tabs;
var cc=$(_32c).addClass("tabs-container");
var _32d=$("<div class=\"tabs-panels\"></div>").insertBefore(cc);
cc.children("div").each(function(){
_32d[0].appendChild(this);
});
cc[0].appendChild(_32d[0]);
$("<div class=\"tabs-header\">"+"<div class=\"tabs-scroller-left\"></div>"+"<div class=\"tabs-scroller-right\"></div>"+"<div class=\"tabs-wrap\">"+"<ul class=\"tabs\"></ul>"+"</div>"+"</div>").prependTo(_32c);
cc.children("div.tabs-panels").children("div").each(function(i){
var opts=$.extend({},$.parser.parseOptions(this),{selected:($(this).attr("selected")?true:undefined)});
_33a(_32c,opts,$(this));
});
cc.children("div.tabs-header").find(".tabs-scroller-left, .tabs-scroller-right").hover(function(){
$(this).addClass("tabs-scroller-over");
},function(){
$(this).removeClass("tabs-scroller-over");
});
cc.bind("_resize",function(e,_32e){
if($(this).hasClass("easyui-fluid")||_32e){
_319(_32c);
_325(_32c);
}
return false;
});
};
function _32f(_330){
var _331=$.data(_330,"tabs");
var opts=_331.options;
$(_330).children("div.tabs-header").unbind().bind("click",function(e){
if($(e.target).hasClass("tabs-scroller-left")){
$(_330).tabs("scrollBy",-opts.scrollIncrement);
}else{
if($(e.target).hasClass("tabs-scroller-right")){
$(_330).tabs("scrollBy",opts.scrollIncrement);
}else{
var li=$(e.target).closest("li");
if(li.hasClass("tabs-disabled")){
return false;
}
var a=$(e.target).closest("a.tabs-close");
if(a.length){
_353(_330,_332(li));
}else{
if(li.length){
var _333=_332(li);
var _334=_331.tabs[_333].panel("options");
if(_334.collapsible){
_334.closed?_34a(_330,_333):_367(_330,_333);
}else{
_34a(_330,_333);
}
}
}
return false;
}
}
}).bind("contextmenu",function(e){
var li=$(e.target).closest("li");
if(li.hasClass("tabs-disabled")){
return;
}
if(li.length){
opts.onContextMenu.call(_330,e,li.find("span.tabs-title").html(),_332(li));
}
});
function _332(li){
var _335=0;
li.parent().children("li").each(function(i){
if(li[0]==this){
_335=i;
return false;
}
});
return _335;
};
};
function _336(_337){
var opts=$.data(_337,"tabs").options;
var _338=$(_337).children("div.tabs-header");
var _339=$(_337).children("div.tabs-panels");
_338.removeClass("tabs-header-top tabs-header-bottom tabs-header-left tabs-header-right");
_339.removeClass("tabs-panels-top tabs-panels-bottom tabs-panels-left tabs-panels-right");
if(opts.tabPosition=="top"){
_338.insertBefore(_339);
}else{
if(opts.tabPosition=="bottom"){
_338.insertAfter(_339);
_338.addClass("tabs-header-bottom");
_339.addClass("tabs-panels-top");
}else{
if(opts.tabPosition=="left"){
_338.addClass("tabs-header-left");
_339.addClass("tabs-panels-right");
}else{
if(opts.tabPosition=="right"){
_338.addClass("tabs-header-right");
_339.addClass("tabs-panels-left");
}
}
}
}
if(opts.plain==true){
_338.addClass("tabs-header-plain");
}else{
_338.removeClass("tabs-header-plain");
}
_338.removeClass("tabs-header-narrow").addClass(opts.narrow?"tabs-header-narrow":"");
var tabs=_338.find(".tabs");
tabs.removeClass("tabs-pill").addClass(opts.pill?"tabs-pill":"");
tabs.removeClass("tabs-narrow").addClass(opts.narrow?"tabs-narrow":"");
tabs.removeClass("tabs-justified").addClass(opts.justified?"tabs-justified":"");
if(opts.border==true){
_338.removeClass("tabs-header-noborder");
_339.removeClass("tabs-panels-noborder");
}else{
_338.addClass("tabs-header-noborder");
_339.addClass("tabs-panels-noborder");
}
opts.doSize=true;
};
function _33a(_33b,_33c,pp){
_33c=_33c||{};
var _33d=$.data(_33b,"tabs");
var tabs=_33d.tabs;
if(_33c.index==undefined||_33c.index>tabs.length){
_33c.index=tabs.length;
}
if(_33c.index<0){
_33c.index=0;
}
var ul=$(_33b).children("div.tabs-header").find("ul.tabs");
var _33e=$(_33b).children("div.tabs-panels");
var tab=$("<li>"+"<a href=\"javascript:void(0)\" class=\"tabs-inner\">"+"<span class=\"tabs-title\"></span>"+"<span class=\"tabs-icon\"></span>"+"</a>"+"</li>");
if(!pp){
pp=$("<div></div>");
}
if(_33c.index>=tabs.length){
tab.appendTo(ul);
pp.appendTo(_33e);
tabs.push(pp);
}else{
tab.insertBefore(ul.children("li:eq("+_33c.index+")"));
pp.insertBefore(_33e.children("div.panel:eq("+_33c.index+")"));
tabs.splice(_33c.index,0,pp);
}
pp.panel($.extend({},_33c,{tab:tab,border:false,noheader:true,closed:true,doSize:false,iconCls:(_33c.icon?_33c.icon:undefined),onLoad:function(){
if(_33c.onLoad){
_33c.onLoad.call(this,arguments);
}
_33d.options.onLoad.call(_33b,$(this));
},onBeforeOpen:function(){
if(_33c.onBeforeOpen){
if(_33c.onBeforeOpen.call(this)==false){
return false;
}
}
var p=$(_33b).tabs("getSelected");
if(p){
if(p[0]!=this){
$(_33b).tabs("unselect",_345(_33b,p));
p=$(_33b).tabs("getSelected");
if(p){
return false;
}
}else{
_325(_33b);
return false;
}
}
var _33f=$(this).panel("options");
_33f.tab.addClass("tabs-selected");
var wrap=$(_33b).find(">div.tabs-header>div.tabs-wrap");
var left=_33f.tab.position().left;
var _340=left+_33f.tab.outerWidth();
if(left<0||_340>wrap.width()){
var _341=left-(wrap.width()-_33f.tab.width())/2;
$(_33b).tabs("scrollBy",_341);
}else{
$(_33b).tabs("scrollBy",0);
}
var _342=$(this).panel("panel");
_342.css("display","block");
_325(_33b);
_342.css("display","none");
},onOpen:function(){
if(_33c.onOpen){
_33c.onOpen.call(this);
}
var _343=$(this).panel("options");
_33d.selectHis.push(_343.title);
_33d.options.onSelect.call(_33b,_343.title,_345(_33b,this));
},onBeforeClose:function(){
if(_33c.onBeforeClose){
if(_33c.onBeforeClose.call(this)==false){
return false;
}
}
$(this).panel("options").tab.removeClass("tabs-selected");
},onClose:function(){
if(_33c.onClose){
_33c.onClose.call(this);
}
var _344=$(this).panel("options");
_33d.options.onUnselect.call(_33b,_344.title,_345(_33b,this));
}}));
$(_33b).tabs("update",{tab:pp,options:pp.panel("options"),type:"header"});
};
function _346(_347,_348){
var _349=$.data(_347,"tabs");
var opts=_349.options;
if(_348.selected==undefined){
_348.selected=true;
}
_33a(_347,_348);
opts.onAdd.call(_347,_348.title,_348.index);
if(_348.selected){
_34a(_347,_348.index);
}
};
function _34b(_34c,_34d){
_34d.type=_34d.type||"all";
var _34e=$.data(_34c,"tabs").selectHis;
var pp=_34d.tab;
var opts=pp.panel("options");
var _34f=opts.title;
$.extend(opts,_34d.options,{iconCls:(_34d.options.icon?_34d.options.icon:undefined)});
if(_34d.type=="all"||_34d.type=="body"){
pp.panel();
}
if(_34d.type=="all"||_34d.type=="header"){
var tab=opts.tab;
if(opts.header){
tab.find(".tabs-inner").html($(opts.header));
}else{
var _350=tab.find("span.tabs-title");
var _351=tab.find("span.tabs-icon");
_350.html(opts.title);
_351.attr("class","tabs-icon");
tab.find("a.tabs-close").remove();
if(opts.closable){
_350.addClass("tabs-closable");
$("<a href=\"javascript:void(0)\" class=\"tabs-close\"></a>").appendTo(tab);
}else{
_350.removeClass("tabs-closable");
}
if(opts.iconCls){
_350.addClass("tabs-with-icon");
_351.addClass(opts.iconCls);
}else{
_350.removeClass("tabs-with-icon");
}
if(opts.tools){
var _352=tab.find("span.tabs-p-tool");
if(!_352.length){
var _352=$("<span class=\"tabs-p-tool\"></span>").insertAfter(tab.find("a.tabs-inner"));
}
if($.isArray(opts.tools)){
_352.empty();
for(var i=0;i<opts.tools.length;i++){
var t=$("<a href=\"javascript:void(0)\"></a>").appendTo(_352);
t.addClass(opts.tools[i].iconCls);
if(opts.tools[i].handler){
t.bind("click",{handler:opts.tools[i].handler},function(e){
if($(this).parents("li").hasClass("tabs-disabled")){
return;
}
e.data.handler.call(this);
});
}
}
}else{
$(opts.tools).children().appendTo(_352);
}
var pr=_352.children().length*12;
if(opts.closable){
pr+=8;
}else{
pr-=3;
_352.css("right","5px");
}
_350.css("padding-right",pr+"px");
}else{
tab.find("span.tabs-p-tool").remove();
_350.css("padding-right","");
}
}
if(_34f!=opts.title){
for(var i=0;i<_34e.length;i++){
if(_34e[i]==_34f){
_34e[i]=opts.title;
}
}
}
}
_319(_34c);
$.data(_34c,"tabs").options.onUpdate.call(_34c,opts.title,_345(_34c,pp));
};
function _353(_354,_355){
var opts=$.data(_354,"tabs").options;
var tabs=$.data(_354,"tabs").tabs;
var _356=$.data(_354,"tabs").selectHis;
if(!_357(_354,_355)){
return;
}
var tab=_358(_354,_355);
var _359=tab.panel("options").title;
var _35a=_345(_354,tab);
if(opts.onBeforeClose.call(_354,_359,_35a)==false){
return;
}
var tab=_358(_354,_355,true);
tab.panel("options").tab.remove();
tab.panel("destroy");
opts.onClose.call(_354,_359,_35a);
_319(_354);
for(var i=0;i<_356.length;i++){
if(_356[i]==_359){
_356.splice(i,1);
i--;
}
}
var _35b=_356.pop();
if(_35b){
_34a(_354,_35b);
}else{
if(tabs.length){
_34a(_354,0);
}
}
};
function _358(_35c,_35d,_35e){
var tabs=$.data(_35c,"tabs").tabs;
if(typeof _35d=="number"){
if(_35d<0||_35d>=tabs.length){
return null;
}else{
var tab=tabs[_35d];
if(_35e){
tabs.splice(_35d,1);
}
return tab;
}
}
for(var i=0;i<tabs.length;i++){
var tab=tabs[i];
if(tab.panel("options").title==_35d){
if(_35e){
tabs.splice(i,1);
}
return tab;
}
}
return null;
};
function _345(_35f,tab){
var tabs=$.data(_35f,"tabs").tabs;
for(var i=0;i<tabs.length;i++){
if(tabs[i][0]==$(tab)[0]){
return i;
}
}
return -1;
};
function _327(_360){
var tabs=$.data(_360,"tabs").tabs;
for(var i=0;i<tabs.length;i++){
var tab=tabs[i];
if(tab.panel("options").tab.hasClass("tabs-selected")){
return tab;
}
}
return null;
};
function _361(_362){
var _363=$.data(_362,"tabs");
var tabs=_363.tabs;
for(var i=0;i<tabs.length;i++){
if(tabs[i].panel("options").selected){
_34a(_362,i);
return;
}
}
_34a(_362,_363.options.selected);
};
function _34a(_364,_365){
var p=_358(_364,_365);
if(p&&!p.is(":visible")){
_366(_364);
p.panel("open");
}
};
function _367(_368,_369){
var p=_358(_368,_369);
if(p&&p.is(":visible")){
_366(_368);
p.panel("close");
}
};
function _366(_36a){
$(_36a).children("div.tabs-panels").each(function(){
$(this).stop(true,true);
});
};
function _357(_36b,_36c){
return _358(_36b,_36c)!=null;
};
function _36d(_36e,_36f){
var opts=$.data(_36e,"tabs").options;
opts.showHeader=_36f;
$(_36e).tabs("resize");
};
function _370(_371,_372){
var tool=$(_371).find(">.tabs-header>.tabs-tool");
if(_372){
tool.removeClass("tabs-tool-hidden").show();
}else{
tool.addClass("tabs-tool-hidden").hide();
}
$(_371).tabs("resize").tabs("scrollBy",0);
};
$.fn.tabs=function(_373,_374){
if(typeof _373=="string"){
return $.fn.tabs.methods[_373](this,_374);
}
_373=_373||{};
return this.each(function(){
var _375=$.data(this,"tabs");
if(_375){
$.extend(_375.options,_373);
}else{
$.data(this,"tabs",{options:$.extend({},$.fn.tabs.defaults,$.fn.tabs.parseOptions(this),_373),tabs:[],selectHis:[]});
_32b(this);
}
_315(this);
_336(this);
_319(this);
_32f(this);
_361(this);
});
};
$.fn.tabs.methods={options:function(jq){
var cc=jq[0];
var opts=$.data(cc,"tabs").options;
var s=_327(cc);
opts.selected=s?_345(cc,s):-1;
return opts;
},tabs:function(jq){
return $.data(jq[0],"tabs").tabs;
},resize:function(jq,_376){
return jq.each(function(){
_319(this,_376);
_325(this);
});
},add:function(jq,_377){
return jq.each(function(){
_346(this,_377);
});
},close:function(jq,_378){
return jq.each(function(){
_353(this,_378);
});
},getTab:function(jq,_379){
return _358(jq[0],_379);
},getTabIndex:function(jq,tab){
return _345(jq[0],tab);
},getSelected:function(jq){
return _327(jq[0]);
},select:function(jq,_37a){
return jq.each(function(){
_34a(this,_37a);
});
},unselect:function(jq,_37b){
return jq.each(function(){
_367(this,_37b);
});
},exists:function(jq,_37c){
return _357(jq[0],_37c);
},update:function(jq,_37d){
return jq.each(function(){
_34b(this,_37d);
});
},enableTab:function(jq,_37e){
return jq.each(function(){
$(this).tabs("getTab",_37e).panel("options").tab.removeClass("tabs-disabled");
});
},disableTab:function(jq,_37f){
return jq.each(function(){
$(this).tabs("getTab",_37f).panel("options").tab.addClass("tabs-disabled");
});
},showHeader:function(jq){
return jq.each(function(){
_36d(this,true);
});
},hideHeader:function(jq){
return jq.each(function(){
_36d(this,false);
});
},showTool:function(jq){
return jq.each(function(){
_370(this,true);
});
},hideTool:function(jq){
return jq.each(function(){
_370(this,false);
});
},scrollBy:function(jq,_380){
return jq.each(function(){
var opts=$(this).tabs("options");
var wrap=$(this).find(">div.tabs-header>div.tabs-wrap");
var pos=Math.min(wrap._scrollLeft()+_380,_381());
wrap.animate({scrollLeft:pos},opts.scrollDuration);
function _381(){
var w=0;
var ul=wrap.children("ul");
ul.children("li").each(function(){
w+=$(this).outerWidth(true);
});
return w-wrap.width()+(ul.outerWidth()-ul.width());
};
});
}};
$.fn.tabs.parseOptions=function(_382){
return $.extend({},$.parser.parseOptions(_382,["tools","toolPosition","tabPosition",{fit:"boolean",border:"boolean",plain:"boolean"},{headerWidth:"number",tabWidth:"number",tabHeight:"number",selected:"number"},{showHeader:"boolean",justified:"boolean",narrow:"boolean",pill:"boolean"}]));
};
$.fn.tabs.defaults={width:"auto",height:"auto",headerWidth:150,tabWidth:"auto",tabHeight:27,selected:0,showHeader:true,plain:false,fit:false,border:true,justified:false,narrow:false,pill:false,tools:null,toolPosition:"right",tabPosition:"top",scrollIncrement:100,scrollDuration:400,onLoad:function(_383){
},onSelect:function(_384,_385){
},onUnselect:function(_386,_387){
},onBeforeClose:function(_388,_389){
},onClose:function(_38a,_38b){
},onAdd:function(_38c,_38d){
},onUpdate:function(_38e,_38f){
},onContextMenu:function(e,_390,_391){
}};
})(jQuery);
(function($){
var _392=false;
function _393(_394,_395){
var _396=$.data(_394,"layout");
var opts=_396.options;
var _397=_396.panels;
var cc=$(_394);
if(_395){
$.extend(opts,{width:_395.width,height:_395.height});
}
if(_394.tagName.toLowerCase()=="body"){
cc._size("fit");
}else{
cc._size(opts);
}
var cpos={top:0,left:0,width:cc.width(),height:cc.height()};
_398(_399(_397.expandNorth)?_397.expandNorth:_397.north,"n");
_398(_399(_397.expandSouth)?_397.expandSouth:_397.south,"s");
_39a(_399(_397.expandEast)?_397.expandEast:_397.east,"e");
_39a(_399(_397.expandWest)?_397.expandWest:_397.west,"w");
_397.center.panel("resize",cpos);
function _398(pp,type){
if(!pp.length||!_399(pp)){
return;
}
var opts=pp.panel("options");
pp.panel("resize",{width:cc.width(),height:opts.height});
var _39b=pp.panel("panel").outerHeight();
pp.panel("move",{left:0,top:(type=="n"?0:cc.height()-_39b)});
cpos.height-=_39b;
if(type=="n"){
cpos.top+=_39b;
if(!opts.split&&opts.border){
cpos.top--;
}
}
if(!opts.split&&opts.border){
cpos.height++;
}
};
function _39a(pp,type){
if(!pp.length||!_399(pp)){
return;
}
var opts=pp.panel("options");
pp.panel("resize",{width:opts.width,height:cpos.height});
var _39c=pp.panel("panel").outerWidth();
pp.panel("move",{left:(type=="e"?cc.width()-_39c:0),top:cpos.top});
cpos.width-=_39c;
if(type=="w"){
cpos.left+=_39c;
if(!opts.split&&opts.border){
cpos.left--;
}
}
if(!opts.split&&opts.border){
cpos.width++;
}
};
};
function init(_39d){
var cc=$(_39d);
cc.addClass("layout");
function _39e(cc){
cc.children("div").each(function(){
var opts=$.fn.layout.parsePanelOptions(this);
if("north,south,east,west,center".indexOf(opts.region)>=0){
_3a0(_39d,opts,this);
}
});
};
cc.children("form").length?_39e(cc.children("form")):_39e(cc);
cc.append("<div class=\"layout-split-proxy-h\"></div><div class=\"layout-split-proxy-v\"></div>");
cc.bind("_resize",function(e,_39f){
if($(this).hasClass("easyui-fluid")||_39f){
_393(_39d);
}
return false;
});
};
function _3a0(_3a1,_3a2,el){
_3a2.region=_3a2.region||"center";
var _3a3=$.data(_3a1,"layout").panels;
var cc=$(_3a1);
var dir=_3a2.region;
if(_3a3[dir].length){
return;
}
var pp=$(el);
if(!pp.length){
pp=$("<div></div>").appendTo(cc);
}
var _3a4=$.extend({},$.fn.layout.paneldefaults,{width:(pp.length?parseInt(pp[0].style.width)||pp.outerWidth():"auto"),height:(pp.length?parseInt(pp[0].style.height)||pp.outerHeight():"auto"),doSize:false,collapsible:true,onOpen:function(){
var tool=$(this).panel("header").children("div.panel-tool");
tool.children("a.panel-tool-collapse").hide();
var _3a5={north:"up",south:"down",east:"right",west:"left"};
if(!_3a5[dir]){
return;
}
var _3a6="layout-button-"+_3a5[dir];
var t=tool.children("a."+_3a6);
if(!t.length){
t=$("<a href=\"javascript:void(0)\"></a>").addClass(_3a6).appendTo(tool);
t.bind("click",{dir:dir},function(e){
_3b2(_3a1,e.data.dir);
return false;
});
}
$(this).panel("options").collapsible?t.show():t.hide();
}},_3a2,{cls:((_3a2.cls||"")+" layout-panel layout-panel-"+dir),bodyCls:((_3a2.bodyCls||"")+" layout-body")});
pp.panel(_3a4);
_3a3[dir]=pp;
var _3a7={north:"s",south:"n",east:"w",west:"e"};
var _3a8=pp.panel("panel");
if(pp.panel("options").split){
_3a8.addClass("layout-split-"+dir);
}
_3a8.resizable($.extend({},{handles:(_3a7[dir]||""),disabled:(!pp.panel("options").split),onStartResize:function(e){
_392=true;
if(dir=="north"||dir=="south"){
var _3a9=$(">div.layout-split-proxy-v",_3a1);
}else{
var _3a9=$(">div.layout-split-proxy-h",_3a1);
}
var top=0,left=0,_3aa=0,_3ab=0;
var pos={display:"block"};
if(dir=="north"){
pos.top=parseInt(_3a8.css("top"))+_3a8.outerHeight()-_3a9.height();
pos.left=parseInt(_3a8.css("left"));
pos.width=_3a8.outerWidth();
pos.height=_3a9.height();
}else{
if(dir=="south"){
pos.top=parseInt(_3a8.css("top"));
pos.left=parseInt(_3a8.css("left"));
pos.width=_3a8.outerWidth();
pos.height=_3a9.height();
}else{
if(dir=="east"){
pos.top=parseInt(_3a8.css("top"))||0;
pos.left=parseInt(_3a8.css("left"))||0;
pos.width=_3a9.width();
pos.height=_3a8.outerHeight();
}else{
if(dir=="west"){
pos.top=parseInt(_3a8.css("top"))||0;
pos.left=_3a8.outerWidth()-_3a9.width();
pos.width=_3a9.width();
pos.height=_3a8.outerHeight();
}
}
}
}
_3a9.css(pos);
$("<div class=\"layout-mask\"></div>").css({left:0,top:0,width:cc.width(),height:cc.height()}).appendTo(cc);
},onResize:function(e){
if(dir=="north"||dir=="south"){
var _3ac=$(">div.layout-split-proxy-v",_3a1);
_3ac.css("top",e.pageY-$(_3a1).offset().top-_3ac.height()/2);
}else{
var _3ac=$(">div.layout-split-proxy-h",_3a1);
_3ac.css("left",e.pageX-$(_3a1).offset().left-_3ac.width()/2);
}
return false;
},onStopResize:function(e){
cc.children("div.layout-split-proxy-v,div.layout-split-proxy-h").hide();
pp.panel("resize",e.data);
_393(_3a1);
_392=false;
cc.find(">div.layout-mask").remove();
}},_3a2));
};
function _3ad(_3ae,_3af){
var _3b0=$.data(_3ae,"layout").panels;
if(_3b0[_3af].length){
_3b0[_3af].panel("destroy");
_3b0[_3af]=$();
var _3b1="expand"+_3af.substring(0,1).toUpperCase()+_3af.substring(1);
if(_3b0[_3b1]){
_3b0[_3b1].panel("destroy");
_3b0[_3b1]=undefined;
}
}
};
function _3b2(_3b3,_3b4,_3b5){
if(_3b5==undefined){
_3b5="normal";
}
var _3b6=$.data(_3b3,"layout").panels;
var p=_3b6[_3b4];
var _3b7=p.panel("options");
if(_3b7.onBeforeCollapse.call(p)==false){
return;
}
var _3b8="expand"+_3b4.substring(0,1).toUpperCase()+_3b4.substring(1);
if(!_3b6[_3b8]){
_3b6[_3b8]=_3b9(_3b4);
_3b6[_3b8].panel("panel").bind("click",function(){
p.panel("expand",false).panel("open");
var _3ba=_3bb();
p.panel("resize",_3ba.collapse);
p.panel("panel").animate(_3ba.expand,function(){
$(this).unbind(".layout").bind("mouseleave.layout",{region:_3b4},function(e){
if(_392==true){
return;
}
if($("body>div.combo-p>div.combo-panel:visible").length){
return;
}
_3b2(_3b3,e.data.region);
});
});
return false;
});
}
var _3bc=_3bb();
if(!_399(_3b6[_3b8])){
_3b6.center.panel("resize",_3bc.resizeC);
}
p.panel("panel").animate(_3bc.collapse,_3b5,function(){
p.panel("collapse",false).panel("close");
_3b6[_3b8].panel("open").panel("resize",_3bc.expandP);
$(this).unbind(".layout");
});
function _3b9(dir){
var icon;
if(dir=="east"){
icon="layout-button-left";
}else{
if(dir=="west"){
icon="layout-button-right";
}else{
if(dir=="north"){
icon="layout-button-down";
}else{
if(dir=="south"){
icon="layout-button-up";
}
}
}
}
var p=$("<div></div>").appendTo(_3b3);
p.panel($.extend({},$.fn.layout.paneldefaults,{cls:("layout-expand layout-expand-"+dir),title:"&nbsp;",closed:true,minWidth:0,minHeight:0,doSize:false,tools:[{iconCls:icon,handler:function(){
_3c2(_3b3,_3b4);
return false;
}}]}));
p.panel("panel").hover(function(){
$(this).addClass("layout-expand-over");
},function(){
$(this).removeClass("layout-expand-over");
});
return p;
};
function _3bb(){
var cc=$(_3b3);
var _3bd=_3b6.center.panel("options");
var _3be=_3b7.collapsedSize;
if(_3b4=="east"){
var _3bf=p.panel("panel")._outerWidth();
var _3c0=_3bd.width+_3bf-_3be;
if(_3b7.split||!_3b7.border){
_3c0++;
}
return {resizeC:{width:_3c0},expand:{left:cc.width()-_3bf},expandP:{top:_3bd.top,left:cc.width()-_3be,width:_3be,height:_3bd.height},collapse:{left:cc.width(),top:_3bd.top,height:_3bd.height}};
}else{
if(_3b4=="west"){
var _3bf=p.panel("panel")._outerWidth();
var _3c0=_3bd.width+_3bf-_3be;
if(_3b7.split||!_3b7.border){
_3c0++;
}
return {resizeC:{width:_3c0,left:_3be-1},expand:{left:0},expandP:{left:0,top:_3bd.top,width:_3be,height:_3bd.height},collapse:{left:-_3bf,top:_3bd.top,height:_3bd.height}};
}else{
if(_3b4=="north"){
var _3c1=p.panel("panel")._outerHeight();
var hh=_3bd.height;
if(!_399(_3b6.expandNorth)){
hh+=_3c1-_3be+((_3b7.split||!_3b7.border)?1:0);
}
_3b6.east.add(_3b6.west).add(_3b6.expandEast).add(_3b6.expandWest).panel("resize",{top:_3be-1,height:hh});
return {resizeC:{top:_3be-1,height:hh},expand:{top:0},expandP:{top:0,left:0,width:cc.width(),height:_3be},collapse:{top:-_3c1,width:cc.width()}};
}else{
if(_3b4=="south"){
var _3c1=p.panel("panel")._outerHeight();
var hh=_3bd.height;
if(!_399(_3b6.expandSouth)){
hh+=_3c1-_3be+((_3b7.split||!_3b7.border)?1:0);
}
_3b6.east.add(_3b6.west).add(_3b6.expandEast).add(_3b6.expandWest).panel("resize",{height:hh});
return {resizeC:{height:hh},expand:{top:cc.height()-_3c1},expandP:{top:cc.height()-_3be,left:0,width:cc.width(),height:_3be},collapse:{top:cc.height(),width:cc.width()}};
}
}
}
}
};
};
function _3c2(_3c3,_3c4){
var _3c5=$.data(_3c3,"layout").panels;
var p=_3c5[_3c4];
var _3c6=p.panel("options");
if(_3c6.onBeforeExpand.call(p)==false){
return;
}
var _3c7="expand"+_3c4.substring(0,1).toUpperCase()+_3c4.substring(1);
if(_3c5[_3c7]){
_3c5[_3c7].panel("close");
p.panel("panel").stop(true,true);
p.panel("expand",false).panel("open");
var _3c8=_3c9();
p.panel("resize",_3c8.collapse);
p.panel("panel").animate(_3c8.expand,function(){
_393(_3c3);
});
}
function _3c9(){
var cc=$(_3c3);
var _3ca=_3c5.center.panel("options");
if(_3c4=="east"&&_3c5.expandEast){
return {collapse:{left:cc.width(),top:_3ca.top,height:_3ca.height},expand:{left:cc.width()-p.panel("panel")._outerWidth()}};
}else{
if(_3c4=="west"&&_3c5.expandWest){
return {collapse:{left:-p.panel("panel")._outerWidth(),top:_3ca.top,height:_3ca.height},expand:{left:0}};
}else{
if(_3c4=="north"&&_3c5.expandNorth){
return {collapse:{top:-p.panel("panel")._outerHeight(),width:cc.width()},expand:{top:0}};
}else{
if(_3c4=="south"&&_3c5.expandSouth){
return {collapse:{top:cc.height(),width:cc.width()},expand:{top:cc.height()-p.panel("panel")._outerHeight()}};
}
}
}
}
};
};
function _399(pp){
if(!pp){
return false;
}
if(pp.length){
return pp.panel("panel").is(":visible");
}else{
return false;
}
};
function _3cb(_3cc){
var _3cd=$.data(_3cc,"layout").panels;
_3ce("east");
_3ce("west");
_3ce("north");
_3ce("south");
function _3ce(_3cf){
var p=_3cd[_3cf];
if(p.length&&p.panel("options").collapsed){
_3b2(_3cc,_3cf,0);
}
};
};
function _3d0(_3d1,_3d2,_3d3){
var p=$(_3d1).layout("panel",_3d2);
p.panel("options").split=_3d3;
var cls="layout-split-"+_3d2;
var _3d4=p.panel("panel").removeClass(cls);
if(_3d3){
_3d4.addClass(cls);
}
_3d4.resizable({disabled:(!_3d3)});
_393(_3d1);
};
$.fn.layout=function(_3d5,_3d6){
if(typeof _3d5=="string"){
return $.fn.layout.methods[_3d5](this,_3d6);
}
_3d5=_3d5||{};
return this.each(function(){
var _3d7=$.data(this,"layout");
if(_3d7){
$.extend(_3d7.options,_3d5);
}else{
var opts=$.extend({},$.fn.layout.defaults,$.fn.layout.parseOptions(this),_3d5);
$.data(this,"layout",{options:opts,panels:{center:$(),north:$(),south:$(),east:$(),west:$()}});
init(this);
}
_393(this);
_3cb(this);
});
};
$.fn.layout.methods={options:function(jq){
return $.data(jq[0],"layout").options;
},resize:function(jq,_3d8){
return jq.each(function(){
_393(this,_3d8);
});
},panel:function(jq,_3d9){
return $.data(jq[0],"layout").panels[_3d9];
},collapse:function(jq,_3da){
return jq.each(function(){
_3b2(this,_3da);
});
},expand:function(jq,_3db){
return jq.each(function(){
_3c2(this,_3db);
});
},add:function(jq,_3dc){
return jq.each(function(){
_3a0(this,_3dc);
_393(this);
if($(this).layout("panel",_3dc.region).panel("options").collapsed){
_3b2(this,_3dc.region,0);
}
});
},remove:function(jq,_3dd){
return jq.each(function(){
_3ad(this,_3dd);
_393(this);
});
},split:function(jq,_3de){
return jq.each(function(){
_3d0(this,_3de,true);
});
},unsplit:function(jq,_3df){
return jq.each(function(){
_3d0(this,_3df,false);
});
}};
$.fn.layout.parseOptions=function(_3e0){
return $.extend({},$.parser.parseOptions(_3e0,[{fit:"boolean"}]));
};
$.fn.layout.defaults={fit:false};
$.fn.layout.parsePanelOptions=function(_3e1){
var t=$(_3e1);
return $.extend({},$.fn.panel.parseOptions(_3e1),$.parser.parseOptions(_3e1,["region",{split:"boolean",collpasedSize:"number",minWidth:"number",minHeight:"number",maxWidth:"number",maxHeight:"number"}]));
};
$.fn.layout.paneldefaults=$.extend({},$.fn.panel.defaults,{region:null,split:false,collapsedSize:28,minWidth:10,minHeight:10,maxWidth:10000,maxHeight:10000});
})(jQuery);
(function($){
$(function(){
$(document).unbind(".menu").bind("mousedown.menu",function(e){
var m=$(e.target).closest("div.menu,div.combo-p");
if(m.length){
return;
}
$("body>div.menu-top:visible").not(".menu-inline").menu("hide");
_3e2($("body>div.menu:visible").not(".menu-inline"));
});
});
function init(_3e3){
var opts=$.data(_3e3,"menu").options;
$(_3e3).addClass("menu-top");
opts.inline?$(_3e3).addClass("menu-inline"):$(_3e3).appendTo("body");
$(_3e3).bind("_resize",function(e,_3e4){
if($(this).hasClass("easyui-fluid")||_3e4){
$(_3e3).menu("resize",_3e3);
}
return false;
});
var _3e5=_3e6($(_3e3));
for(var i=0;i<_3e5.length;i++){
_3e7(_3e5[i]);
}
function _3e6(menu){
var _3e8=[];
menu.addClass("menu");
_3e8.push(menu);
if(!menu.hasClass("menu-content")){
menu.children("div").each(function(){
var _3e9=$(this).children("div");
if(_3e9.length){
_3e9.appendTo("body");
this.submenu=_3e9;
var mm=_3e6(_3e9);
_3e8=_3e8.concat(mm);
}
});
}
return _3e8;
};
function _3e7(menu){
var wh=$.parser.parseOptions(menu[0],["width","height"]);
menu[0].originalHeight=wh.height||0;
if(menu.hasClass("menu-content")){
menu[0].originalWidth=wh.width||menu._outerWidth();
}else{
menu[0].originalWidth=wh.width||0;
menu.children("div").each(function(){
var item=$(this);
var _3ea=$.extend({},$.parser.parseOptions(this,["name","iconCls","href",{separator:"boolean"}]),{disabled:(item.attr("disabled")?true:undefined)});
if(_3ea.separator){
item.addClass("menu-sep");
}
if(!item.hasClass("menu-sep")){
item[0].itemName=_3ea.name||"";
item[0].itemHref=_3ea.href||"";
var text=item.addClass("menu-item").html();
item.empty().append($("<div class=\"menu-text\"></div>").html(text));
if(_3ea.iconCls){
$("<div class=\"menu-icon\"></div>").addClass(_3ea.iconCls).appendTo(item);
}
if(_3ea.disabled){
_3eb(_3e3,item[0],true);
}
if(item[0].submenu){
$("<div class=\"menu-rightarrow\"></div>").appendTo(item);
}
_3ec(_3e3,item);
}
});
$("<div class=\"menu-line\"></div>").prependTo(menu);
}
_3ed(_3e3,menu);
if(!menu.hasClass("menu-inline")){
menu.hide();
}
_3ee(_3e3,menu);
};
};
function _3ed(_3ef,menu){
var opts=$.data(_3ef,"menu").options;
var _3f0=menu.attr("style")||"";
menu.css({display:"block",left:-10000,height:"auto",overflow:"hidden"});
menu.find(".menu-item").each(function(){
$(this)._outerHeight(opts.itemHeight);
$(this).find(".menu-text").css({height:(opts.itemHeight-2)+"px",lineHeight:(opts.itemHeight-2)+"px"});
});
menu.removeClass("menu-noline").addClass(opts.noline?"menu-noline":"");
var _3f1=menu[0].originalWidth||"auto";
if(isNaN(parseInt(_3f1))){
_3f1=0;
menu.find("div.menu-text").each(function(){
if(_3f1<$(this)._outerWidth()){
_3f1=$(this)._outerWidth();
}
});
_3f1+=40;
}
var _3f2=menu.outerHeight();
var _3f3=menu[0].originalHeight||"auto";
if(isNaN(parseInt(_3f3))){
_3f3=_3f2;
if(menu.hasClass("menu-top")&&opts.alignTo){
var at=$(opts.alignTo);
var h1=at.offset().top-$(document).scrollTop();
var h2=$(window)._outerHeight()+$(document).scrollTop()-at.offset().top-at._outerHeight();
_3f3=Math.min(_3f3,Math.max(h1,h2));
}else{
if(_3f3>$(window)._outerHeight()){
_3f3=$(window).height();
}
}
}
menu.attr("style",_3f0);
menu._size({fit:(menu[0]==_3ef?opts.fit:false),width:_3f1,minWidth:opts.minWidth,height:_3f3});
menu.css("overflow",menu.outerHeight()<_3f2?"auto":"hidden");
menu.children("div.menu-line")._outerHeight(_3f2-2);
};
function _3ee(_3f4,menu){
if(menu.hasClass("menu-inline")){
return;
}
var _3f5=$.data(_3f4,"menu");
menu.unbind(".menu").bind("mouseenter.menu",function(){
if(_3f5.timer){
clearTimeout(_3f5.timer);
_3f5.timer=null;
}
}).bind("mouseleave.menu",function(){
if(_3f5.options.hideOnUnhover){
_3f5.timer=setTimeout(function(){
_3f6(_3f4,$(_3f4).hasClass("menu-inline"));
},_3f5.options.duration);
}
});
};
function _3ec(_3f7,item){
if(!item.hasClass("menu-item")){
return;
}
item.unbind(".menu");
item.bind("click.menu",function(){
if($(this).hasClass("menu-item-disabled")){
return;
}
if(!this.submenu){
_3f6(_3f7,$(_3f7).hasClass("menu-inline"));
var href=this.itemHref;
if(href){
location.href=href;
}
}
$(this).trigger("mouseenter");
var item=$(_3f7).menu("getItem",this);
$.data(_3f7,"menu").options.onClick.call(_3f7,item);
}).bind("mouseenter.menu",function(e){
item.siblings().each(function(){
if(this.submenu){
_3e2(this.submenu);
}
$(this).removeClass("menu-active");
});
item.addClass("menu-active");
if($(this).hasClass("menu-item-disabled")){
item.addClass("menu-active-disabled");
return;
}
var _3f8=item[0].submenu;
if(_3f8){
$(_3f7).menu("show",{menu:_3f8,parent:item});
}
}).bind("mouseleave.menu",function(e){
item.removeClass("menu-active menu-active-disabled");
var _3f9=item[0].submenu;
if(_3f9){
if(e.pageX>=parseInt(_3f9.css("left"))){
item.addClass("menu-active");
}else{
_3e2(_3f9);
}
}else{
item.removeClass("menu-active");
}
});
};
function _3f6(_3fa,_3fb){
var _3fc=$.data(_3fa,"menu");
if(_3fc){
if($(_3fa).is(":visible")){
_3e2($(_3fa));
if(_3fb){
$(_3fa).show();
}else{
_3fc.options.onHide.call(_3fa);
}
}
}
return false;
};
function _3fd(_3fe,_3ff){
var left,top;
_3ff=_3ff||{};
var menu=$(_3ff.menu||_3fe);
$(_3fe).menu("resize",menu[0]);
if(menu.hasClass("menu-top")){
var opts=$.data(_3fe,"menu").options;
$.extend(opts,_3ff);
left=opts.left;
top=opts.top;
if(opts.alignTo){
var at=$(opts.alignTo);
left=at.offset().left;
top=at.offset().top+at._outerHeight();
if(opts.align=="right"){
left+=at.outerWidth()-menu.outerWidth();
}
}
if(left+menu.outerWidth()>$(window)._outerWidth()+$(document)._scrollLeft()){
left=$(window)._outerWidth()+$(document).scrollLeft()-menu.outerWidth()-5;
}
if(left<0){
left=0;
}
top=_400(top,opts.alignTo);
}else{
var _401=_3ff.parent;
left=_401.offset().left+_401.outerWidth()-2;
if(left+menu.outerWidth()+5>$(window)._outerWidth()+$(document).scrollLeft()){
left=_401.offset().left-menu.outerWidth()+2;
}
top=_400(_401.offset().top-3);
}
function _400(top,_402){
if(top+menu.outerHeight()>$(window)._outerHeight()+$(document).scrollTop()){
if(_402){
top=$(_402).offset().top-menu._outerHeight();
}else{
top=$(window)._outerHeight()+$(document).scrollTop()-menu.outerHeight();
}
}
if(top<0){
top=0;
}
return top;
};
menu.css({left:left,top:top});
menu.show(0,function(){
if(!menu[0].shadow){
menu[0].shadow=$("<div class=\"menu-shadow\"></div>").insertAfter(menu);
}
menu[0].shadow.css({display:(menu.hasClass("menu-inline")?"none":"block"),zIndex:$.fn.menu.defaults.zIndex++,left:menu.css("left"),top:menu.css("top"),width:menu.outerWidth(),height:menu.outerHeight()});
menu.css("z-index",$.fn.menu.defaults.zIndex++);
if(menu.hasClass("menu-top")){
$.data(menu[0],"menu").options.onShow.call(menu[0]);
}
});
};
function _3e2(menu){
if(menu&&menu.length){
_403(menu);
menu.find("div.menu-item").each(function(){
if(this.submenu){
_3e2(this.submenu);
}
$(this).removeClass("menu-active");
});
}
function _403(m){
m.stop(true,true);
if(m[0].shadow){
m[0].shadow.hide();
}
m.hide();
};
};
function _404(_405,text){
var _406=null;
var tmp=$("<div></div>");
function find(menu){
menu.children("div.menu-item").each(function(){
var item=$(_405).menu("getItem",this);
var s=tmp.empty().html(item.text).text();
if(text==$.trim(s)){
_406=item;
}else{
if(this.submenu&&!_406){
find(this.submenu);
}
}
});
};
find($(_405));
tmp.remove();
return _406;
};
function _3eb(_407,_408,_409){
var t=$(_408);
if(!t.hasClass("menu-item")){
return;
}
if(_409){
t.addClass("menu-item-disabled");
if(_408.onclick){
_408.onclick1=_408.onclick;
_408.onclick=null;
}
}else{
t.removeClass("menu-item-disabled");
if(_408.onclick1){
_408.onclick=_408.onclick1;
_408.onclick1=null;
}
}
};
function _40a(_40b,_40c){
var opts=$.data(_40b,"menu").options;
var menu=$(_40b);
if(_40c.parent){
if(!_40c.parent.submenu){
var _40d=$("<div class=\"menu\"><div class=\"menu-line\"></div></div>").appendTo("body");
_40d.hide();
_40c.parent.submenu=_40d;
$("<div class=\"menu-rightarrow\"></div>").appendTo(_40c.parent);
}
menu=_40c.parent.submenu;
}
if(_40c.separator){
var item=$("<div class=\"menu-sep\"></div>").appendTo(menu);
}else{
var item=$("<div class=\"menu-item\"></div>").appendTo(menu);
$("<div class=\"menu-text\"></div>").html(_40c.text).appendTo(item);
}
if(_40c.iconCls){
$("<div class=\"menu-icon\"></div>").addClass(_40c.iconCls).appendTo(item);
}
if(_40c.id){
item.attr("id",_40c.id);
}
if(_40c.name){
item[0].itemName=_40c.name;
}
if(_40c.href){
item[0].itemHref=_40c.href;
}
if(_40c.onclick){
if(typeof _40c.onclick=="string"){
item.attr("onclick",_40c.onclick);
}else{
item[0].onclick=eval(_40c.onclick);
}
}
if(_40c.handler){
item[0].onclick=eval(_40c.handler);
}
if(_40c.disabled){
_3eb(_40b,item[0],true);
}
_3ec(_40b,item);
_3ee(_40b,menu);
_3ed(_40b,menu);
};
function _40e(_40f,_410){
function _411(el){
if(el.submenu){
el.submenu.children("div.menu-item").each(function(){
_411(this);
});
var _412=el.submenu[0].shadow;
if(_412){
_412.remove();
}
el.submenu.remove();
}
$(el).remove();
};
var menu=$(_410).parent();
_411(_410);
_3ed(_40f,menu);
};
function _413(_414,_415,_416){
var menu=$(_415).parent();
if(_416){
$(_415).show();
}else{
$(_415).hide();
}
_3ed(_414,menu);
};
function _417(_418){
$(_418).children("div.menu-item").each(function(){
_40e(_418,this);
});
if(_418.shadow){
_418.shadow.remove();
}
$(_418).remove();
};
$.fn.menu=function(_419,_41a){
if(typeof _419=="string"){
return $.fn.menu.methods[_419](this,_41a);
}
_419=_419||{};
return this.each(function(){
var _41b=$.data(this,"menu");
if(_41b){
$.extend(_41b.options,_419);
}else{
_41b=$.data(this,"menu",{options:$.extend({},$.fn.menu.defaults,$.fn.menu.parseOptions(this),_419)});
init(this);
}
$(this).css({left:_41b.options.left,top:_41b.options.top});
});
};
$.fn.menu.methods={options:function(jq){
return $.data(jq[0],"menu").options;
},show:function(jq,pos){
return jq.each(function(){
_3fd(this,pos);
});
},hide:function(jq){
return jq.each(function(){
_3f6(this);
});
},destroy:function(jq){
return jq.each(function(){
_417(this);
});
},setText:function(jq,_41c){
return jq.each(function(){
$(_41c.target).children("div.menu-text").html(_41c.text);
});
},setIcon:function(jq,_41d){
return jq.each(function(){
$(_41d.target).children("div.menu-icon").remove();
if(_41d.iconCls){
$("<div class=\"menu-icon\"></div>").addClass(_41d.iconCls).appendTo(_41d.target);
}
});
},getItem:function(jq,_41e){
var t=$(_41e);
var item={target:_41e,id:t.attr("id"),text:$.trim(t.children("div.menu-text").html()),disabled:t.hasClass("menu-item-disabled"),name:_41e.itemName,href:_41e.itemHref,onclick:_41e.onclick};
var icon=t.children("div.menu-icon");
if(icon.length){
var cc=[];
var aa=icon.attr("class").split(" ");
for(var i=0;i<aa.length;i++){
if(aa[i]!="menu-icon"){
cc.push(aa[i]);
}
}
item.iconCls=cc.join(" ");
}
return item;
},findItem:function(jq,text){
return _404(jq[0],text);
},appendItem:function(jq,_41f){
return jq.each(function(){
_40a(this,_41f);
});
},removeItem:function(jq,_420){
return jq.each(function(){
_40e(this,_420);
});
},enableItem:function(jq,_421){
return jq.each(function(){
_3eb(this,_421,false);
});
},disableItem:function(jq,_422){
return jq.each(function(){
_3eb(this,_422,true);
});
},showItem:function(jq,_423){
return jq.each(function(){
_413(this,_423,true);
});
},hideItem:function(jq,_424){
return jq.each(function(){
_413(this,_424,false);
});
},resize:function(jq,_425){
return jq.each(function(){
_3ed(this,$(_425));
});
}};
$.fn.menu.parseOptions=function(_426){
return $.extend({},$.parser.parseOptions(_426,[{minWidth:"number",itemHeight:"number",duration:"number",hideOnUnhover:"boolean"},{fit:"boolean",inline:"boolean",noline:"boolean"}]));
};
$.fn.menu.defaults={zIndex:110000,left:0,top:0,alignTo:null,align:"left",minWidth:120,itemHeight:22,duration:100,hideOnUnhover:true,inline:false,fit:false,noline:false,onShow:function(){
},onHide:function(){
},onClick:function(item){
}};
})(jQuery);
(function($){
function init(_427){
var opts=$.data(_427,"menubutton").options;
var btn=$(_427);
btn.linkbutton(opts);
if(opts.hasDownArrow){
btn.removeClass(opts.cls.btn1+" "+opts.cls.btn2).addClass("m-btn");
btn.removeClass("m-btn-small m-btn-medium m-btn-large").addClass("m-btn-"+opts.size);
var _428=btn.find(".l-btn-left");
$("<span></span>").addClass(opts.cls.arrow).appendTo(_428);
$("<span></span>").addClass("m-btn-line").appendTo(_428);
}
$(_427).menubutton("resize");
if(opts.menu){
$(opts.menu).menu({duration:opts.duration});
var _429=$(opts.menu).menu("options");
var _42a=_429.onShow;
var _42b=_429.onHide;
$.extend(_429,{onShow:function(){
var _42c=$(this).menu("options");
var btn=$(_42c.alignTo);
var opts=btn.menubutton("options");
btn.addClass((opts.plain==true)?opts.cls.btn2:opts.cls.btn1);
_42a.call(this);
},onHide:function(){
var _42d=$(this).menu("options");
var btn=$(_42d.alignTo);
var opts=btn.menubutton("options");
btn.removeClass((opts.plain==true)?opts.cls.btn2:opts.cls.btn1);
_42b.call(this);
}});
}
};
function _42e(_42f){
var opts=$.data(_42f,"menubutton").options;
var btn=$(_42f);
var t=btn.find("."+opts.cls.trigger);
if(!t.length){
t=btn;
}
t.unbind(".menubutton");
var _430=null;
t.bind("click.menubutton",function(){
if(!_431()){
_432(_42f);
return false;
}
}).bind("mouseenter.menubutton",function(){
if(!_431()){
_430=setTimeout(function(){
_432(_42f);
},opts.duration);
return false;
}
}).bind("mouseleave.menubutton",function(){
if(_430){
clearTimeout(_430);
}
$(opts.menu).triggerHandler("mouseleave");
});
function _431(){
return $(_42f).linkbutton("options").disabled;
};
};
function _432(_433){
var opts=$(_433).menubutton("options");
if(opts.disabled||!opts.menu){
return;
}
$("body>div.menu-top").menu("hide");
var btn=$(_433);
var mm=$(opts.menu);
if(mm.length){
mm.menu("options").alignTo=btn;
mm.menu("show",{alignTo:btn,align:opts.menuAlign});
}
btn.blur();
};
$.fn.menubutton=function(_434,_435){
if(typeof _434=="string"){
var _436=$.fn.menubutton.methods[_434];
if(_436){
return _436(this,_435);
}else{
return this.linkbutton(_434,_435);
}
}
_434=_434||{};
return this.each(function(){
var _437=$.data(this,"menubutton");
if(_437){
$.extend(_437.options,_434);
}else{
$.data(this,"menubutton",{options:$.extend({},$.fn.menubutton.defaults,$.fn.menubutton.parseOptions(this),_434)});
$(this).removeAttr("disabled");
}
init(this);
_42e(this);
});
};
$.fn.menubutton.methods={options:function(jq){
var _438=jq.linkbutton("options");
return $.extend($.data(jq[0],"menubutton").options,{toggle:_438.toggle,selected:_438.selected,disabled:_438.disabled});
},destroy:function(jq){
return jq.each(function(){
var opts=$(this).menubutton("options");
if(opts.menu){
$(opts.menu).menu("destroy");
}
$(this).remove();
});
}};
$.fn.menubutton.parseOptions=function(_439){
var t=$(_439);
return $.extend({},$.fn.linkbutton.parseOptions(_439),$.parser.parseOptions(_439,["menu",{plain:"boolean",hasDownArrow:"boolean",duration:"number"}]));
};
$.fn.menubutton.defaults=$.extend({},$.fn.linkbutton.defaults,{plain:true,hasDownArrow:true,menu:null,menuAlign:"left",duration:100,cls:{btn1:"m-btn-active",btn2:"m-btn-plain-active",arrow:"m-btn-downarrow",trigger:"m-btn"}});
})(jQuery);
(function($){
function init(_43a){
var opts=$.data(_43a,"splitbutton").options;
$(_43a).menubutton(opts);
$(_43a).addClass("s-btn");
};
$.fn.splitbutton=function(_43b,_43c){
if(typeof _43b=="string"){
var _43d=$.fn.splitbutton.methods[_43b];
if(_43d){
return _43d(this,_43c);
}else{
return this.menubutton(_43b,_43c);
}
}
_43b=_43b||{};
return this.each(function(){
var _43e=$.data(this,"splitbutton");
if(_43e){
$.extend(_43e.options,_43b);
}else{
$.data(this,"splitbutton",{options:$.extend({},$.fn.splitbutton.defaults,$.fn.splitbutton.parseOptions(this),_43b)});
$(this).removeAttr("disabled");
}
init(this);
});
};
$.fn.splitbutton.methods={options:function(jq){
var _43f=jq.menubutton("options");
var _440=$.data(jq[0],"splitbutton").options;
$.extend(_440,{disabled:_43f.disabled,toggle:_43f.toggle,selected:_43f.selected});
return _440;
}};
$.fn.splitbutton.parseOptions=function(_441){
var t=$(_441);
return $.extend({},$.fn.linkbutton.parseOptions(_441),$.parser.parseOptions(_441,["menu",{plain:"boolean",duration:"number"}]));
};
$.fn.splitbutton.defaults=$.extend({},$.fn.linkbutton.defaults,{plain:true,menu:null,duration:100,cls:{btn1:"m-btn-active s-btn-active",btn2:"m-btn-plain-active s-btn-plain-active",arrow:"m-btn-downarrow",trigger:"m-btn-line"}});
})(jQuery);
(function($){
function init(_442){
var _443=$("<span class=\"switchbutton\">"+"<span class=\"switchbutton-inner\">"+"<span class=\"switchbutton-on\"></span>"+"<span class=\"switchbutton-handle\"></span>"+"<span class=\"switchbutton-off\"></span>"+"<input class=\"switchbutton-value\" type=\"checkbox\">"+"</span>"+"</span>").insertAfter(_442);
var t=$(_442);
t.addClass("switchbutton-f").hide();
var name=t.attr("name");
if(name){
t.removeAttr("name").attr("switchbuttonName",name);
_443.find(".switchbutton-value").attr("name",name);
}
_443.bind("_resize",function(e,_444){
if($(this).hasClass("easyui-fluid")||_444){
_445(_442);
}
return false;
});
return _443;
};
function _445(_446,_447){
var _448=$.data(_446,"switchbutton");
var opts=_448.options;
var _449=_448.switchbutton;
if(_447){
$.extend(opts,_447);
}
var _44a=_449.is(":visible");
if(!_44a){
_449.appendTo("body");
}
_449._size(opts);
var w=_449.width();
var h=_449.height();
var w=_449.outerWidth();
var h=_449.outerHeight();
var _44b=parseInt(opts.handleWidth)||_449.height();
var _44c=w*2-_44b;
_449.find(".switchbutton-inner").css({width:_44c+"px",height:h+"px",lineHeight:h+"px"});
_449.find(".switchbutton-handle")._outerWidth(_44b)._outerHeight(h).css({marginLeft:-_44b/2+"px"});
_449.find(".switchbutton-on").css({width:(w-_44b/2)+"px",textIndent:(opts.reversed?"":"-")+_44b/2+"px"});
_449.find(".switchbutton-off").css({width:(w-_44b/2)+"px",textIndent:(opts.reversed?"-":"")+_44b/2+"px"});
opts.marginWidth=w-_44b;
_44d(_446,opts.checked,false);
if(!_44a){
_449.insertAfter(_446);
}
};
function _44e(_44f){
var _450=$.data(_44f,"switchbutton");
var opts=_450.options;
var _451=_450.switchbutton;
var _452=_451.find(".switchbutton-inner");
var on=_452.find(".switchbutton-on").html(opts.onText);
var off=_452.find(".switchbutton-off").html(opts.offText);
var _453=_452.find(".switchbutton-handle").html(opts.handleText);
if(opts.reversed){
off.prependTo(_452);
on.insertAfter(_453);
}else{
on.prependTo(_452);
off.insertAfter(_453);
}
_451.find(".switchbutton-value")._propAttr("checked",opts.checked);
_451.removeClass("switchbutton-disabled").addClass(opts.disabled?"switchbutton-disabled":"");
_451.removeClass("switchbutton-reversed").addClass(opts.reversed?"switchbutton-reversed":"");
_44d(_44f,opts.checked);
_454(_44f,opts.readonly);
$(_44f).switchbutton("setValue",opts.value);
};
function _44d(_455,_456,_457){
var _458=$.data(_455,"switchbutton");
var opts=_458.options;
opts.checked=_456;
var _459=_458.switchbutton.find(".switchbutton-inner");
var _45a=_459.find(".switchbutton-on");
var _45b=opts.reversed?(opts.checked?opts.marginWidth:0):(opts.checked?0:opts.marginWidth);
var dir=_45a.css("float").toLowerCase();
var css={};
css["margin-"+dir]=-_45b+"px";
_457?_459.animate(css,200):_459.css(css);
var _45c=_459.find(".switchbutton-value");
var ck=_45c.is(":checked");
$(_455).add(_45c)._propAttr("checked",opts.checked);
if(ck!=opts.checked){
opts.onChange.call(_455,opts.checked);
}
};
function _45d(_45e,_45f){
var _460=$.data(_45e,"switchbutton");
var opts=_460.options;
var _461=_460.switchbutton;
var _462=_461.find(".switchbutton-value");
if(_45f){
opts.disabled=true;
$(_45e).add(_462).attr("disabled","disabled");
_461.addClass("switchbutton-disabled");
}else{
opts.disabled=false;
$(_45e).add(_462).removeAttr("disabled");
_461.removeClass("switchbutton-disabled");
}
};
function _454(_463,mode){
var _464=$.data(_463,"switchbutton");
var opts=_464.options;
opts.readonly=mode==undefined?true:mode;
_464.switchbutton.removeClass("switchbutton-readonly").addClass(opts.readonly?"switchbutton-readonly":"");
};
function _465(_466){
var _467=$.data(_466,"switchbutton");
var opts=_467.options;
_467.switchbutton.unbind(".switchbutton").bind("click.switchbutton",function(){
if(!opts.disabled&&!opts.readonly){
_44d(_466,opts.checked?false:true,true);
}
});
};
$.fn.switchbutton=function(_468,_469){
if(typeof _468=="string"){
return $.fn.switchbutton.methods[_468](this,_469);
}
_468=_468||{};
return this.each(function(){
var _46a=$.data(this,"switchbutton");
if(_46a){
$.extend(_46a.options,_468);
}else{
_46a=$.data(this,"switchbutton",{options:$.extend({},$.fn.switchbutton.defaults,$.fn.switchbutton.parseOptions(this),_468),switchbutton:init(this)});
}
_46a.options.originalChecked=_46a.options.checked;
_44e(this);
_445(this);
_465(this);
});
};
$.fn.switchbutton.methods={options:function(jq){
var _46b=jq.data("switchbutton");
return $.extend(_46b.options,{value:_46b.switchbutton.find(".switchbutton-value").val()});
},resize:function(jq,_46c){
return jq.each(function(){
_445(this,_46c);
});
},enable:function(jq){
return jq.each(function(){
_45d(this,false);
});
},disable:function(jq){
return jq.each(function(){
_45d(this,true);
});
},readonly:function(jq,mode){
return jq.each(function(){
_454(this,mode);
});
},check:function(jq){
return jq.each(function(){
_44d(this,true);
});
},uncheck:function(jq){
return jq.each(function(){
_44d(this,false);
});
},clear:function(jq){
return jq.each(function(){
_44d(this,false);
});
},reset:function(jq){
return jq.each(function(){
var opts=$(this).switchbutton("options");
_44d(this,opts.originalChecked);
});
},setValue:function(jq,_46d){
return jq.each(function(){
$(this).val(_46d);
$.data(this,"switchbutton").switchbutton.find(".switchbutton-value").val(_46d);
});
}};
$.fn.switchbutton.parseOptions=function(_46e){
var t=$(_46e);
return $.extend({},$.parser.parseOptions(_46e,["onText","offText","handleText",{handleWidth:"number",reversed:"boolean"}]),{value:(t.val()||undefined),checked:(t.attr("checked")?true:undefined),disabled:(t.attr("disabled")?true:undefined),readonly:(t.attr("readonly")?true:undefined)});
};
$.fn.switchbutton.defaults={handleWidth:"auto",width:60,height:26,checked:false,disabled:false,readonly:false,reversed:false,onText:"ON",offText:"OFF",handleText:"",value:"on",onChange:function(_46f){
}};
})(jQuery);
(function($){
function init(_470){
$(_470).addClass("validatebox-text");
};
function _471(_472){
var _473=$.data(_472,"validatebox");
_473.validating=false;
if(_473.timer){
clearTimeout(_473.timer);
}
$(_472).tooltip("destroy");
$(_472).unbind();
$(_472).remove();
};
function _474(_475){
var opts=$.data(_475,"validatebox").options;
var box=$(_475);
box.unbind(".validatebox");
if(opts.novalidate||box.is(":disabled")){
return;
}
for(var _476 in opts.events){
$(_475).bind(_476+".validatebox",{target:_475},opts.events[_476]);
}
};
function _477(e){
var _478=e.data.target;
var _479=$.data(_478,"validatebox");
var box=$(_478);
if($(_478).attr("readonly")){
return;
}
_479.validating=true;
_479.value=undefined;
(function(){
if(_479.validating){
if(_479.value!=box.val()){
_479.value=box.val();
if(_479.timer){
clearTimeout(_479.timer);
}
_479.timer=setTimeout(function(){
$(_478).validatebox("validate");
},_479.options.delay);
}else{
_47a(_478);
}
setTimeout(arguments.callee,200);
}
})();
};
function _47b(e){
var _47c=e.data.target;
var _47d=$.data(_47c,"validatebox");
if(_47d.timer){
clearTimeout(_47d.timer);
_47d.timer=undefined;
}
_47d.validating=false;
_47e(_47c);
};
function _47f(e){
var _480=e.data.target;
if($(_480).hasClass("validatebox-invalid")){
_481(_480);
}
};
function _482(e){
var _483=e.data.target;
var _484=$.data(_483,"validatebox");
if(!_484.validating){
_47e(_483);
}
};
function _481(_485){
var _486=$.data(_485,"validatebox");
var opts=_486.options;
$(_485).tooltip($.extend({},opts.tipOptions,{content:_486.message,position:opts.tipPosition,deltaX:opts.deltaX})).tooltip("show");
_486.tip=true;
};
function _47a(_487){
var _488=$.data(_487,"validatebox");
if(_488&&_488.tip){
$(_487).tooltip("reposition");
}
};
function _47e(_489){
var _48a=$.data(_489,"validatebox");
_48a.tip=false;
$(_489).tooltip("hide");
};
function _48b(_48c){
var _48d=$.data(_48c,"validatebox");
var opts=_48d.options;
var box=$(_48c);
opts.onBeforeValidate.call(_48c);
var _48e=_48f();
opts.onValidate.call(_48c,_48e);
return _48e;
function _490(msg){
_48d.message=msg;
};
function _491(_492,_493){
var _494=box.val();
var _495=/([a-zA-Z_]+)(.*)/.exec(_492);
var rule=opts.rules[_495[1]];
if(rule&&_494){
var _496=_493||opts.validParams||eval(_495[2]);
if(!rule["validator"].call(_48c,_494,_496)){
box.addClass("validatebox-invalid");
var _497=rule["message"];
if(_496){
for(var i=0;i<_496.length;i++){
_497=_497.replace(new RegExp("\\{"+i+"\\}","g"),_496[i]);
}
}
_490(opts.invalidMessage||_497);
if(_48d.validating){
_481(_48c);
}
return false;
}
}
return true;
};
function _48f(){
box.removeClass("validatebox-invalid");
_47e(_48c);
if(opts.novalidate||box.is(":disabled")){
return true;
}
if(opts.required){
if(box.val()==""){
box.addClass("validatebox-invalid");
_490(opts.missingMessage);
if(_48d.validating){
_481(_48c);
}
return false;
}
}
if(opts.validType){
if($.isArray(opts.validType)){
for(var i=0;i<opts.validType.length;i++){
if(!_491(opts.validType[i])){
return false;
}
}
}else{
if(typeof opts.validType=="string"){
if(!_491(opts.validType)){
return false;
}
}else{
for(var _498 in opts.validType){
var _499=opts.validType[_498];
if(!_491(_498,_499)){
return false;
}
}
}
}
}
return true;
};
};
function _49a(_49b,_49c){
var opts=$.data(_49b,"validatebox").options;
if(_49c!=undefined){
opts.novalidate=_49c;
}
if(opts.novalidate){
$(_49b).removeClass("validatebox-invalid");
_47e(_49b);
}
_48b(_49b);
_474(_49b);
};
$.fn.validatebox=function(_49d,_49e){
if(typeof _49d=="string"){
return $.fn.validatebox.methods[_49d](this,_49e);
}
_49d=_49d||{};
return this.each(function(){
var _49f=$.data(this,"validatebox");
if(_49f){
$.extend(_49f.options,_49d);
}else{
init(this);
$.data(this,"validatebox",{options:$.extend({},$.fn.validatebox.defaults,$.fn.validatebox.parseOptions(this),_49d)});
}
_49a(this);
_48b(this);
});
};
$.fn.validatebox.methods={options:function(jq){
return $.data(jq[0],"validatebox").options;
},destroy:function(jq){
return jq.each(function(){
_471(this);
});
},validate:function(jq){
return jq.each(function(){
_48b(this);
});
},isValid:function(jq){
return _48b(jq[0]);
},enableValidation:function(jq){
return jq.each(function(){
_49a(this,false);
});
},disableValidation:function(jq){
return jq.each(function(){
_49a(this,true);
});
}};
$.fn.validatebox.parseOptions=function(_4a0){
var t=$(_4a0);
return $.extend({},$.parser.parseOptions(_4a0,["validType","missingMessage","invalidMessage","tipPosition",{delay:"number",deltaX:"number"}]),{required:(t.attr("required")?true:undefined),novalidate:(t.attr("novalidate")!=undefined?true:undefined)});
};
$.fn.validatebox.defaults={required:false,validType:null,validParams:null,delay:200,missingMessage:"This field is required.",invalidMessage:null,tipPosition:"right",deltaX:0,novalidate:false,events:{focus:_477,blur:_47b,mouseenter:_47f,mouseleave:_482,click:function(e){
var t=$(e.data.target);
if(!t.is(":focus")){
t.trigger("focus");
}
}},tipOptions:{showEvent:"none",hideEvent:"none",showDelay:0,hideDelay:0,zIndex:"",onShow:function(){
$(this).tooltip("tip").css({color:"#000",borderColor:"#CC9933",backgroundColor:"#FFFFCC"});
},onHide:function(){
$(this).tooltip("destroy");
}},rules:{email:{validator:function(_4a1){
return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(_4a1);
},message:"Please enter a valid email address."},url:{validator:function(_4a2){
return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(_4a2);
},message:"Please enter a valid URL."},length:{validator:function(_4a3,_4a4){
var len=$.trim(_4a3).length;
return len>=_4a4[0]&&len<=_4a4[1];
},message:"Please enter a value between {0} and {1}."},remote:{validator:function(_4a5,_4a6){
var data={};
data[_4a6[1]]=_4a5;
var _4a7=$.ajax({url:_4a6[0],dataType:"json",data:data,async:false,cache:false,type:"post"}).responseText;
return _4a7=="true";
},message:"Please fix this field."}},onBeforeValidate:function(){
},onValidate:function(_4a8){
}};
})(jQuery);
(function($){
function init(_4a9){
$(_4a9).addClass("textbox-f").hide();
var span=$("<span class=\"textbox\">"+"<input class=\"textbox-text\" autocomplete=\"off\">"+"<input type=\"hidden\" class=\"textbox-value\">"+"</span>").insertAfter(_4a9);
var name=$(_4a9).attr("name");
if(name){
span.find("input.textbox-value").attr("name",name);
$(_4a9).removeAttr("name").attr("textboxName",name);
}
return span;
};
function _4aa(_4ab){
var _4ac=$.data(_4ab,"textbox");
var opts=_4ac.options;
var tb=_4ac.textbox;
tb.find(".textbox-text").remove();
if(opts.multiline){
$("<textarea class=\"textbox-text\" autocomplete=\"off\"></textarea>").prependTo(tb);
}else{
$("<input type=\""+opts.type+"\" class=\"textbox-text\" autocomplete=\"off\">").prependTo(tb);
}
tb.find(".textbox-addon").remove();
var bb=opts.icons?$.extend(true,[],opts.icons):[];
if(opts.iconCls){
bb.push({iconCls:opts.iconCls,disabled:true});
}
if(bb.length){
var bc=$("<span class=\"textbox-addon\"></span>").prependTo(tb);
bc.addClass("textbox-addon-"+opts.iconAlign);
for(var i=0;i<bb.length;i++){
bc.append("<a href=\"javascript:void(0)\" class=\"textbox-icon "+bb[i].iconCls+"\" icon-index=\""+i+"\" tabindex=\"-1\"></a>");
}
}
tb.find(".textbox-button").remove();
if(opts.buttonText||opts.buttonIcon){
var btn=$("<a href=\"javascript:void(0)\" class=\"textbox-button\"></a>").prependTo(tb);
btn.addClass("textbox-button-"+opts.buttonAlign).linkbutton({text:opts.buttonText,iconCls:opts.buttonIcon});
}
_4ad(_4ab,opts.disabled);
_4ae(_4ab,opts.readonly);
};
function _4af(_4b0){
var tb=$.data(_4b0,"textbox").textbox;
tb.find(".textbox-text").validatebox("destroy");
tb.remove();
$(_4b0).remove();
};
function _4b1(_4b2,_4b3){
var _4b4=$.data(_4b2,"textbox");
var opts=_4b4.options;
var tb=_4b4.textbox;
var _4b5=tb.parent();
if(_4b3){
opts.width=_4b3;
}
if(isNaN(parseInt(opts.width))){
var c=$(_4b2).clone();
c.css("visibility","hidden");
c.insertAfter(_4b2);
opts.width=c.outerWidth();
c.remove();
}
var _4b6=tb.is(":visible");
if(!_4b6){
tb.appendTo("body");
}
var _4b7=tb.find(".textbox-text");
var btn=tb.find(".textbox-button");
var _4b8=tb.find(".textbox-addon");
var _4b9=_4b8.find(".textbox-icon");
tb._size(opts,_4b5);
btn.linkbutton("resize",{height:tb.height()});
btn.css({left:(opts.buttonAlign=="left"?0:""),right:(opts.buttonAlign=="right"?0:"")});
_4b8.css({left:(opts.iconAlign=="left"?(opts.buttonAlign=="left"?btn._outerWidth():0):""),right:(opts.iconAlign=="right"?(opts.buttonAlign=="right"?btn._outerWidth():0):"")});
_4b9.css({width:opts.iconWidth+"px",height:tb.height()+"px"});
_4b7.css({paddingLeft:(_4b2.style.paddingLeft||""),paddingRight:(_4b2.style.paddingRight||""),marginLeft:_4ba("left"),marginRight:_4ba("right")});
if(opts.multiline){
_4b7.css({paddingTop:(_4b2.style.paddingTop||""),paddingBottom:(_4b2.style.paddingBottom||"")});
_4b7._outerHeight(tb.height());
}else{
var _4bb=Math.floor((tb.height()-_4b7.height())/2);
_4b7.css({paddingTop:_4bb+"px",paddingBottom:_4bb+"px"});
}
_4b7._outerWidth(tb.width()-_4b9.length*opts.iconWidth-btn._outerWidth());
if(!_4b6){
tb.insertAfter(_4b2);
}
opts.onResize.call(_4b2,opts.width,opts.height);
function _4ba(_4bc){
return (opts.iconAlign==_4bc?_4b8._outerWidth():0)+(opts.buttonAlign==_4bc?btn._outerWidth():0);
};
};
function _4bd(_4be){
var opts=$(_4be).textbox("options");
var _4bf=$(_4be).textbox("textbox");
_4bf.validatebox($.extend({},opts,{deltaX:$(_4be).textbox("getTipX"),onBeforeValidate:function(){
var box=$(this);
if(!box.is(":focus")){
opts.oldInputValue=box.val();
box.val(opts.value);
}
},onValidate:function(_4c0){
var box=$(this);
if(opts.oldInputValue!=undefined){
box.val(opts.oldInputValue);
opts.oldInputValue=undefined;
}
var tb=box.parent();
if(_4c0){
tb.removeClass("textbox-invalid");
}else{
tb.addClass("textbox-invalid");
}
}}));
};
function _4c1(_4c2){
var _4c3=$.data(_4c2,"textbox");
var opts=_4c3.options;
var tb=_4c3.textbox;
var _4c4=tb.find(".textbox-text");
_4c4.attr("placeholder",opts.prompt);
_4c4.unbind(".textbox");
if(!opts.disabled&&!opts.readonly){
_4c4.bind("blur.textbox",function(e){
if(!tb.hasClass("textbox-focused")){
return;
}
opts.value=$(this).val();
if(opts.value==""){
$(this).val(opts.prompt).addClass("textbox-prompt");
}else{
$(this).removeClass("textbox-prompt");
}
tb.removeClass("textbox-focused");
}).bind("focus.textbox",function(e){
if(tb.hasClass("textbox-focused")){
return;
}
if($(this).val()!=opts.value){
$(this).val(opts.value);
}
$(this).removeClass("textbox-prompt");
tb.addClass("textbox-focused");
});
for(var _4c5 in opts.inputEvents){
_4c4.bind(_4c5+".textbox",{target:_4c2},opts.inputEvents[_4c5]);
}
}
var _4c6=tb.find(".textbox-addon");
_4c6.unbind().bind("click",{target:_4c2},function(e){
var icon=$(e.target).closest("a.textbox-icon:not(.textbox-icon-disabled)");
if(icon.length){
var _4c7=parseInt(icon.attr("icon-index"));
var conf=opts.icons[_4c7];
if(conf&&conf.handler){
conf.handler.call(icon[0],e);
opts.onClickIcon.call(_4c2,_4c7);
}
}
});
_4c6.find(".textbox-icon").each(function(_4c8){
var conf=opts.icons[_4c8];
var icon=$(this);
if(!conf||conf.disabled||opts.disabled||opts.readonly){
icon.addClass("textbox-icon-disabled");
}else{
icon.removeClass("textbox-icon-disabled");
}
});
var btn=tb.find(".textbox-button");
btn.unbind(".textbox").bind("click.textbox",function(){
if(!btn.linkbutton("options").disabled){
opts.onClickButton.call(_4c2);
}
});
btn.linkbutton((opts.disabled||opts.readonly)?"disable":"enable");
tb.unbind(".textbox").bind("_resize.textbox",function(e,_4c9){
if($(this).hasClass("easyui-fluid")||_4c9){
_4b1(_4c2);
}
return false;
});
};
function _4ad(_4ca,_4cb){
var _4cc=$.data(_4ca,"textbox");
var opts=_4cc.options;
var tb=_4cc.textbox;
if(_4cb){
opts.disabled=true;
$(_4ca).attr("disabled","disabled");
tb.addClass("textbox-disabled");
tb.find(".textbox-text,.textbox-value").attr("disabled","disabled");
}else{
opts.disabled=false;
tb.removeClass("textbox-disabled");
$(_4ca).removeAttr("disabled");
tb.find(".textbox-text,.textbox-value").removeAttr("disabled");
}
};
function _4ae(_4cd,mode){
var _4ce=$.data(_4cd,"textbox");
var opts=_4ce.options;
opts.readonly=mode==undefined?true:mode;
_4ce.textbox.removeClass("textbox-readonly").addClass(opts.readonly?"textbox-readonly":"");
var _4cf=_4ce.textbox.find(".textbox-text");
_4cf.removeAttr("readonly");
if(opts.readonly||!opts.editable){
_4cf.attr("readonly","readonly");
}
};
$.fn.textbox=function(_4d0,_4d1){
if(typeof _4d0=="string"){
var _4d2=$.fn.textbox.methods[_4d0];
if(_4d2){
return _4d2(this,_4d1);
}else{
return this.each(function(){
var _4d3=$(this).textbox("textbox");
_4d3.validatebox(_4d0,_4d1);
});
}
}
_4d0=_4d0||{};
return this.each(function(){
var _4d4=$.data(this,"textbox");
if(_4d4){
$.extend(_4d4.options,_4d0);
if(_4d0.value!=undefined){
_4d4.options.originalValue=_4d0.value;
}
}else{
_4d4=$.data(this,"textbox",{options:$.extend({},$.fn.textbox.defaults,$.fn.textbox.parseOptions(this),_4d0),textbox:init(this)});
_4d4.options.originalValue=_4d4.options.value;
}
_4aa(this);
_4c1(this);
_4b1(this);
_4bd(this);
$(this).textbox("initValue",_4d4.options.value);
});
};
$.fn.textbox.methods={options:function(jq){
return $.data(jq[0],"textbox").options;
},cloneFrom:function(jq,from){
return jq.each(function(){
var t=$(this);
if(t.data("textbox")){
return;
}
if(!$(from).data("textbox")){
$(from).textbox();
}
var name=t.attr("name")||"";
t.addClass("textbox-f").hide();
t.removeAttr("name").attr("textboxName",name);
var span=$(from).next().clone().insertAfter(t);
span.find("input.textbox-value").attr("name",name);
$.data(this,"textbox",{options:$.extend(true,{},$(from).textbox("options")),textbox:span});
var _4d5=$(from).textbox("button");
if(_4d5.length){
t.textbox("button").linkbutton($.extend(true,{},_4d5.linkbutton("options")));
}
_4c1(this);
_4bd(this);
});
},textbox:function(jq){
return $.data(jq[0],"textbox").textbox.find(".textbox-text");
},button:function(jq){
return $.data(jq[0],"textbox").textbox.find(".textbox-button");
},destroy:function(jq){
return jq.each(function(){
_4af(this);
});
},resize:function(jq,_4d6){
return jq.each(function(){
_4b1(this,_4d6);
});
},disable:function(jq){
return jq.each(function(){
_4ad(this,true);
_4c1(this);
});
},enable:function(jq){
return jq.each(function(){
_4ad(this,false);
_4c1(this);
});
},readonly:function(jq,mode){
return jq.each(function(){
_4ae(this,mode);
_4c1(this);
});
},isValid:function(jq){
return jq.textbox("textbox").validatebox("isValid");
},clear:function(jq){
return jq.each(function(){
$(this).textbox("setValue","");
});
},setText:function(jq,_4d7){
return jq.each(function(){
var opts=$(this).textbox("options");
var _4d8=$(this).textbox("textbox");
_4d7=_4d7==undefined?"":String(_4d7);
if($(this).textbox("getText")!=_4d7){
_4d8.val(_4d7);
}
opts.value=_4d7;
if(!_4d8.is(":focus")){
if(_4d7){
_4d8.removeClass("textbox-prompt");
}else{
_4d8.val(opts.prompt).addClass("textbox-prompt");
}
}
$(this).textbox("validate");
});
},initValue:function(jq,_4d9){
return jq.each(function(){
var _4da=$.data(this,"textbox");
_4da.options.value="";
$(this).textbox("setText",_4d9);
_4da.textbox.find(".textbox-value").val(_4d9);
$(this).val(_4d9);
});
},setValue:function(jq,_4db){
return jq.each(function(){
var opts=$.data(this,"textbox").options;
var _4dc=$(this).textbox("getValue");
$(this).textbox("initValue",_4db);
if(_4dc!=_4db){
opts.onChange.call(this,_4db,_4dc);
$(this).closest("form").trigger("_change",[this]);
}
});
},getText:function(jq){
var _4dd=jq.textbox("textbox");
if(_4dd.is(":focus")){
return _4dd.val();
}else{
return jq.textbox("options").value;
}
},getValue:function(jq){
return jq.data("textbox").textbox.find(".textbox-value").val();
},reset:function(jq){
return jq.each(function(){
var opts=$(this).textbox("options");
$(this).textbox("setValue",opts.originalValue);
});
},getIcon:function(jq,_4de){
return jq.data("textbox").textbox.find(".textbox-icon:eq("+_4de+")");
},getTipX:function(jq){
var _4df=jq.data("textbox");
var opts=_4df.options;
var tb=_4df.textbox;
var _4e0=tb.find(".textbox-text");
var _4e1=tb.find(".textbox-addon")._outerWidth();
var _4e2=tb.find(".textbox-button")._outerWidth();
if(opts.tipPosition=="right"){
return (opts.iconAlign=="right"?_4e1:0)+(opts.buttonAlign=="right"?_4e2:0)+1;
}else{
if(opts.tipPosition=="left"){
return (opts.iconAlign=="left"?-_4e1:0)+(opts.buttonAlign=="left"?-_4e2:0)-1;
}else{
return _4e1/2*(opts.iconAlign=="right"?1:-1);
}
}
}};
$.fn.textbox.parseOptions=function(_4e3){
var t=$(_4e3);
return $.extend({},$.fn.validatebox.parseOptions(_4e3),$.parser.parseOptions(_4e3,["prompt","iconCls","iconAlign","buttonText","buttonIcon","buttonAlign",{multiline:"boolean",editable:"boolean",iconWidth:"number"}]),{value:(t.val()||undefined),type:(t.attr("type")?t.attr("type"):undefined),disabled:(t.attr("disabled")?true:undefined),readonly:(t.attr("readonly")?true:undefined)});
};
$.fn.textbox.defaults=$.extend({},$.fn.validatebox.defaults,{width:"auto",height:22,prompt:"",value:"",type:"text",multiline:false,editable:true,disabled:false,readonly:false,icons:[],iconCls:null,iconAlign:"right",iconWidth:18,buttonText:"",buttonIcon:null,buttonAlign:"right",inputEvents:{blur:function(e){
var t=$(e.data.target);
var opts=t.textbox("options");
t.textbox("setValue",opts.value);
},keydown:function(e){
if(e.keyCode==13){
var t=$(e.data.target);
t.textbox("setValue",t.textbox("getText"));
}
}},onChange:function(_4e4,_4e5){
},onResize:function(_4e6,_4e7){
},onClickButton:function(){
},onClickIcon:function(_4e8){
}});
})(jQuery);
(function($){
var _4e9=0;
function _4ea(_4eb){
var _4ec=$.data(_4eb,"filebox");
var opts=_4ec.options;
var id="filebox_file_id_"+(++_4e9);
$(_4eb).addClass("filebox-f").textbox(opts);
$(_4eb).textbox("textbox").attr("readonly","readonly");
_4ec.filebox=$(_4eb).next().addClass("filebox");
_4ec.filebox.find(".textbox-value").remove();
opts.oldValue="";
var file=$("<input type=\"file\" class=\"textbox-value\">").appendTo(_4ec.filebox);
file.attr("id",id).attr("name",$(_4eb).attr("textboxName")||"");
file.change(function(){
$(_4eb).filebox("setText",this.value);
opts.onChange.call(_4eb,this.value,opts.oldValue);
opts.oldValue=this.value;
});
var btn=$(_4eb).filebox("button");
if(btn.length){
$("<label class=\"filebox-label\" for=\""+id+"\"></label>").appendTo(btn);
if(btn.linkbutton("options").disabled){
file.attr("disabled","disabled");
}else{
file.removeAttr("disabled");
}
}
};
$.fn.filebox=function(_4ed,_4ee){
if(typeof _4ed=="string"){
var _4ef=$.fn.filebox.methods[_4ed];
if(_4ef){
return _4ef(this,_4ee);
}else{
return this.textbox(_4ed,_4ee);
}
}
_4ed=_4ed||{};
return this.each(function(){
var _4f0=$.data(this,"filebox");
if(_4f0){
$.extend(_4f0.options,_4ed);
}else{
$.data(this,"filebox",{options:$.extend({},$.fn.filebox.defaults,$.fn.filebox.parseOptions(this),_4ed)});
}
_4ea(this);
});
};
$.fn.filebox.methods={options:function(jq){
var opts=jq.textbox("options");
return $.extend($.data(jq[0],"filebox").options,{width:opts.width,value:opts.value,originalValue:opts.originalValue,disabled:opts.disabled,readonly:opts.readonly});
}};
$.fn.filebox.parseOptions=function(_4f1){
return $.extend({},$.fn.textbox.parseOptions(_4f1),{});
};
$.fn.filebox.defaults=$.extend({},$.fn.textbox.defaults,{buttonIcon:null,buttonText:"Choose File",buttonAlign:"right",inputEvents:{}});
})(jQuery);
(function($){
function _4f2(_4f3){
var _4f4=$.data(_4f3,"searchbox");
var opts=_4f4.options;
var _4f5=$.extend(true,[],opts.icons);
_4f5.push({iconCls:"searchbox-button",handler:function(e){
var t=$(e.data.target);
var opts=t.searchbox("options");
opts.searcher.call(e.data.target,t.searchbox("getValue"),t.searchbox("getName"));
}});
_4f6();
var _4f7=_4f8();
$(_4f3).addClass("searchbox-f").textbox($.extend({},opts,{icons:_4f5,buttonText:(_4f7?_4f7.text:"")}));
$(_4f3).attr("searchboxName",$(_4f3).attr("textboxName"));
_4f4.searchbox=$(_4f3).next();
_4f4.searchbox.addClass("searchbox");
_4f9(_4f7);
function _4f6(){
if(opts.menu){
_4f4.menu=$(opts.menu).menu();
var _4fa=_4f4.menu.menu("options");
var _4fb=_4fa.onClick;
_4fa.onClick=function(item){
_4f9(item);
_4fb.call(this,item);
};
}else{
if(_4f4.menu){
_4f4.menu.menu("destroy");
}
_4f4.menu=null;
}
};
function _4f8(){
if(_4f4.menu){
var item=_4f4.menu.children("div.menu-item:first");
_4f4.menu.children("div.menu-item").each(function(){
var _4fc=$.extend({},$.parser.parseOptions(this),{selected:($(this).attr("selected")?true:undefined)});
if(_4fc.selected){
item=$(this);
return false;
}
});
return _4f4.menu.menu("getItem",item[0]);
}else{
return null;
}
};
function _4f9(item){
if(!item){
return;
}
$(_4f3).textbox("button").menubutton({text:item.text,iconCls:(item.iconCls||null),menu:_4f4.menu,menuAlign:opts.buttonAlign,plain:false});
_4f4.searchbox.find("input.textbox-value").attr("name",item.name||item.text);
$(_4f3).searchbox("resize");
};
};
$.fn.searchbox=function(_4fd,_4fe){
if(typeof _4fd=="string"){
var _4ff=$.fn.searchbox.methods[_4fd];
if(_4ff){
return _4ff(this,_4fe);
}else{
return this.textbox(_4fd,_4fe);
}
}
_4fd=_4fd||{};
return this.each(function(){
var _500=$.data(this,"searchbox");
if(_500){
$.extend(_500.options,_4fd);
}else{
$.data(this,"searchbox",{options:$.extend({},$.fn.searchbox.defaults,$.fn.searchbox.parseOptions(this),_4fd)});
}
_4f2(this);
});
};
$.fn.searchbox.methods={options:function(jq){
var opts=jq.textbox("options");
return $.extend($.data(jq[0],"searchbox").options,{width:opts.width,value:opts.value,originalValue:opts.originalValue,disabled:opts.disabled,readonly:opts.readonly});
},menu:function(jq){
return $.data(jq[0],"searchbox").menu;
},getName:function(jq){
return $.data(jq[0],"searchbox").searchbox.find("input.textbox-value").attr("name");
},selectName:function(jq,name){
return jq.each(function(){
var menu=$.data(this,"searchbox").menu;
if(menu){
menu.children("div.menu-item").each(function(){
var item=menu.menu("getItem",this);
if(item.name==name){
$(this).triggerHandler("click");
return false;
}
});
}
});
},destroy:function(jq){
return jq.each(function(){
var menu=$(this).searchbox("menu");
if(menu){
menu.menu("destroy");
}
$(this).textbox("destroy");
});
}};
$.fn.searchbox.parseOptions=function(_501){
var t=$(_501);
return $.extend({},$.fn.textbox.parseOptions(_501),$.parser.parseOptions(_501,["menu"]),{searcher:(t.attr("searcher")?eval(t.attr("searcher")):undefined)});
};
$.fn.searchbox.defaults=$.extend({},$.fn.textbox.defaults,{inputEvents:$.extend({},$.fn.textbox.defaults.inputEvents,{keydown:function(e){
if(e.keyCode==13){
e.preventDefault();
var t=$(e.data.target);
var opts=t.searchbox("options");
t.searchbox("setValue",$(this).val());
opts.searcher.call(e.data.target,t.searchbox("getValue"),t.searchbox("getName"));
return false;
}
}}),buttonAlign:"left",menu:null,searcher:function(_502,name){
}});
})(jQuery);
(function($){
function _503(_504,_505){
var opts=$.data(_504,"form").options;
$.extend(opts,_505||{});
var _506=$.extend({},opts.queryParams);
if(opts.onSubmit.call(_504,_506)==false){
return;
}
$(_504).find(".textbox-text:focus").blur();
var _507="easyui_frame_"+(new Date().getTime());
var _508=$("<iframe id="+_507+" name="+_507+"></iframe>").appendTo("body");
_508.attr("src",window.ActiveXObject?"javascript:false":"about:blank");
_508.css({position:"absolute",top:-1000,left:-1000});
_508.bind("load",cb);
_509(_506);
function _509(_50a){
var form=$(_504);
if(opts.url){
form.attr("action",opts.url);
}
var t=form.attr("target"),a=form.attr("action");
form.attr("target",_507);
var _50b=$();
try{
for(var n in _50a){
var _50c=$("<input type=\"hidden\" name=\""+n+"\">").val(_50a[n]).appendTo(form);
_50b=_50b.add(_50c);
}
_50d();
form[0].submit();
}
finally{
form.attr("action",a);
t?form.attr("target",t):form.removeAttr("target");
_50b.remove();
}
};
function _50d(){
var f=$("#"+_507);
if(!f.length){
return;
}
try{
var s=f.contents()[0].readyState;
if(s&&s.toLowerCase()=="uninitialized"){
setTimeout(_50d,100);
}
}
catch(e){
cb();
}
};
var _50e=10;
function cb(){
var f=$("#"+_507);
if(!f.length){
return;
}
f.unbind();
var data="";
try{
var body=f.contents().find("body");
data=body.html();
if(data==""){
if(--_50e){
setTimeout(cb,100);
return;
}
}
var ta=body.find(">textarea");
if(ta.length){
data=ta.val();
}else{
var pre=body.find(">pre");
if(pre.length){
data=pre.html();
}
}
}
catch(e){
}
opts.success(data);
setTimeout(function(){
f.unbind();
f.remove();
},100);
};
};
function load(_50f,data){
var opts=$.data(_50f,"form").options;
if(typeof data=="string"){
var _510={};
if(opts.onBeforeLoad.call(_50f,_510)==false){
return;
}
$.ajax({url:data,data:_510,dataType:"json",success:function(data){
_511(data);
},error:function(){
opts.onLoadError.apply(_50f,arguments);
}});
}else{
_511(data);
}
function _511(data){
var form=$(_50f);
for(var name in data){
var val=data[name];
if(!_512(name,val)){
if(!_513(name,val)){
form.find("input[name=\""+name+"\"]").val(val);
form.find("textarea[name=\""+name+"\"]").val(val);
form.find("select[name=\""+name+"\"]").val(val);
}
}
}
opts.onLoadSuccess.call(_50f,data);
form.form("validate");
};
function _512(name,val){
var cc=$(_50f).find("[switchbuttonName=\""+name+"\"]");
if(cc.length){
cc.switchbutton("uncheck");
cc.each(function(){
if(_514($(this).switchbutton("options").value,val)){
$(this).switchbutton("check");
}
});
return true;
}
cc=$(_50f).find("input[name=\""+name+"\"][type=radio], input[name=\""+name+"\"][type=checkbox]");
if(cc.length){
cc._propAttr("checked",false);
cc.each(function(){
if(_514($(this).val(),val)){
$(this)._propAttr("checked",true);
}
});
return true;
}
return false;
};
function _514(v,val){
if(v==String(val)||$.inArray(v,$.isArray(val)?val:[val])>=0){
return true;
}else{
return false;
}
};
function _513(name,val){
var _515=$(_50f).find("[textboxName=\""+name+"\"],[sliderName=\""+name+"\"]");
if(_515.length){
for(var i=0;i<opts.fieldTypes.length;i++){
var type=opts.fieldTypes[i];
var _516=_515.data(type);
if(_516){
if(_516.options.multiple||_516.options.range){
_515[type]("setValues",val);
}else{
_515[type]("setValue",val);
}
return true;
}
}
}
return false;
};
};
function _517(_518){
$("input,select,textarea",_518).each(function(){
var t=this.type,tag=this.tagName.toLowerCase();
if(t=="text"||t=="hidden"||t=="password"||tag=="textarea"){
this.value="";
}else{
if(t=="file"){
var file=$(this);
if(!file.hasClass("textbox-value")){
var _519=file.clone().val("");
_519.insertAfter(file);
if(file.data("validatebox")){
file.validatebox("destroy");
_519.validatebox();
}else{
file.remove();
}
}
}else{
if(t=="checkbox"||t=="radio"){
this.checked=false;
}else{
if(tag=="select"){
this.selectedIndex=-1;
}
}
}
}
});
var form=$(_518);
var opts=$.data(_518,"form").options;
for(var i=opts.fieldTypes.length-1;i>=0;i--){
var type=opts.fieldTypes[i];
var _51a=form.find("."+type+"-f");
if(_51a.length&&_51a[type]){
_51a[type]("clear");
}
}
form.form("validate");
};
function _51b(_51c){
_51c.reset();
var form=$(_51c);
var opts=$.data(_51c,"form").options;
for(var i=opts.fieldTypes.length-1;i>=0;i--){
var type=opts.fieldTypes[i];
var _51d=form.find("."+type+"-f");
if(_51d.length&&_51d[type]){
_51d[type]("reset");
}
}
form.form("validate");
};
function _51e(_51f){
var _520=$.data(_51f,"form").options;
$(_51f).unbind(".form");
if(_520.ajax){
$(_51f).bind("submit.form",function(){
setTimeout(function(){
_503(_51f,_520);
},0);
return false;
});
}
$(_51f).bind("_change.form",function(e,t){
_520.onChange.call(this,t);
}).bind("change.form",function(e){
var t=e.target;
if(!$(t).hasClass("textbox-text")){
_520.onChange.call(this,t);
}
});
_521(_51f,_520.novalidate);
};
function _522(_523,_524){
_524=_524||{};
var _525=$.data(_523,"form");
if(_525){
$.extend(_525.options,_524);
}else{
$.data(_523,"form",{options:$.extend({},$.fn.form.defaults,$.fn.form.parseOptions(_523),_524)});
}
};
function _526(_527){
if($.fn.validatebox){
var t=$(_527);
t.find(".validatebox-text:not(:disabled)").validatebox("validate");
var _528=t.find(".validatebox-invalid");
_528.filter(":not(:disabled):first").focus();
return _528.length==0;
}
return true;
};
function _521(_529,_52a){
var opts=$.data(_529,"form").options;
opts.novalidate=_52a;
$(_529).find(".validatebox-text:not(:disabled)").validatebox(_52a?"disableValidation":"enableValidation");
};
$.fn.form=function(_52b,_52c){
if(typeof _52b=="string"){
this.each(function(){
_522(this);
});
return $.fn.form.methods[_52b](this,_52c);
}
return this.each(function(){
_522(this,_52b);
_51e(this);
});
};
$.fn.form.methods={options:function(jq){
return $.data(jq[0],"form").options;
},submit:function(jq,_52d){
return jq.each(function(){
_503(this,_52d);
});
},load:function(jq,data){
return jq.each(function(){
load(this,data);
});
},clear:function(jq){
return jq.each(function(){
_517(this);
});
},reset:function(jq){
return jq.each(function(){
_51b(this);
});
},validate:function(jq){
return _526(jq[0]);
},disableValidation:function(jq){
return jq.each(function(){
_521(this,true);
});
},enableValidation:function(jq){
return jq.each(function(){
_521(this,false);
});
}};
$.fn.form.parseOptions=function(_52e){
var t=$(_52e);
return $.extend({},$.parser.parseOptions(_52e,[{ajax:"boolean"}]),{url:(t.attr("action")?t.attr("action"):undefined)});
};
$.fn.form.defaults={fieldTypes:["combobox","combotree","combogrid","datetimebox","datebox","combo","datetimespinner","timespinner","numberspinner","spinner","slider","searchbox","numberbox","textbox","switchbutton"],novalidate:false,ajax:true,url:null,queryParams:{},onSubmit:function(_52f){
return $(this).form("validate");
},success:function(data){
},onBeforeLoad:function(_530){
},onLoadSuccess:function(data){
},onLoadError:function(){
},onChange:function(_531){
}};
})(jQuery);
(function($){
function _532(_533){
var _534=$.data(_533,"numberbox");
var opts=_534.options;
$(_533).addClass("numberbox-f").textbox(opts);
$(_533).textbox("textbox").css({imeMode:"disabled"});
$(_533).attr("numberboxName",$(_533).attr("textboxName"));
_534.numberbox=$(_533).next();
_534.numberbox.addClass("numberbox");
var _535=opts.parser.call(_533,opts.value);
var _536=opts.formatter.call(_533,_535);
$(_533).numberbox("initValue",_535).numberbox("setText",_536);
};
function _537(_538,_539){
var _53a=$.data(_538,"numberbox");
var opts=_53a.options;
var _539=opts.parser.call(_538,_539);
var text=opts.formatter.call(_538,_539);
opts.value=_539;
$(_538).textbox("setText",text).textbox("setValue",_539);
text=opts.formatter.call(_538,$(_538).textbox("getValue"));
$(_538).textbox("setText",text);
};
$.fn.numberbox=function(_53b,_53c){
if(typeof _53b=="string"){
var _53d=$.fn.numberbox.methods[_53b];
if(_53d){
return _53d(this,_53c);
}else{
return this.textbox(_53b,_53c);
}
}
_53b=_53b||{};
return this.each(function(){
var _53e=$.data(this,"numberbox");
if(_53e){
$.extend(_53e.options,_53b);
}else{
_53e=$.data(this,"numberbox",{options:$.extend({},$.fn.numberbox.defaults,$.fn.numberbox.parseOptions(this),_53b)});
}
_532(this);
});
};
$.fn.numberbox.methods={options:function(jq){
var opts=jq.data("textbox")?jq.textbox("options"):{};
return $.extend($.data(jq[0],"numberbox").options,{width:opts.width,originalValue:opts.originalValue,disabled:opts.disabled,readonly:opts.readonly});
},fix:function(jq){
return jq.each(function(){
$(this).numberbox("setValue",$(this).numberbox("getText"));
});
},setValue:function(jq,_53f){
return jq.each(function(){
_537(this,_53f);
});
},clear:function(jq){
return jq.each(function(){
$(this).textbox("clear");
$(this).numberbox("options").value="";
});
},reset:function(jq){
return jq.each(function(){
$(this).textbox("reset");
$(this).numberbox("setValue",$(this).numberbox("getValue"));
});
}};
$.fn.numberbox.parseOptions=function(_540){
var t=$(_540);
return $.extend({},$.fn.textbox.parseOptions(_540),$.parser.parseOptions(_540,["decimalSeparator","groupSeparator","suffix",{min:"number",max:"number",precision:"number"}]),{prefix:(t.attr("prefix")?t.attr("prefix"):undefined)});
};
$.fn.numberbox.defaults=$.extend({},$.fn.textbox.defaults,{inputEvents:{keypress:function(e){
var _541=e.data.target;
var opts=$(_541).numberbox("options");
return opts.filter.call(_541,e);
},blur:function(e){
var _542=e.data.target;
$(_542).numberbox("setValue",$(_542).numberbox("getText"));
},keydown:function(e){
if(e.keyCode==13){
var _543=e.data.target;
$(_543).numberbox("setValue",$(_543).numberbox("getText"));
}
}},min:null,max:null,precision:0,decimalSeparator:".",groupSeparator:"",prefix:"",suffix:"",filter:function(e){
var opts=$(this).numberbox("options");
var s=$(this).numberbox("getText");
if(e.which==13){
return true;
}
if(e.which==45){
return (s.indexOf("-")==-1?true:false);
}
var c=String.fromCharCode(e.which);
if(c==opts.decimalSeparator){
return (s.indexOf(c)==-1?true:false);
}else{
if(c==opts.groupSeparator){
return true;
}else{
if((e.which>=48&&e.which<=57&&e.ctrlKey==false&&e.shiftKey==false)||e.which==0||e.which==8){
return true;
}else{
if(e.ctrlKey==true&&(e.which==99||e.which==118)){
return true;
}else{
return false;
}
}
}
}
},formatter:function(_544){
if(!_544){
return _544;
}
_544=_544+"";
var opts=$(this).numberbox("options");
var s1=_544,s2="";
var dpos=_544.indexOf(".");
if(dpos>=0){
s1=_544.substring(0,dpos);
s2=_544.substring(dpos+1,_544.length);
}
if(opts.groupSeparator){
var p=/(\d+)(\d{3})/;
while(p.test(s1)){
s1=s1.replace(p,"$1"+opts.groupSeparator+"$2");
}
}
if(s2){
return opts.prefix+s1+opts.decimalSeparator+s2+opts.suffix;
}else{
return opts.prefix+s1+opts.suffix;
}
},parser:function(s){
s=s+"";
var opts=$(this).numberbox("options");
if(parseFloat(s)!=s){
if(opts.prefix){
s=$.trim(s.replace(new RegExp("\\"+$.trim(opts.prefix),"g"),""));
}
if(opts.suffix){
s=$.trim(s.replace(new RegExp("\\"+$.trim(opts.suffix),"g"),""));
}
if(opts.groupSeparator){
s=$.trim(s.replace(new RegExp("\\"+opts.groupSeparator,"g"),""));
}
if(opts.decimalSeparator){
s=$.trim(s.replace(new RegExp("\\"+opts.decimalSeparator,"g"),"."));
}
s=s.replace(/\s/g,"");
}
var val=parseFloat(s).toFixed(opts.precision);
if(isNaN(val)){
val="";
}else{
if(typeof (opts.min)=="number"&&val<opts.min){
val=opts.min.toFixed(opts.precision);
}else{
if(typeof (opts.max)=="number"&&val>opts.max){
val=opts.max.toFixed(opts.precision);
}
}
}
return val;
}});
})(jQuery);
(function($){
function _545(_546,_547){
var opts=$.data(_546,"calendar").options;
var t=$(_546);
if(_547){
$.extend(opts,{width:_547.width,height:_547.height});
}
t._size(opts,t.parent());
t.find(".calendar-body")._outerHeight(t.height()-t.find(".calendar-header")._outerHeight());
if(t.find(".calendar-menu").is(":visible")){
_548(_546);
}
};
function init(_549){
$(_549).addClass("calendar").html("<div class=\"calendar-header\">"+"<div class=\"calendar-nav calendar-prevmonth\"></div>"+"<div class=\"calendar-nav calendar-nextmonth\"></div>"+"<div class=\"calendar-nav calendar-prevyear\"></div>"+"<div class=\"calendar-nav calendar-nextyear\"></div>"+"<div class=\"calendar-title\">"+"<span class=\"calendar-text\"></span>"+"</div>"+"</div>"+"<div class=\"calendar-body\">"+"<div class=\"calendar-menu\">"+"<div class=\"calendar-menu-year-inner\">"+"<span class=\"calendar-nav calendar-menu-prev\"></span>"+"<span><input class=\"calendar-menu-year\" type=\"text\"></input></span>"+"<span class=\"calendar-nav calendar-menu-next\"></span>"+"</div>"+"<div class=\"calendar-menu-month-inner\">"+"</div>"+"</div>"+"</div>");
$(_549).bind("_resize",function(e,_54a){
if($(this).hasClass("easyui-fluid")||_54a){
_545(_549);
}
return false;
});
};
function _54b(_54c){
var opts=$.data(_54c,"calendar").options;
var menu=$(_54c).find(".calendar-menu");
menu.find(".calendar-menu-year").unbind(".calendar").bind("keypress.calendar",function(e){
if(e.keyCode==13){
_54d(true);
}
});
$(_54c).unbind(".calendar").bind("mouseover.calendar",function(e){
var t=_54e(e.target);
if(t.hasClass("calendar-nav")||t.hasClass("calendar-text")||(t.hasClass("calendar-day")&&!t.hasClass("calendar-disabled"))){
t.addClass("calendar-nav-hover");
}
}).bind("mouseout.calendar",function(e){
var t=_54e(e.target);
if(t.hasClass("calendar-nav")||t.hasClass("calendar-text")||(t.hasClass("calendar-day")&&!t.hasClass("calendar-disabled"))){
t.removeClass("calendar-nav-hover");
}
}).bind("click.calendar",function(e){
var t=_54e(e.target);
if(t.hasClass("calendar-menu-next")||t.hasClass("calendar-nextyear")){
_54f(1);
}else{
if(t.hasClass("calendar-menu-prev")||t.hasClass("calendar-prevyear")){
_54f(-1);
}else{
if(t.hasClass("calendar-menu-month")){
menu.find(".calendar-selected").removeClass("calendar-selected");
t.addClass("calendar-selected");
_54d(true);
}else{
if(t.hasClass("calendar-prevmonth")){
_550(-1);
}else{
if(t.hasClass("calendar-nextmonth")){
_550(1);
}else{
if(t.hasClass("calendar-text")){
if(menu.is(":visible")){
menu.hide();
}else{
_548(_54c);
}
}else{
if(t.hasClass("calendar-day")){
if(t.hasClass("calendar-disabled")){
return;
}
var _551=opts.current;
t.closest("div.calendar-body").find(".calendar-selected").removeClass("calendar-selected");
t.addClass("calendar-selected");
var _552=t.attr("abbr").split(",");
var y=parseInt(_552[0]);
var m=parseInt(_552[1]);
var d=parseInt(_552[2]);
opts.current=new Date(y,m-1,d);
opts.onSelect.call(_54c,opts.current);
if(!_551||_551.getTime()!=opts.current.getTime()){
opts.onChange.call(_54c,opts.current,_551);
}
if(opts.year!=y||opts.month!=m){
opts.year=y;
opts.month=m;
show(_54c);
}
}
}
}
}
}
}
}
});
function _54e(t){
var day=$(t).closest(".calendar-day");
if(day.length){
return day;
}else{
return $(t);
}
};
function _54d(_553){
var menu=$(_54c).find(".calendar-menu");
var year=menu.find(".calendar-menu-year").val();
var _554=menu.find(".calendar-selected").attr("abbr");
if(!isNaN(year)){
opts.year=parseInt(year);
opts.month=parseInt(_554);
show(_54c);
}
if(_553){
menu.hide();
}
};
function _54f(_555){
opts.year+=_555;
show(_54c);
menu.find(".calendar-menu-year").val(opts.year);
};
function _550(_556){
opts.month+=_556;
if(opts.month>12){
opts.year++;
opts.month=1;
}else{
if(opts.month<1){
opts.year--;
opts.month=12;
}
}
show(_54c);
menu.find("td.calendar-selected").removeClass("calendar-selected");
menu.find("td:eq("+(opts.month-1)+")").addClass("calendar-selected");
};
};
function _548(_557){
var opts=$.data(_557,"calendar").options;
$(_557).find(".calendar-menu").show();
if($(_557).find(".calendar-menu-month-inner").is(":empty")){
$(_557).find(".calendar-menu-month-inner").empty();
var t=$("<table class=\"calendar-mtable\"></table>").appendTo($(_557).find(".calendar-menu-month-inner"));
var idx=0;
for(var i=0;i<3;i++){
var tr=$("<tr></tr>").appendTo(t);
for(var j=0;j<4;j++){
$("<td class=\"calendar-nav calendar-menu-month\"></td>").html(opts.months[idx++]).attr("abbr",idx).appendTo(tr);
}
}
}
var body=$(_557).find(".calendar-body");
var sele=$(_557).find(".calendar-menu");
var _558=sele.find(".calendar-menu-year-inner");
var _559=sele.find(".calendar-menu-month-inner");
_558.find("input").val(opts.year).focus();
_559.find("td.calendar-selected").removeClass("calendar-selected");
_559.find("td:eq("+(opts.month-1)+")").addClass("calendar-selected");
sele._outerWidth(body._outerWidth());
sele._outerHeight(body._outerHeight());
_559._outerHeight(sele.height()-_558._outerHeight());
};
function _55a(_55b,year,_55c){
var opts=$.data(_55b,"calendar").options;
var _55d=[];
var _55e=new Date(year,_55c,0).getDate();
for(var i=1;i<=_55e;i++){
_55d.push([year,_55c,i]);
}
var _55f=[],week=[];
var _560=-1;
while(_55d.length>0){
var date=_55d.shift();
week.push(date);
var day=new Date(date[0],date[1]-1,date[2]).getDay();
if(_560==day){
day=0;
}else{
if(day==(opts.firstDay==0?7:opts.firstDay)-1){
_55f.push(week);
week=[];
}
}
_560=day;
}
if(week.length){
_55f.push(week);
}
var _561=_55f[0];
if(_561.length<7){
while(_561.length<7){
var _562=_561[0];
var date=new Date(_562[0],_562[1]-1,_562[2]-1);
_561.unshift([date.getFullYear(),date.getMonth()+1,date.getDate()]);
}
}else{
var _562=_561[0];
var week=[];
for(var i=1;i<=7;i++){
var date=new Date(_562[0],_562[1]-1,_562[2]-i);
week.unshift([date.getFullYear(),date.getMonth()+1,date.getDate()]);
}
_55f.unshift(week);
}
var _563=_55f[_55f.length-1];
while(_563.length<7){
var _564=_563[_563.length-1];
var date=new Date(_564[0],_564[1]-1,_564[2]+1);
_563.push([date.getFullYear(),date.getMonth()+1,date.getDate()]);
}
if(_55f.length<6){
var _564=_563[_563.length-1];
var week=[];
for(var i=1;i<=7;i++){
var date=new Date(_564[0],_564[1]-1,_564[2]+i);
week.push([date.getFullYear(),date.getMonth()+1,date.getDate()]);
}
_55f.push(week);
}
return _55f;
};
function show(_565){
var opts=$.data(_565,"calendar").options;
if(opts.current&&!opts.validator.call(_565,opts.current)){
opts.current=null;
}
var now=new Date();
var _566=now.getFullYear()+","+(now.getMonth()+1)+","+now.getDate();
var _567=opts.current?(opts.current.getFullYear()+","+(opts.current.getMonth()+1)+","+opts.current.getDate()):"";
var _568=6-opts.firstDay;
var _569=_568+1;
if(_568>=7){
_568-=7;
}
if(_569>=7){
_569-=7;
}
$(_565).find(".calendar-title span").html(opts.months[opts.month-1]+" "+opts.year);
var body=$(_565).find("div.calendar-body");
body.children("table").remove();
var data=["<table class=\"calendar-dtable\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">"];
data.push("<thead><tr>");
for(var i=opts.firstDay;i<opts.weeks.length;i++){
data.push("<th>"+opts.weeks[i]+"</th>");
}
for(var i=0;i<opts.firstDay;i++){
data.push("<th>"+opts.weeks[i]+"</th>");
}
data.push("</tr></thead>");
data.push("<tbody>");
var _56a=_55a(_565,opts.year,opts.month);
for(var i=0;i<_56a.length;i++){
var week=_56a[i];
var cls="";
if(i==0){
cls="calendar-first";
}else{
if(i==_56a.length-1){
cls="calendar-last";
}
}
data.push("<tr class=\""+cls+"\">");
for(var j=0;j<week.length;j++){
var day=week[j];
var s=day[0]+","+day[1]+","+day[2];
var _56b=new Date(day[0],parseInt(day[1])-1,day[2]);
var d=opts.formatter.call(_565,_56b);
var css=opts.styler.call(_565,_56b);
var _56c="";
var _56d="";
if(typeof css=="string"){
_56d=css;
}else{
if(css){
_56c=css["class"]||"";
_56d=css["style"]||"";
}
}
var cls="calendar-day";
if(!(opts.year==day[0]&&opts.month==day[1])){
cls+=" calendar-other-month";
}
if(s==_566){
cls+=" calendar-today";
}
if(s==_567){
cls+=" calendar-selected";
}
if(j==_568){
cls+=" calendar-saturday";
}else{
if(j==_569){
cls+=" calendar-sunday";
}
}
if(j==0){
cls+=" calendar-first";
}else{
if(j==week.length-1){
cls+=" calendar-last";
}
}
cls+=" "+_56c;
if(!opts.validator.call(_565,_56b)){
cls+=" calendar-disabled";
}
data.push("<td class=\""+cls+"\" abbr=\""+s+"\" style=\""+_56d+"\">"+d+"</td>");
}
data.push("</tr>");
}
data.push("</tbody>");
data.push("</table>");
body.append(data.join(""));
body.children("table.calendar-dtable").prependTo(body);
opts.onNavigate.call(_565,opts.year,opts.month);
};
$.fn.calendar=function(_56e,_56f){
if(typeof _56e=="string"){
return $.fn.calendar.methods[_56e](this,_56f);
}
_56e=_56e||{};
return this.each(function(){
var _570=$.data(this,"calendar");
if(_570){
$.extend(_570.options,_56e);
}else{
_570=$.data(this,"calendar",{options:$.extend({},$.fn.calendar.defaults,$.fn.calendar.parseOptions(this),_56e)});
init(this);
}
if(_570.options.border==false){
$(this).addClass("calendar-noborder");
}
_545(this);
_54b(this);
show(this);
$(this).find("div.calendar-menu").hide();
});
};
$.fn.calendar.methods={options:function(jq){
return $.data(jq[0],"calendar").options;
},resize:function(jq,_571){
return jq.each(function(){
_545(this,_571);
});
},moveTo:function(jq,date){
return jq.each(function(){
if(!date){
var now=new Date();
$(this).calendar({year:now.getFullYear(),month:now.getMonth()+1,current:date});
return;
}
var opts=$(this).calendar("options");
if(opts.validator.call(this,date)){
var _572=opts.current;
$(this).calendar({year:date.getFullYear(),month:date.getMonth()+1,current:date});
if(!_572||_572.getTime()!=date.getTime()){
opts.onChange.call(this,opts.current,_572);
}
}
});
}};
$.fn.calendar.parseOptions=function(_573){
var t=$(_573);
return $.extend({},$.parser.parseOptions(_573,[{firstDay:"number",fit:"boolean",border:"boolean"}]));
};
$.fn.calendar.defaults={width:180,height:180,fit:false,border:true,firstDay:0,weeks:["S","M","T","W","T","F","S"],months:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],year:new Date().getFullYear(),month:new Date().getMonth()+1,current:(function(){
var d=new Date();
return new Date(d.getFullYear(),d.getMonth(),d.getDate());
})(),formatter:function(date){
return date.getDate();
},styler:function(date){
return "";
},validator:function(date){
return true;
},onSelect:function(date){
},onChange:function(_574,_575){
},onNavigate:function(year,_576){
}};
})(jQuery);
(function($){
function _577(_578){
var _579=$.data(_578,"spinner");
var opts=_579.options;
var _57a=$.extend(true,[],opts.icons);
_57a.push({iconCls:"spinner-arrow",handler:function(e){
_57b(e);
}});
$(_578).addClass("spinner-f").textbox($.extend({},opts,{icons:_57a}));
var _57c=$(_578).textbox("getIcon",_57a.length-1);
_57c.append("<a href=\"javascript:void(0)\" class=\"spinner-arrow-up\" tabindex=\"-1\"></a>");
_57c.append("<a href=\"javascript:void(0)\" class=\"spinner-arrow-down\" tabindex=\"-1\"></a>");
$(_578).attr("spinnerName",$(_578).attr("textboxName"));
_579.spinner=$(_578).next();
_579.spinner.addClass("spinner");
};
function _57b(e){
var _57d=e.data.target;
var opts=$(_57d).spinner("options");
var up=$(e.target).closest("a.spinner-arrow-up");
if(up.length){
opts.spin.call(_57d,false);
opts.onSpinUp.call(_57d);
$(_57d).spinner("validate");
}
var down=$(e.target).closest("a.spinner-arrow-down");
if(down.length){
opts.spin.call(_57d,true);
opts.onSpinDown.call(_57d);
$(_57d).spinner("validate");
}
};
$.fn.spinner=function(_57e,_57f){
if(typeof _57e=="string"){
var _580=$.fn.spinner.methods[_57e];
if(_580){
return _580(this,_57f);
}else{
return this.textbox(_57e,_57f);
}
}
_57e=_57e||{};
return this.each(function(){
var _581=$.data(this,"spinner");
if(_581){
$.extend(_581.options,_57e);
}else{
_581=$.data(this,"spinner",{options:$.extend({},$.fn.spinner.defaults,$.fn.spinner.parseOptions(this),_57e)});
}
_577(this);
});
};
$.fn.spinner.methods={options:function(jq){
var opts=jq.textbox("options");
return $.extend($.data(jq[0],"spinner").options,{width:opts.width,value:opts.value,originalValue:opts.originalValue,disabled:opts.disabled,readonly:opts.readonly});
}};
$.fn.spinner.parseOptions=function(_582){
return $.extend({},$.fn.textbox.parseOptions(_582),$.parser.parseOptions(_582,["min","max",{increment:"number"}]));
};
$.fn.spinner.defaults=$.extend({},$.fn.textbox.defaults,{min:null,max:null,increment:1,spin:function(down){
},onSpinUp:function(){
},onSpinDown:function(){
}});
})(jQuery);
(function($){
function _583(_584){
$(_584).addClass("numberspinner-f");
var opts=$.data(_584,"numberspinner").options;
$(_584).numberbox(opts).spinner(opts);
$(_584).numberbox("setValue",opts.value);
};
function _585(_586,down){
var opts=$.data(_586,"numberspinner").options;
var v=parseFloat($(_586).numberbox("getValue")||opts.value)||0;
if(down){
v-=opts.increment;
}else{
v+=opts.increment;
}
$(_586).numberbox("setValue",v);
};
$.fn.numberspinner=function(_587,_588){
if(typeof _587=="string"){
var _589=$.fn.numberspinner.methods[_587];
if(_589){
return _589(this,_588);
}else{
return this.numberbox(_587,_588);
}
}
_587=_587||{};
return this.each(function(){
var _58a=$.data(this,"numberspinner");
if(_58a){
$.extend(_58a.options,_587);
}else{
$.data(this,"numberspinner",{options:$.extend({},$.fn.numberspinner.defaults,$.fn.numberspinner.parseOptions(this),_587)});
}
_583(this);
});
};
$.fn.numberspinner.methods={options:function(jq){
var opts=jq.numberbox("options");
return $.extend($.data(jq[0],"numberspinner").options,{width:opts.width,value:opts.value,originalValue:opts.originalValue,disabled:opts.disabled,readonly:opts.readonly});
}};
$.fn.numberspinner.parseOptions=function(_58b){
return $.extend({},$.fn.spinner.parseOptions(_58b),$.fn.numberbox.parseOptions(_58b),{});
};
$.fn.numberspinner.defaults=$.extend({},$.fn.spinner.defaults,$.fn.numberbox.defaults,{spin:function(down){
_585(this,down);
}});
})(jQuery);
(function($){
function _58c(_58d){
var _58e=0;
if(typeof _58d.selectionStart=="number"){
_58e=_58d.selectionStart;
}else{
if(_58d.createTextRange){
var _58f=_58d.createTextRange();
var s=document.selection.createRange();
s.setEndPoint("StartToStart",_58f);
_58e=s.text.length;
}
}
return _58e;
};
function _590(_591,_592,end){
if(_591.setSelectionRange){
_591.setSelectionRange(_592,end);
}else{
if(_591.createTextRange){
var _593=_591.createTextRange();
_593.collapse();
_593.moveEnd("character",end);
_593.moveStart("character",_592);
_593.select();
}
}
};
function _594(_595){
var opts=$.data(_595,"timespinner").options;
$(_595).addClass("timespinner-f").spinner(opts);
var _596=opts.formatter.call(_595,opts.parser.call(_595,opts.value));
$(_595).timespinner("initValue",_596);
};
function _597(e){
var _598=e.data.target;
var opts=$.data(_598,"timespinner").options;
var _599=_58c(this);
for(var i=0;i<opts.selections.length;i++){
var _59a=opts.selections[i];
if(_599>=_59a[0]&&_599<=_59a[1]){
_59b(_598,i);
return;
}
}
};
function _59b(_59c,_59d){
var opts=$.data(_59c,"timespinner").options;
if(_59d!=undefined){
opts.highlight=_59d;
}
var _59e=opts.selections[opts.highlight];
if(_59e){
var tb=$(_59c).timespinner("textbox");
_590(tb[0],_59e[0],_59e[1]);
tb.focus();
}
};
function _59f(_5a0,_5a1){
var opts=$.data(_5a0,"timespinner").options;
var _5a1=opts.parser.call(_5a0,_5a1);
var text=opts.formatter.call(_5a0,_5a1);
$(_5a0).spinner("setValue",text);
};
function _5a2(_5a3,down){
var opts=$.data(_5a3,"timespinner").options;
var s=$(_5a3).timespinner("getValue");
var _5a4=opts.selections[opts.highlight];
var s1=s.substring(0,_5a4[0]);
var s2=s.substring(_5a4[0],_5a4[1]);
var s3=s.substring(_5a4[1]);
var v=s1+((parseInt(s2)||0)+opts.increment*(down?-1:1))+s3;
$(_5a3).timespinner("setValue",v);
_59b(_5a3);
};
$.fn.timespinner=function(_5a5,_5a6){
if(typeof _5a5=="string"){
var _5a7=$.fn.timespinner.methods[_5a5];
if(_5a7){
return _5a7(this,_5a6);
}else{
return this.spinner(_5a5,_5a6);
}
}
_5a5=_5a5||{};
return this.each(function(){
var _5a8=$.data(this,"timespinner");
if(_5a8){
$.extend(_5a8.options,_5a5);
}else{
$.data(this,"timespinner",{options:$.extend({},$.fn.timespinner.defaults,$.fn.timespinner.parseOptions(this),_5a5)});
}
_594(this);
});
};
$.fn.timespinner.methods={options:function(jq){
var opts=jq.data("spinner")?jq.spinner("options"):{};
return $.extend($.data(jq[0],"timespinner").options,{width:opts.width,value:opts.value,originalValue:opts.originalValue,disabled:opts.disabled,readonly:opts.readonly});
},setValue:function(jq,_5a9){
return jq.each(function(){
_59f(this,_5a9);
});
},getHours:function(jq){
var opts=$.data(jq[0],"timespinner").options;
var vv=jq.timespinner("getValue").split(opts.separator);
return parseInt(vv[0],10);
},getMinutes:function(jq){
var opts=$.data(jq[0],"timespinner").options;
var vv=jq.timespinner("getValue").split(opts.separator);
return parseInt(vv[1],10);
},getSeconds:function(jq){
var opts=$.data(jq[0],"timespinner").options;
var vv=jq.timespinner("getValue").split(opts.separator);
return parseInt(vv[2],10)||0;
}};
$.fn.timespinner.parseOptions=function(_5aa){
return $.extend({},$.fn.spinner.parseOptions(_5aa),$.parser.parseOptions(_5aa,["separator",{showSeconds:"boolean",highlight:"number"}]));
};
$.fn.timespinner.defaults=$.extend({},$.fn.spinner.defaults,{inputEvents:$.extend({},$.fn.spinner.defaults.inputEvents,{click:function(e){
_597.call(this,e);
},blur:function(e){
var t=$(e.data.target);
t.timespinner("setValue",t.timespinner("getText"));
},keydown:function(e){
if(e.keyCode==13){
var t=$(e.data.target);
t.timespinner("setValue",t.timespinner("getText"));
}
}}),formatter:function(date){
if(!date){
return "";
}
var opts=$(this).timespinner("options");
var tt=[_5ab(date.getHours()),_5ab(date.getMinutes())];
if(opts.showSeconds){
tt.push(_5ab(date.getSeconds()));
}
return tt.join(opts.separator);
function _5ab(_5ac){
return (_5ac<10?"0":"")+_5ac;
};
},parser:function(s){
var opts=$(this).timespinner("options");
var date=_5ad(s);
if(date){
var min=_5ad(opts.min);
var max=_5ad(opts.max);
if(min&&min>date){
date=min;
}
if(max&&max<date){
date=max;
}
}
return date;
function _5ad(s){
if(!s){
return null;
}
var tt=s.split(opts.separator);
return new Date(1900,0,0,parseInt(tt[0],10)||0,parseInt(tt[1],10)||0,parseInt(tt[2],10)||0);
};
if(!s){
return null;
}
var tt=s.split(opts.separator);
return new Date(1900,0,0,parseInt(tt[0],10)||0,parseInt(tt[1],10)||0,parseInt(tt[2],10)||0);
},selections:[[0,2],[3,5],[6,8]],separator:":",showSeconds:false,highlight:0,spin:function(down){
_5a2(this,down);
}});
})(jQuery);
(function($){
function _5ae(_5af){
var opts=$.data(_5af,"datetimespinner").options;
$(_5af).addClass("datetimespinner-f").timespinner(opts);
};
$.fn.datetimespinner=function(_5b0,_5b1){
if(typeof _5b0=="string"){
var _5b2=$.fn.datetimespinner.methods[_5b0];
if(_5b2){
return _5b2(this,_5b1);
}else{
return this.timespinner(_5b0,_5b1);
}
}
_5b0=_5b0||{};
return this.each(function(){
var _5b3=$.data(this,"datetimespinner");
if(_5b3){
$.extend(_5b3.options,_5b0);
}else{
$.data(this,"datetimespinner",{options:$.extend({},$.fn.datetimespinner.defaults,$.fn.datetimespinner.parseOptions(this),_5b0)});
}
_5ae(this);
});
};
$.fn.datetimespinner.methods={options:function(jq){
var opts=jq.timespinner("options");
return $.extend($.data(jq[0],"datetimespinner").options,{width:opts.width,value:opts.value,originalValue:opts.originalValue,disabled:opts.disabled,readonly:opts.readonly});
}};
$.fn.datetimespinner.parseOptions=function(_5b4){
return $.extend({},$.fn.timespinner.parseOptions(_5b4),$.parser.parseOptions(_5b4,[]));
};
$.fn.datetimespinner.defaults=$.extend({},$.fn.timespinner.defaults,{formatter:function(date){
if(!date){
return "";
}
return $.fn.datebox.defaults.formatter.call(this,date)+" "+$.fn.timespinner.defaults.formatter.call(this,date);
},parser:function(s){
s=$.trim(s);
if(!s){
return null;
}
var dt=s.split(" ");
var _5b5=$.fn.datebox.defaults.parser.call(this,dt[0]);
if(dt.length<2){
return _5b5;
}
var _5b6=$.fn.timespinner.defaults.parser.call(this,dt[1]);
return new Date(_5b5.getFullYear(),_5b5.getMonth(),_5b5.getDate(),_5b6.getHours(),_5b6.getMinutes(),_5b6.getSeconds());
},selections:[[0,2],[3,5],[6,10],[11,13],[14,16],[17,19]]});
})(jQuery);
(function($){
var _5b7=0;
function _5b8(a,o){
for(var i=0,len=a.length;i<len;i++){
if(a[i]==o){
return i;
}
}
return -1;
};
function _5b9(a,o,id){
if(typeof o=="string"){
for(var i=0,len=a.length;i<len;i++){
if(a[i][o]==id){
a.splice(i,1);
return;
}
}
}else{
var _5ba=_5b8(a,o);
if(_5ba!=-1){
a.splice(_5ba,1);
}
}
};
function _5bb(a,o,r){
for(var i=0,len=a.length;i<len;i++){
if(a[i][o]==r[o]){
return;
}
}
a.push(r);
};
function _5bc(_5bd,aa){
return $.data(_5bd,"treegrid")?aa.slice(1):aa;
};
function _5be(_5bf){
var _5c0=$.data(_5bf,"datagrid");
var opts=_5c0.options;
var _5c1=_5c0.panel;
var dc=_5c0.dc;
var ss=null;
if(opts.sharedStyleSheet){
ss=typeof opts.sharedStyleSheet=="boolean"?"head":opts.sharedStyleSheet;
}else{
ss=_5c1.closest("div.datagrid-view");
if(!ss.length){
ss=dc.view;
}
}
var cc=$(ss);
var _5c2=$.data(cc[0],"ss");
if(!_5c2){
_5c2=$.data(cc[0],"ss",{cache:{},dirty:[]});
}
return {add:function(_5c3){
var ss=["<style type=\"text/css\" easyui=\"true\">"];
for(var i=0;i<_5c3.length;i++){
_5c2.cache[_5c3[i][0]]={width:_5c3[i][1]};
}
var _5c4=0;
for(var s in _5c2.cache){
var item=_5c2.cache[s];
item.index=_5c4++;
ss.push(s+"{width:"+item.width+"}");
}
ss.push("</style>");
$(ss.join("\n")).appendTo(cc);
cc.children("style[easyui]:not(:last)").remove();
},getRule:function(_5c5){
var _5c6=cc.children("style[easyui]:last")[0];
var _5c7=_5c6.styleSheet?_5c6.styleSheet:(_5c6.sheet||document.styleSheets[document.styleSheets.length-1]);
var _5c8=_5c7.cssRules||_5c7.rules;
return _5c8[_5c5];
},set:function(_5c9,_5ca){
var item=_5c2.cache[_5c9];
if(item){
item.width=_5ca;
var rule=this.getRule(item.index);
if(rule){
rule.style["width"]=_5ca;
}
}
},remove:function(_5cb){
var tmp=[];
for(var s in _5c2.cache){
if(s.indexOf(_5cb)==-1){
tmp.push([s,_5c2.cache[s].width]);
}
}
_5c2.cache={};
this.add(tmp);
},dirty:function(_5cc){
if(_5cc){
_5c2.dirty.push(_5cc);
}
},clean:function(){
for(var i=0;i<_5c2.dirty.length;i++){
this.remove(_5c2.dirty[i]);
}
_5c2.dirty=[];
}};
};
function _5cd(_5ce,_5cf){
var _5d0=$.data(_5ce,"datagrid");
var opts=_5d0.options;
var _5d1=_5d0.panel;
if(_5cf){
$.extend(opts,_5cf);
}
if(opts.fit==true){
var p=_5d1.panel("panel").parent();
opts.width=p.width();
opts.height=p.height();
}
_5d1.panel("resize",opts);
};
function _5d2(_5d3){
var _5d4=$.data(_5d3,"datagrid");
var opts=_5d4.options;
var dc=_5d4.dc;
var wrap=_5d4.panel;
var _5d5=wrap.width();
var _5d6=wrap.height();
var view=dc.view;
var _5d7=dc.view1;
var _5d8=dc.view2;
var _5d9=_5d7.children("div.datagrid-header");
var _5da=_5d8.children("div.datagrid-header");
var _5db=_5d9.find("table");
var _5dc=_5da.find("table");
view.width(_5d5);
var _5dd=_5d9.children("div.datagrid-header-inner").show();
_5d7.width(_5dd.find("table").width());
if(!opts.showHeader){
_5dd.hide();
}
_5d8.width(_5d5-_5d7._outerWidth());
_5d7.children()._outerWidth(_5d7.width());
_5d8.children()._outerWidth(_5d8.width());
var all=_5d9.add(_5da).add(_5db).add(_5dc);
all.css("height","");
var hh=Math.max(_5db.height(),_5dc.height());
all._outerHeight(hh);
dc.body1.add(dc.body2).children("table.datagrid-btable-frozen").css({position:"absolute",top:dc.header2._outerHeight()});
var _5de=dc.body2.children("table.datagrid-btable-frozen")._outerHeight();
var _5df=_5de+_5da._outerHeight()+_5d8.children(".datagrid-footer")._outerHeight();
wrap.children(":not(.datagrid-view,.datagrid-mask,.datagrid-mask-msg)").each(function(){
_5df+=$(this)._outerHeight();
});
var _5e0=wrap.outerHeight()-wrap.height();
var _5e1=wrap._size("minHeight")||"";
var _5e2=wrap._size("maxHeight")||"";
_5d7.add(_5d8).children("div.datagrid-body").css({marginTop:_5de,height:(isNaN(parseInt(opts.height))?"":(_5d6-_5df)),minHeight:(_5e1?_5e1-_5e0-_5df:""),maxHeight:(_5e2?_5e2-_5e0-_5df:"")});
view.height(_5d8.height());
};
function _5e3(_5e4,_5e5,_5e6){
var rows=$.data(_5e4,"datagrid").data.rows;
var opts=$.data(_5e4,"datagrid").options;
var dc=$.data(_5e4,"datagrid").dc;
if(!dc.body1.is(":empty")&&(!opts.nowrap||opts.autoRowHeight||_5e6)){
if(_5e5!=undefined){
var tr1=opts.finder.getTr(_5e4,_5e5,"body",1);
var tr2=opts.finder.getTr(_5e4,_5e5,"body",2);
_5e7(tr1,tr2);
}else{
var tr1=opts.finder.getTr(_5e4,0,"allbody",1);
var tr2=opts.finder.getTr(_5e4,0,"allbody",2);
_5e7(tr1,tr2);
if(opts.showFooter){
var tr1=opts.finder.getTr(_5e4,0,"allfooter",1);
var tr2=opts.finder.getTr(_5e4,0,"allfooter",2);
_5e7(tr1,tr2);
}
}
}
_5d2(_5e4);
if(opts.height=="auto"){
var _5e8=dc.body1.parent();
var _5e9=dc.body2;
var _5ea=_5eb(_5e9);
var _5ec=_5ea.height;
if(_5ea.width>_5e9.width()){
_5ec+=18;
}
_5ec-=parseInt(_5e9.css("marginTop"))||0;
_5e8.height(_5ec);
_5e9.height(_5ec);
dc.view.height(dc.view2.height());
}
dc.body2.triggerHandler("scroll");
function _5e7(trs1,trs2){
for(var i=0;i<trs2.length;i++){
var tr1=$(trs1[i]);
var tr2=$(trs2[i]);
tr1.css("height","");
tr2.css("height","");
var _5ed=Math.max(tr1.height(),tr2.height());
tr1.css("height",_5ed);
tr2.css("height",_5ed);
}
};
function _5eb(cc){
var _5ee=0;
var _5ef=0;
$(cc).children().each(function(){
var c=$(this);
if(c.is(":visible")){
_5ef+=c._outerHeight();
if(_5ee<c._outerWidth()){
_5ee=c._outerWidth();
}
}
});
return {width:_5ee,height:_5ef};
};
};
function _5f0(_5f1,_5f2){
var _5f3=$.data(_5f1,"datagrid");
var opts=_5f3.options;
var dc=_5f3.dc;
if(!dc.body2.children("table.datagrid-btable-frozen").length){
dc.body1.add(dc.body2).prepend("<table class=\"datagrid-btable datagrid-btable-frozen\" cellspacing=\"0\" cellpadding=\"0\"></table>");
}
_5f4(true);
_5f4(false);
_5d2(_5f1);
function _5f4(_5f5){
var _5f6=_5f5?1:2;
var tr=opts.finder.getTr(_5f1,_5f2,"body",_5f6);
(_5f5?dc.body1:dc.body2).children("table.datagrid-btable-frozen").append(tr);
};
};
function _5f7(_5f8,_5f9){
function _5fa(){
var _5fb=[];
var _5fc=[];
$(_5f8).children("thead").each(function(){
var opt=$.parser.parseOptions(this,[{frozen:"boolean"}]);
$(this).find("tr").each(function(){
var cols=[];
$(this).find("th").each(function(){
var th=$(this);
var col=$.extend({},$.parser.parseOptions(this,["field","align","halign","order","width",{sortable:"boolean",checkbox:"boolean",resizable:"boolean",fixed:"boolean"},{rowspan:"number",colspan:"number"}]),{title:(th.html()||undefined),hidden:(th.attr("hidden")?true:undefined),formatter:(th.attr("formatter")?eval(th.attr("formatter")):undefined),styler:(th.attr("styler")?eval(th.attr("styler")):undefined),sorter:(th.attr("sorter")?eval(th.attr("sorter")):undefined)});
if(col.width&&String(col.width).indexOf("%")==-1){
col.width=parseInt(col.width);
}
if(th.attr("editor")){
var s=$.trim(th.attr("editor"));
if(s.substr(0,1)=="{"){
col.editor=eval("("+s+")");
}else{
col.editor=s;
}
}
cols.push(col);
});
opt.frozen?_5fb.push(cols):_5fc.push(cols);
});
});
return [_5fb,_5fc];
};
var _5fd=$("<div class=\"datagrid-wrap\">"+"<div class=\"datagrid-view\">"+"<div class=\"datagrid-view1\">"+"<div class=\"datagrid-header\">"+"<div class=\"datagrid-header-inner\"></div>"+"</div>"+"<div class=\"datagrid-body\">"+"<div class=\"datagrid-body-inner\"></div>"+"</div>"+"<div class=\"datagrid-footer\">"+"<div class=\"datagrid-footer-inner\"></div>"+"</div>"+"</div>"+"<div class=\"datagrid-view2\">"+"<div class=\"datagrid-header\">"+"<div class=\"datagrid-header-inner\"></div>"+"</div>"+"<div class=\"datagrid-body\"></div>"+"<div class=\"datagrid-footer\">"+"<div class=\"datagrid-footer-inner\"></div>"+"</div>"+"</div>"+"</div>"+"</div>").insertAfter(_5f8);
_5fd.panel({doSize:false,cls:"datagrid"});
$(_5f8).addClass("datagrid-f").hide().appendTo(_5fd.children("div.datagrid-view"));
var cc=_5fa();
var view=_5fd.children("div.datagrid-view");
var _5fe=view.children("div.datagrid-view1");
var _5ff=view.children("div.datagrid-view2");
return {panel:_5fd,frozenColumns:cc[0],columns:cc[1],dc:{view:view,view1:_5fe,view2:_5ff,header1:_5fe.children("div.datagrid-header").children("div.datagrid-header-inner"),header2:_5ff.children("div.datagrid-header").children("div.datagrid-header-inner"),body1:_5fe.children("div.datagrid-body").children("div.datagrid-body-inner"),body2:_5ff.children("div.datagrid-body"),footer1:_5fe.children("div.datagrid-footer").children("div.datagrid-footer-inner"),footer2:_5ff.children("div.datagrid-footer").children("div.datagrid-footer-inner")}};
};
function _600(_601){
var _602=$.data(_601,"datagrid");
var opts=_602.options;
var dc=_602.dc;
var _603=_602.panel;
_602.ss=$(_601).datagrid("createStyleSheet");
_603.panel($.extend({},opts,{id:null,doSize:false,onResize:function(_604,_605){
if($.data(_601,"datagrid")){
_5d2(_601);
$(_601).datagrid("fitColumns");
opts.onResize.call(_603,_604,_605);
}
},onExpand:function(){
if($.data(_601,"datagrid")){
$(_601).datagrid("fixRowHeight").datagrid("fitColumns");
opts.onExpand.call(_603);
}
}}));
_602.rowIdPrefix="datagrid-row-r"+(++_5b7);
_602.cellClassPrefix="datagrid-cell-c"+_5b7;
_606(dc.header1,opts.frozenColumns,true);
_606(dc.header2,opts.columns,false);
_607();
dc.header1.add(dc.header2).css("display",opts.showHeader?"block":"none");
dc.footer1.add(dc.footer2).css("display",opts.showFooter?"block":"none");
if(opts.toolbar){
if($.isArray(opts.toolbar)){
$("div.datagrid-toolbar",_603).remove();
var tb=$("<div class=\"datagrid-toolbar\"><table cellspacing=\"0\" cellpadding=\"0\"><tr></tr></table></div>").prependTo(_603);
var tr=tb.find("tr");
for(var i=0;i<opts.toolbar.length;i++){
var btn=opts.toolbar[i];
if(btn=="-"){
$("<td><div class=\"datagrid-btn-separator\"></div></td>").appendTo(tr);
}else{
var td=$("<td></td>").appendTo(tr);
var tool=$("<a href=\"javascript:void(0)\"></a>").appendTo(td);
tool[0].onclick=eval(btn.handler||function(){
});
tool.linkbutton($.extend({},btn,{plain:true}));
}
}
}else{
$(opts.toolbar).addClass("datagrid-toolbar").prependTo(_603);
$(opts.toolbar).show();
}
}else{
$("div.datagrid-toolbar",_603).remove();
}
$("div.datagrid-pager",_603).remove();
if(opts.pagination){
var _608=$("<div class=\"datagrid-pager\"></div>");
if(opts.pagePosition=="bottom"){
_608.appendTo(_603);
}else{
if(opts.pagePosition=="top"){
_608.addClass("datagrid-pager-top").prependTo(_603);
}else{
var ptop=$("<div class=\"datagrid-pager datagrid-pager-top\"></div>").prependTo(_603);
_608.appendTo(_603);
_608=_608.add(ptop);
}
}
_608.pagination({total:(opts.pageNumber*opts.pageSize),pageNumber:opts.pageNumber,pageSize:opts.pageSize,pageList:opts.pageList,onSelectPage:function(_609,_60a){
opts.pageNumber=_609||1;
opts.pageSize=_60a;
_608.pagination("refresh",{pageNumber:_609,pageSize:_60a});
_646(_601);
}});
opts.pageSize=_608.pagination("options").pageSize;
}
function _606(_60b,_60c,_60d){
if(!_60c){
return;
}
$(_60b).show();
$(_60b).empty();
var _60e=[];
var _60f=[];
if(opts.sortName){
_60e=opts.sortName.split(",");
_60f=opts.sortOrder.split(",");
}
var t=$("<table class=\"datagrid-htable\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tbody></tbody></table>").appendTo(_60b);
for(var i=0;i<_60c.length;i++){
var tr=$("<tr class=\"datagrid-header-row\"></tr>").appendTo($("tbody",t));
var cols=_60c[i];
for(var j=0;j<cols.length;j++){
var col=cols[j];
var attr="";
if(col.rowspan){
attr+="rowspan=\""+col.rowspan+"\" ";
}
if(col.colspan){
attr+="colspan=\""+col.colspan+"\" ";
}
var td=$("<td "+attr+"></td>").appendTo(tr);
if(col.checkbox){
td.attr("field",col.field);
$("<div class=\"datagrid-header-check\"></div>").html("<input type=\"checkbox\"/>").appendTo(td);
}else{
if(col.field){
td.attr("field",col.field);
td.append("<div class=\"datagrid-cell\"><span></span><span class=\"datagrid-sort-icon\"></span></div>");
$("span",td).html(col.title);
$("span.datagrid-sort-icon",td).html("&nbsp;");
var cell=td.find("div.datagrid-cell");
var pos=_5b8(_60e,col.field);
if(pos>=0){
cell.addClass("datagrid-sort-"+_60f[pos]);
}
if(col.resizable==false){
cell.attr("resizable","false");
}
if(col.width){
var _610=$.parser.parseValue("width",col.width,dc.view,opts.scrollbarSize);
cell._outerWidth(_610-1);
col.boxWidth=parseInt(cell[0].style.width);
col.deltaWidth=_610-col.boxWidth;
}else{
col.auto=true;
}
cell.css("text-align",(col.halign||col.align||""));
col.cellClass=_602.cellClassPrefix+"-"+col.field.replace(/[\.|\s]/g,"-");
cell.addClass(col.cellClass).css("width","");
}else{
$("<div class=\"datagrid-cell-group\"></div>").html(col.title).appendTo(td);
}
}
if(col.hidden){
td.hide();
}
}
}
if(_60d&&opts.rownumbers){
var td=$("<td rowspan=\""+opts.frozenColumns.length+"\"><div class=\"datagrid-header-rownumber\"></div></td>");
if($("tr",t).length==0){
td.wrap("<tr class=\"datagrid-header-row\"></tr>").parent().appendTo($("tbody",t));
}else{
td.prependTo($("tr:first",t));
}
}
};
function _607(){
var _611=[];
var _612=_613(_601,true).concat(_613(_601));
for(var i=0;i<_612.length;i++){
var col=_614(_601,_612[i]);
if(col&&!col.checkbox){
_611.push(["."+col.cellClass,col.boxWidth?col.boxWidth+"px":"auto"]);
}
}
_602.ss.add(_611);
_602.ss.dirty(_602.cellSelectorPrefix);
_602.cellSelectorPrefix="."+_602.cellClassPrefix;
};
};
function _615(_616){
var _617=$.data(_616,"datagrid");
var _618=_617.panel;
var opts=_617.options;
var dc=_617.dc;
var _619=dc.header1.add(dc.header2);
_619.find("input[type=checkbox]").unbind(".datagrid").bind("click.datagrid",function(e){
if(opts.singleSelect&&opts.selectOnCheck){
return false;
}
if($(this).is(":checked")){
_6b0(_616);
}else{
_6b6(_616);
}
e.stopPropagation();
});
var _61a=_619.find("div.datagrid-cell");
_61a.closest("td").unbind(".datagrid").bind("mouseenter.datagrid",function(){
if(_617.resizing){
return;
}
$(this).addClass("datagrid-header-over");
}).bind("mouseleave.datagrid",function(){
$(this).removeClass("datagrid-header-over");
}).bind("contextmenu.datagrid",function(e){
var _61b=$(this).attr("field");
opts.onHeaderContextMenu.call(_616,e,_61b);
});
_61a.unbind(".datagrid").bind("click.datagrid",function(e){
var p1=$(this).offset().left+5;
var p2=$(this).offset().left+$(this)._outerWidth()-5;
if(e.pageX<p2&&e.pageX>p1){
_63b(_616,$(this).parent().attr("field"));
}
}).bind("dblclick.datagrid",function(e){
var p1=$(this).offset().left+5;
var p2=$(this).offset().left+$(this)._outerWidth()-5;
var cond=opts.resizeHandle=="right"?(e.pageX>p2):(opts.resizeHandle=="left"?(e.pageX<p1):(e.pageX<p1||e.pageX>p2));
if(cond){
var _61c=$(this).parent().attr("field");
var col=_614(_616,_61c);
if(col.resizable==false){
return;
}
$(_616).datagrid("autoSizeColumn",_61c);
col.auto=false;
}
});
var _61d=opts.resizeHandle=="right"?"e":(opts.resizeHandle=="left"?"w":"e,w");
_61a.each(function(){
$(this).resizable({handles:_61d,disabled:($(this).attr("resizable")?$(this).attr("resizable")=="false":false),minWidth:25,onStartResize:function(e){
_617.resizing=true;
_619.css("cursor",$("body").css("cursor"));
if(!_617.proxy){
_617.proxy=$("<div class=\"datagrid-resize-proxy\"></div>").appendTo(dc.view);
}
_617.proxy.css({left:e.pageX-$(_618).offset().left-1,display:"none"});
setTimeout(function(){
if(_617.proxy){
_617.proxy.show();
}
},500);
},onResize:function(e){
_617.proxy.css({left:e.pageX-$(_618).offset().left-1,display:"block"});
return false;
},onStopResize:function(e){
_619.css("cursor","");
$(this).css("height","");
var _61e=$(this).parent().attr("field");
var col=_614(_616,_61e);
col.width=$(this)._outerWidth();
col.boxWidth=col.width-col.deltaWidth;
col.auto=undefined;
$(this).css("width","");
$(_616).datagrid("fixColumnSize",_61e);
_617.proxy.remove();
_617.proxy=null;
if($(this).parents("div:first.datagrid-header").parent().hasClass("datagrid-view1")){
_5d2(_616);
}
$(_616).datagrid("fitColumns");
opts.onResizeColumn.call(_616,_61e,col.width);
setTimeout(function(){
_617.resizing=false;
},0);
}});
});
var bb=dc.body1.add(dc.body2);
bb.unbind();
for(var _61f in opts.rowEvents){
bb.bind(_61f,opts.rowEvents[_61f]);
}
dc.body1.bind("mousewheel DOMMouseScroll",function(e){
var e1=e.originalEvent||window.event;
var _620=e1.wheelDelta||e1.detail*(-1);
var dg=$(e.target).closest("div.datagrid-view").children(".datagrid-f");
var dc=dg.data("datagrid").dc;
dc.body2.scrollTop(dc.body2.scrollTop()-_620);
});
dc.body2.bind("scroll",function(){
var b1=dc.view1.children("div.datagrid-body");
b1.scrollTop($(this).scrollTop());
var c1=dc.body1.children(":first");
var c2=dc.body2.children(":first");
if(c1.length&&c2.length){
var top1=c1.offset().top;
var top2=c2.offset().top;
if(top1!=top2){
b1.scrollTop(b1.scrollTop()+top1-top2);
}
}
dc.view2.children("div.datagrid-header,div.datagrid-footer")._scrollLeft($(this)._scrollLeft());
dc.body2.children("table.datagrid-btable-frozen").css("left",-$(this)._scrollLeft());
});
};
function _621(_622){
return function(e){
var tr=_623(e.target);
if(!tr){
return;
}
var _624=_625(tr);
if($.data(_624,"datagrid").resizing){
return;
}
var _626=_627(tr);
if(_622){
_628(_624,_626);
}else{
var opts=$.data(_624,"datagrid").options;
opts.finder.getTr(_624,_626).removeClass("datagrid-row-over");
}
};
};
function _629(e){
var tr=_623(e.target);
if(!tr){
return;
}
var _62a=_625(tr);
var opts=$.data(_62a,"datagrid").options;
var _62b=_627(tr);
var tt=$(e.target);
if(tt.parent().hasClass("datagrid-cell-check")){
if(opts.singleSelect&&opts.selectOnCheck){
tt._propAttr("checked",!tt.is(":checked"));
_62c(_62a,_62b);
}else{
if(tt.is(":checked")){
tt._propAttr("checked",false);
_62c(_62a,_62b);
}else{
tt._propAttr("checked",true);
_62d(_62a,_62b);
}
}
}else{
var row=opts.finder.getRow(_62a,_62b);
var td=tt.closest("td[field]",tr);
if(td.length){
var _62e=td.attr("field");
opts.onClickCell.call(_62a,_62b,_62e,row[_62e]);
}
if(opts.singleSelect==true){
_62f(_62a,_62b);
}else{
if(opts.ctrlSelect){
if(e.ctrlKey){
if(tr.hasClass("datagrid-row-selected")){
_630(_62a,_62b);
}else{
_62f(_62a,_62b);
}
}else{
if(e.shiftKey){
$(_62a).datagrid("clearSelections");
var _631=Math.min(opts.lastSelectedIndex||0,_62b);
var _632=Math.max(opts.lastSelectedIndex||0,_62b);
for(var i=_631;i<=_632;i++){
_62f(_62a,i);
}
}else{
$(_62a).datagrid("clearSelections");
_62f(_62a,_62b);
opts.lastSelectedIndex=_62b;
}
}
}else{
if(tr.hasClass("datagrid-row-selected")){
_630(_62a,_62b);
}else{
_62f(_62a,_62b);
}
}
}
opts.onClickRow.apply(_62a,_5bc(_62a,[_62b,row]));
}
};
function _633(e){
var tr=_623(e.target);
if(!tr){
return;
}
var _634=_625(tr);
var opts=$.data(_634,"datagrid").options;
var _635=_627(tr);
var row=opts.finder.getRow(_634,_635);
var td=$(e.target).closest("td[field]",tr);
if(td.length){
var _636=td.attr("field");
opts.onDblClickCell.call(_634,_635,_636,row[_636]);
}
opts.onDblClickRow.apply(_634,_5bc(_634,[_635,row]));
};
function _637(e){
var tr=_623(e.target);
if(tr){
var _638=_625(tr);
var opts=$.data(_638,"datagrid").options;
var _639=_627(tr);
var row=opts.finder.getRow(_638,_639);
opts.onRowContextMenu.call(_638,e,_639,row);
}else{
var body=_623(e.target,".datagrid-body");
if(body){
var _638=_625(body);
var opts=$.data(_638,"datagrid").options;
opts.onRowContextMenu.call(_638,e,-1,null);
}
}
};
function _625(t){
return $(t).closest("div.datagrid-view").children(".datagrid-f")[0];
};
function _623(t,_63a){
var tr=$(t).closest(_63a||"tr.datagrid-row");
if(tr.length&&tr.parent().length){
return tr;
}else{
return undefined;
}
};
function _627(tr){
if(tr.attr("datagrid-row-index")){
return parseInt(tr.attr("datagrid-row-index"));
}else{
return tr.attr("node-id");
}
};
function _63b(_63c,_63d){
var _63e=$.data(_63c,"datagrid");
var opts=_63e.options;
_63d=_63d||{};
var _63f={sortName:opts.sortName,sortOrder:opts.sortOrder};
if(typeof _63d=="object"){
$.extend(_63f,_63d);
}
var _640=[];
var _641=[];
if(_63f.sortName){
_640=_63f.sortName.split(",");
_641=_63f.sortOrder.split(",");
}
if(typeof _63d=="string"){
var _642=_63d;
var col=_614(_63c,_642);
if(!col.sortable||_63e.resizing){
return;
}
var _643=col.order||"asc";
var pos=_5b8(_640,_642);
if(pos>=0){
var _644=_641[pos]=="asc"?"desc":"asc";
if(opts.multiSort&&_644==_643){
_640.splice(pos,1);
_641.splice(pos,1);
}else{
_641[pos]=_644;
}
}else{
if(opts.multiSort){
_640.push(_642);
_641.push(_643);
}else{
_640=[_642];
_641=[_643];
}
}
_63f.sortName=_640.join(",");
_63f.sortOrder=_641.join(",");
}
if(opts.onBeforeSortColumn.call(_63c,_63f.sortName,_63f.sortOrder)==false){
return;
}
$.extend(opts,_63f);
var dc=_63e.dc;
var _645=dc.header1.add(dc.header2);
_645.find("div.datagrid-cell").removeClass("datagrid-sort-asc datagrid-sort-desc");
for(var i=0;i<_640.length;i++){
var col=_614(_63c,_640[i]);
_645.find("div."+col.cellClass).addClass("datagrid-sort-"+_641[i]);
}
if(opts.remoteSort){
_646(_63c);
}else{
_647(_63c,$(_63c).datagrid("getData"));
}
opts.onSortColumn.call(_63c,opts.sortName,opts.sortOrder);
};
function _648(_649){
var _64a=$.data(_649,"datagrid");
var opts=_64a.options;
var dc=_64a.dc;
var _64b=dc.view2.children("div.datagrid-header");
dc.body2.css("overflow-x","");
_64c();
_64d();
_64e();
_64c(true);
if(_64b.width()>=_64b.find("table").width()){
dc.body2.css("overflow-x","hidden");
}
function _64e(){
if(!opts.fitColumns){
return;
}
if(!_64a.leftWidth){
_64a.leftWidth=0;
}
var _64f=0;
var cc=[];
var _650=_613(_649,false);
for(var i=0;i<_650.length;i++){
var col=_614(_649,_650[i]);
if(_651(col)){
_64f+=col.width;
cc.push({field:col.field,col:col,addingWidth:0});
}
}
if(!_64f){
return;
}
cc[cc.length-1].addingWidth-=_64a.leftWidth;
var _652=_64b.children("div.datagrid-header-inner").show();
var _653=_64b.width()-_64b.find("table").width()-opts.scrollbarSize+_64a.leftWidth;
var rate=_653/_64f;
if(!opts.showHeader){
_652.hide();
}
for(var i=0;i<cc.length;i++){
var c=cc[i];
var _654=parseInt(c.col.width*rate);
c.addingWidth+=_654;
_653-=_654;
}
cc[cc.length-1].addingWidth+=_653;
for(var i=0;i<cc.length;i++){
var c=cc[i];
if(c.col.boxWidth+c.addingWidth>0){
c.col.boxWidth+=c.addingWidth;
c.col.width+=c.addingWidth;
}
}
_64a.leftWidth=_653;
$(_649).datagrid("fixColumnSize");
};
function _64d(){
var _655=false;
var _656=_613(_649,true).concat(_613(_649,false));
$.map(_656,function(_657){
var col=_614(_649,_657);
if(String(col.width||"").indexOf("%")>=0){
var _658=$.parser.parseValue("width",col.width,dc.view,opts.scrollbarSize)-col.deltaWidth;
if(_658>0){
col.boxWidth=_658;
_655=true;
}
}
});
if(_655){
$(_649).datagrid("fixColumnSize");
}
};
function _64c(fit){
var _659=dc.header1.add(dc.header2).find(".datagrid-cell-group");
if(_659.length){
_659.each(function(){
$(this)._outerWidth(fit?$(this).parent().width():10);
});
if(fit){
_5d2(_649);
}
}
};
function _651(col){
if(String(col.width||"").indexOf("%")>=0){
return false;
}
if(!col.hidden&&!col.checkbox&&!col.auto&&!col.fixed){
return true;
}
};
};
function _65a(_65b,_65c){
var _65d=$.data(_65b,"datagrid");
var opts=_65d.options;
var dc=_65d.dc;
var tmp=$("<div class=\"datagrid-cell\" style=\"position:absolute;left:-9999px\"></div>").appendTo("body");
if(_65c){
_5cd(_65c);
$(_65b).datagrid("fitColumns");
}else{
var _65e=false;
var _65f=_613(_65b,true).concat(_613(_65b,false));
for(var i=0;i<_65f.length;i++){
var _65c=_65f[i];
var col=_614(_65b,_65c);
if(col.auto){
_5cd(_65c);
_65e=true;
}
}
if(_65e){
$(_65b).datagrid("fitColumns");
}
}
tmp.remove();
function _5cd(_660){
var _661=dc.view.find("div.datagrid-header td[field=\""+_660+"\"] div.datagrid-cell");
_661.css("width","");
var col=$(_65b).datagrid("getColumnOption",_660);
col.width=undefined;
col.boxWidth=undefined;
col.auto=true;
$(_65b).datagrid("fixColumnSize",_660);
var _662=Math.max(_663("header"),_663("allbody"),_663("allfooter"))+1;
_661._outerWidth(_662-1);
col.width=_662;
col.boxWidth=parseInt(_661[0].style.width);
col.deltaWidth=_662-col.boxWidth;
_661.css("width","");
$(_65b).datagrid("fixColumnSize",_660);
opts.onResizeColumn.call(_65b,_660,col.width);
function _663(type){
var _664=0;
if(type=="header"){
_664=_665(_661);
}else{
opts.finder.getTr(_65b,0,type).find("td[field=\""+_660+"\"] div.datagrid-cell").each(function(){
var w=_665($(this));
if(_664<w){
_664=w;
}
});
}
return _664;
function _665(cell){
return cell.is(":visible")?cell._outerWidth():tmp.html(cell.html())._outerWidth();
};
};
};
};
function _666(_667,_668){
var _669=$.data(_667,"datagrid");
var opts=_669.options;
var dc=_669.dc;
var _66a=dc.view.find("table.datagrid-btable,table.datagrid-ftable");
_66a.css("table-layout","fixed");
if(_668){
fix(_668);
}else{
var ff=_613(_667,true).concat(_613(_667,false));
for(var i=0;i<ff.length;i++){
fix(ff[i]);
}
}
_66a.css("table-layout","");
_66b(_667);
_5e3(_667);
_66c(_667);
function fix(_66d){
var col=_614(_667,_66d);
if(col.cellClass){
_669.ss.set("."+col.cellClass,col.boxWidth?col.boxWidth+"px":"auto");
}
};
};
function _66b(_66e){
var dc=$.data(_66e,"datagrid").dc;
dc.view.find("td.datagrid-td-merged").each(function(){
var td=$(this);
var _66f=td.attr("colspan")||1;
var col=_614(_66e,td.attr("field"));
var _670=col.boxWidth+col.deltaWidth-1;
for(var i=1;i<_66f;i++){
td=td.next();
col=_614(_66e,td.attr("field"));
_670+=col.boxWidth+col.deltaWidth;
}
$(this).children("div.datagrid-cell")._outerWidth(_670);
});
};
function _66c(_671){
var dc=$.data(_671,"datagrid").dc;
dc.view.find("div.datagrid-editable").each(function(){
var cell=$(this);
var _672=cell.parent().attr("field");
var col=$(_671).datagrid("getColumnOption",_672);
cell._outerWidth(col.boxWidth+col.deltaWidth-1);
var ed=$.data(this,"datagrid.editor");
if(ed.actions.resize){
ed.actions.resize(ed.target,cell.width());
}
});
};
function _614(_673,_674){
function find(_675){
if(_675){
for(var i=0;i<_675.length;i++){
var cc=_675[i];
for(var j=0;j<cc.length;j++){
var c=cc[j];
if(c.field==_674){
return c;
}
}
}
}
return null;
};
var opts=$.data(_673,"datagrid").options;
var col=find(opts.columns);
if(!col){
col=find(opts.frozenColumns);
}
return col;
};
function _613(_676,_677){
var opts=$.data(_676,"datagrid").options;
var _678=(_677==true)?(opts.frozenColumns||[[]]):opts.columns;
if(_678.length==0){
return [];
}
var aa=[];
var _679=_67a();
for(var i=0;i<_678.length;i++){
aa[i]=new Array(_679);
}
for(var _67b=0;_67b<_678.length;_67b++){
$.map(_678[_67b],function(col){
var _67c=_67d(aa[_67b]);
if(_67c>=0){
var _67e=col.field||"";
for(var c=0;c<(col.colspan||1);c++){
for(var r=0;r<(col.rowspan||1);r++){
aa[_67b+r][_67c]=_67e;
}
_67c++;
}
}
});
}
return aa[aa.length-1];
function _67a(){
var _67f=0;
$.map(_678[0],function(col){
_67f+=col.colspan||1;
});
return _67f;
};
function _67d(a){
for(var i=0;i<a.length;i++){
if(a[i]==undefined){
return i;
}
}
return -1;
};
};
function _647(_680,data){
var _681=$.data(_680,"datagrid");
var opts=_681.options;
var dc=_681.dc;
data=opts.loadFilter.call(_680,data);
data.total=parseInt(data.total);
_681.data=data;
if(data.footer){
_681.footer=data.footer;
}
if(!opts.remoteSort&&opts.sortName){
var _682=opts.sortName.split(",");
var _683=opts.sortOrder.split(",");
data.rows.sort(function(r1,r2){
var r=0;
for(var i=0;i<_682.length;i++){
var sn=_682[i];
var so=_683[i];
var col=_614(_680,sn);
var _684=col.sorter||function(a,b){
return a==b?0:(a>b?1:-1);
};
r=_684(r1[sn],r2[sn])*(so=="asc"?1:-1);
if(r!=0){
return r;
}
}
return r;
});
}
if(opts.view.onBeforeRender){
opts.view.onBeforeRender.call(opts.view,_680,data.rows);
}
opts.view.render.call(opts.view,_680,dc.body2,false);
opts.view.render.call(opts.view,_680,dc.body1,true);
if(opts.showFooter){
opts.view.renderFooter.call(opts.view,_680,dc.footer2,false);
opts.view.renderFooter.call(opts.view,_680,dc.footer1,true);
}
if(opts.view.onAfterRender){
opts.view.onAfterRender.call(opts.view,_680);
}
_681.ss.clean();
var _685=$(_680).datagrid("getPager");
if(_685.length){
var _686=_685.pagination("options");
if(_686.total!=data.total){
_685.pagination("refresh",{total:data.total});
if(opts.pageNumber!=_686.pageNumber&&_686.pageNumber>0){
opts.pageNumber=_686.pageNumber;
_646(_680);
}
}
}
_5e3(_680);
dc.body2.triggerHandler("scroll");
$(_680).datagrid("setSelectionState");
$(_680).datagrid("autoSizeColumn");
opts.onLoadSuccess.call(_680,data);
};
function _687(_688){
var _689=$.data(_688,"datagrid");
var opts=_689.options;
var dc=_689.dc;
dc.header1.add(dc.header2).find("input[type=checkbox]")._propAttr("checked",false);
if(opts.idField){
var _68a=$.data(_688,"treegrid")?true:false;
var _68b=opts.onSelect;
var _68c=opts.onCheck;
opts.onSelect=opts.onCheck=function(){
};
var rows=opts.finder.getRows(_688);
for(var i=0;i<rows.length;i++){
var row=rows[i];
var _68d=_68a?row[opts.idField]:i;
if(_68e(_689.selectedRows,row)){
_62f(_688,_68d,true);
}
if(_68e(_689.checkedRows,row)){
_62c(_688,_68d,true);
}
}
opts.onSelect=_68b;
opts.onCheck=_68c;
}
function _68e(a,r){
for(var i=0;i<a.length;i++){
if(a[i][opts.idField]==r[opts.idField]){
a[i]=r;
return true;
}
}
return false;
};
};
function _68f(_690,row){
var _691=$.data(_690,"datagrid");
var opts=_691.options;
var rows=_691.data.rows;
if(typeof row=="object"){
return _5b8(rows,row);
}else{
for(var i=0;i<rows.length;i++){
if(rows[i][opts.idField]==row){
return i;
}
}
return -1;
}
};
function _692(_693){
var _694=$.data(_693,"datagrid");
var opts=_694.options;
var data=_694.data;
if(opts.idField){
return _694.selectedRows;
}else{
var rows=[];
opts.finder.getTr(_693,"","selected",2).each(function(){
rows.push(opts.finder.getRow(_693,$(this)));
});
return rows;
}
};
function _695(_696){
var _697=$.data(_696,"datagrid");
var opts=_697.options;
if(opts.idField){
return _697.checkedRows;
}else{
var rows=[];
opts.finder.getTr(_696,"","checked",2).each(function(){
rows.push(opts.finder.getRow(_696,$(this)));
});
return rows;
}
};
function _698(_699,_69a){
var _69b=$.data(_699,"datagrid");
var dc=_69b.dc;
var opts=_69b.options;
var tr=opts.finder.getTr(_699,_69a);
if(tr.length){
if(tr.closest("table").hasClass("datagrid-btable-frozen")){
return;
}
var _69c=dc.view2.children("div.datagrid-header")._outerHeight();
var _69d=dc.body2;
var _69e=_69d.outerHeight(true)-_69d.outerHeight();
var top=tr.position().top-_69c-_69e;
if(top<0){
_69d.scrollTop(_69d.scrollTop()+top);
}else{
if(top+tr._outerHeight()>_69d.height()-18){
_69d.scrollTop(_69d.scrollTop()+top+tr._outerHeight()-_69d.height()+18);
}
}
}
};
function _628(_69f,_6a0){
var _6a1=$.data(_69f,"datagrid");
var opts=_6a1.options;
opts.finder.getTr(_69f,_6a1.highlightIndex).removeClass("datagrid-row-over");
opts.finder.getTr(_69f,_6a0).addClass("datagrid-row-over");
_6a1.highlightIndex=_6a0;
};
function _62f(_6a2,_6a3,_6a4){
var _6a5=$.data(_6a2,"datagrid");
var opts=_6a5.options;
var row=opts.finder.getRow(_6a2,_6a3);
if(opts.onBeforeSelect.apply(_6a2,_5bc(_6a2,[_6a3,row]))==false){
return;
}
if(opts.singleSelect){
_6a6(_6a2,true);
_6a5.selectedRows=[];
}
if(!_6a4&&opts.checkOnSelect){
_62c(_6a2,_6a3,true);
}
if(opts.idField){
_5bb(_6a5.selectedRows,opts.idField,row);
}
opts.finder.getTr(_6a2,_6a3).addClass("datagrid-row-selected");
opts.onSelect.apply(_6a2,_5bc(_6a2,[_6a3,row]));
_698(_6a2,_6a3);
};
function _630(_6a7,_6a8,_6a9){
var _6aa=$.data(_6a7,"datagrid");
var dc=_6aa.dc;
var opts=_6aa.options;
var row=opts.finder.getRow(_6a7,_6a8);
if(opts.onBeforeUnselect.apply(_6a7,_5bc(_6a7,[_6a8,row]))==false){
return;
}
if(!_6a9&&opts.checkOnSelect){
_62d(_6a7,_6a8,true);
}
opts.finder.getTr(_6a7,_6a8).removeClass("datagrid-row-selected");
if(opts.idField){
_5b9(_6aa.selectedRows,opts.idField,row[opts.idField]);
}
opts.onUnselect.apply(_6a7,_5bc(_6a7,[_6a8,row]));
};
function _6ab(_6ac,_6ad){
var _6ae=$.data(_6ac,"datagrid");
var opts=_6ae.options;
var rows=opts.finder.getRows(_6ac);
var _6af=$.data(_6ac,"datagrid").selectedRows;
if(!_6ad&&opts.checkOnSelect){
_6b0(_6ac,true);
}
opts.finder.getTr(_6ac,"","allbody").addClass("datagrid-row-selected");
if(opts.idField){
for(var _6b1=0;_6b1<rows.length;_6b1++){
_5bb(_6af,opts.idField,rows[_6b1]);
}
}
opts.onSelectAll.call(_6ac,rows);
};
function _6a6(_6b2,_6b3){
var _6b4=$.data(_6b2,"datagrid");
var opts=_6b4.options;
var rows=opts.finder.getRows(_6b2);
var _6b5=$.data(_6b2,"datagrid").selectedRows;
if(!_6b3&&opts.checkOnSelect){
_6b6(_6b2,true);
}
opts.finder.getTr(_6b2,"","selected").removeClass("datagrid-row-selected");
if(opts.idField){
for(var _6b7=0;_6b7<rows.length;_6b7++){
_5b9(_6b5,opts.idField,rows[_6b7][opts.idField]);
}
}
opts.onUnselectAll.call(_6b2,rows);
};
function _62c(_6b8,_6b9,_6ba){
var _6bb=$.data(_6b8,"datagrid");
var opts=_6bb.options;
var row=opts.finder.getRow(_6b8,_6b9);
if(opts.onBeforeCheck.apply(_6b8,_5bc(_6b8,[_6b9,row]))==false){
return;
}
if(opts.singleSelect&&opts.selectOnCheck){
_6b6(_6b8,true);
_6bb.checkedRows=[];
}
if(!_6ba&&opts.selectOnCheck){
_62f(_6b8,_6b9,true);
}
var tr=opts.finder.getTr(_6b8,_6b9).addClass("datagrid-row-checked");
tr.find("div.datagrid-cell-check input[type=checkbox]")._propAttr("checked",true);
tr=opts.finder.getTr(_6b8,"","checked",2);
if(tr.length==opts.finder.getRows(_6b8).length){
var dc=_6bb.dc;
dc.header1.add(dc.header2).find("input[type=checkbox]")._propAttr("checked",true);
}
if(opts.idField){
_5bb(_6bb.checkedRows,opts.idField,row);
}
opts.onCheck.apply(_6b8,_5bc(_6b8,[_6b9,row]));
};
function _62d(_6bc,_6bd,_6be){
var _6bf=$.data(_6bc,"datagrid");
var opts=_6bf.options;
var row=opts.finder.getRow(_6bc,_6bd);
if(opts.onBeforeUncheck.apply(_6bc,_5bc(_6bc,[_6bd,row]))==false){
return;
}
if(!_6be&&opts.selectOnCheck){
_630(_6bc,_6bd,true);
}
var tr=opts.finder.getTr(_6bc,_6bd).removeClass("datagrid-row-checked");
tr.find("div.datagrid-cell-check input[type=checkbox]")._propAttr("checked",false);
var dc=_6bf.dc;
var _6c0=dc.header1.add(dc.header2);
_6c0.find("input[type=checkbox]")._propAttr("checked",false);
if(opts.idField){
_5b9(_6bf.checkedRows,opts.idField,row[opts.idField]);
}
opts.onUncheck.apply(_6bc,_5bc(_6bc,[_6bd,row]));
};
function _6b0(_6c1,_6c2){
var _6c3=$.data(_6c1,"datagrid");
var opts=_6c3.options;
var rows=opts.finder.getRows(_6c1);
if(!_6c2&&opts.selectOnCheck){
_6ab(_6c1,true);
}
var dc=_6c3.dc;
var hck=dc.header1.add(dc.header2).find("input[type=checkbox]");
var bck=opts.finder.getTr(_6c1,"","allbody").addClass("datagrid-row-checked").find("div.datagrid-cell-check input[type=checkbox]");
hck.add(bck)._propAttr("checked",true);
if(opts.idField){
for(var i=0;i<rows.length;i++){
_5bb(_6c3.checkedRows,opts.idField,rows[i]);
}
}
opts.onCheckAll.call(_6c1,rows);
};
function _6b6(_6c4,_6c5){
var _6c6=$.data(_6c4,"datagrid");
var opts=_6c6.options;
var rows=opts.finder.getRows(_6c4);
if(!_6c5&&opts.selectOnCheck){
_6a6(_6c4,true);
}
var dc=_6c6.dc;
var hck=dc.header1.add(dc.header2).find("input[type=checkbox]");
var bck=opts.finder.getTr(_6c4,"","checked").removeClass("datagrid-row-checked").find("div.datagrid-cell-check input[type=checkbox]");
hck.add(bck)._propAttr("checked",false);
if(opts.idField){
for(var i=0;i<rows.length;i++){
_5b9(_6c6.checkedRows,opts.idField,rows[i][opts.idField]);
}
}
opts.onUncheckAll.call(_6c4,rows);
};
function _6c7(_6c8,_6c9){
var opts=$.data(_6c8,"datagrid").options;
var tr=opts.finder.getTr(_6c8,_6c9);
var row=opts.finder.getRow(_6c8,_6c9);
if(tr.hasClass("datagrid-row-editing")){
return;
}
if(opts.onBeforeEdit.apply(_6c8,_5bc(_6c8,[_6c9,row]))==false){
return;
}
tr.addClass("datagrid-row-editing");
_6ca(_6c8,_6c9);
_66c(_6c8);
tr.find("div.datagrid-editable").each(function(){
var _6cb=$(this).parent().attr("field");
var ed=$.data(this,"datagrid.editor");
ed.actions.setValue(ed.target,row[_6cb]);
});
_6cc(_6c8,_6c9);
opts.onBeginEdit.apply(_6c8,_5bc(_6c8,[_6c9,row]));
};
function _6cd(_6ce,_6cf,_6d0){
var _6d1=$.data(_6ce,"datagrid");
var opts=_6d1.options;
var _6d2=_6d1.updatedRows;
var _6d3=_6d1.insertedRows;
var tr=opts.finder.getTr(_6ce,_6cf);
var row=opts.finder.getRow(_6ce,_6cf);
if(!tr.hasClass("datagrid-row-editing")){
return;
}
if(!_6d0){
if(!_6cc(_6ce,_6cf)){
return;
}
var _6d4=false;
var _6d5={};
tr.find("div.datagrid-editable").each(function(){
var _6d6=$(this).parent().attr("field");
var ed=$.data(this,"datagrid.editor");
var t=$(ed.target);
var _6d7=t.data("textbox")?t.textbox("textbox"):t;
_6d7.triggerHandler("blur");
var _6d8=ed.actions.getValue(ed.target);
if(row[_6d6]!=_6d8){
row[_6d6]=_6d8;
_6d4=true;
_6d5[_6d6]=_6d8;
}
});
if(_6d4){
if(_5b8(_6d3,row)==-1){
if(_5b8(_6d2,row)==-1){
_6d2.push(row);
}
}
}
opts.onEndEdit.apply(_6ce,_5bc(_6ce,[_6cf,row,_6d5]));
}
tr.removeClass("datagrid-row-editing");
_6d9(_6ce,_6cf);
$(_6ce).datagrid("refreshRow",_6cf);
if(!_6d0){
opts.onAfterEdit.apply(_6ce,_5bc(_6ce,[_6cf,row,_6d5]));
}else{
opts.onCancelEdit.apply(_6ce,_5bc(_6ce,[_6cf,row]));
}
};
function _6da(_6db,_6dc){
var opts=$.data(_6db,"datagrid").options;
var tr=opts.finder.getTr(_6db,_6dc);
var _6dd=[];
tr.children("td").each(function(){
var cell=$(this).find("div.datagrid-editable");
if(cell.length){
var ed=$.data(cell[0],"datagrid.editor");
_6dd.push(ed);
}
});
return _6dd;
};
function _6de(_6df,_6e0){
var _6e1=_6da(_6df,_6e0.index!=undefined?_6e0.index:_6e0.id);
for(var i=0;i<_6e1.length;i++){
if(_6e1[i].field==_6e0.field){
return _6e1[i];
}
}
return null;
};
function _6ca(_6e2,_6e3){
var opts=$.data(_6e2,"datagrid").options;
var tr=opts.finder.getTr(_6e2,_6e3);
tr.children("td").each(function(){
var cell=$(this).find("div.datagrid-cell");
var _6e4=$(this).attr("field");
var col=_614(_6e2,_6e4);
if(col&&col.editor){
var _6e5,_6e6;
if(typeof col.editor=="string"){
_6e5=col.editor;
}else{
_6e5=col.editor.type;
_6e6=col.editor.options;
}
var _6e7=opts.editors[_6e5];
if(_6e7){
var _6e8=cell.html();
var _6e9=cell._outerWidth();
cell.addClass("datagrid-editable");
cell._outerWidth(_6e9);
cell.html("<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\"><tr><td></td></tr></table>");
cell.children("table").bind("click dblclick contextmenu",function(e){
e.stopPropagation();
});
$.data(cell[0],"datagrid.editor",{actions:_6e7,target:_6e7.init(cell.find("td"),_6e6),field:_6e4,type:_6e5,oldHtml:_6e8});
}
}
});
_5e3(_6e2,_6e3,true);
};
function _6d9(_6ea,_6eb){
var opts=$.data(_6ea,"datagrid").options;
var tr=opts.finder.getTr(_6ea,_6eb);
tr.children("td").each(function(){
var cell=$(this).find("div.datagrid-editable");
if(cell.length){
var ed=$.data(cell[0],"datagrid.editor");
if(ed.actions.destroy){
ed.actions.destroy(ed.target);
}
cell.html(ed.oldHtml);
$.removeData(cell[0],"datagrid.editor");
cell.removeClass("datagrid-editable");
cell.css("width","");
}
});
};
function _6cc(_6ec,_6ed){
var tr=$.data(_6ec,"datagrid").options.finder.getTr(_6ec,_6ed);
if(!tr.hasClass("datagrid-row-editing")){
return true;
}
var vbox=tr.find(".validatebox-text");
vbox.validatebox("validate");
vbox.trigger("mouseleave");
var _6ee=tr.find(".validatebox-invalid");
return _6ee.length==0;
};
function _6ef(_6f0,_6f1){
var _6f2=$.data(_6f0,"datagrid").insertedRows;
var _6f3=$.data(_6f0,"datagrid").deletedRows;
var _6f4=$.data(_6f0,"datagrid").updatedRows;
if(!_6f1){
var rows=[];
rows=rows.concat(_6f2);
rows=rows.concat(_6f3);
rows=rows.concat(_6f4);
return rows;
}else{
if(_6f1=="inserted"){
return _6f2;
}else{
if(_6f1=="deleted"){
return _6f3;
}else{
if(_6f1=="updated"){
return _6f4;
}
}
}
}
return [];
};
function _6f5(_6f6,_6f7){
var _6f8=$.data(_6f6,"datagrid");
var opts=_6f8.options;
var data=_6f8.data;
var _6f9=_6f8.insertedRows;
var _6fa=_6f8.deletedRows;
$(_6f6).datagrid("cancelEdit",_6f7);
var row=opts.finder.getRow(_6f6,_6f7);
if(_5b8(_6f9,row)>=0){
_5b9(_6f9,row);
}else{
_6fa.push(row);
}
_5b9(_6f8.selectedRows,opts.idField,row[opts.idField]);
_5b9(_6f8.checkedRows,opts.idField,row[opts.idField]);
opts.view.deleteRow.call(opts.view,_6f6,_6f7);
if(opts.height=="auto"){
_5e3(_6f6);
}
$(_6f6).datagrid("getPager").pagination("refresh",{total:data.total});
};
function _6fb(_6fc,_6fd){
var data=$.data(_6fc,"datagrid").data;
var view=$.data(_6fc,"datagrid").options.view;
var _6fe=$.data(_6fc,"datagrid").insertedRows;
view.insertRow.call(view,_6fc,_6fd.index,_6fd.row);
_6fe.push(_6fd.row);
$(_6fc).datagrid("getPager").pagination("refresh",{total:data.total});
};
function _6ff(_700,row){
var data=$.data(_700,"datagrid").data;
var view=$.data(_700,"datagrid").options.view;
var _701=$.data(_700,"datagrid").insertedRows;
view.insertRow.call(view,_700,null,row);
_701.push(row);
$(_700).datagrid("getPager").pagination("refresh",{total:data.total});
};
function _702(_703){
var _704=$.data(_703,"datagrid");
var data=_704.data;
var rows=data.rows;
var _705=[];
for(var i=0;i<rows.length;i++){
_705.push($.extend({},rows[i]));
}
_704.originalRows=_705;
_704.updatedRows=[];
_704.insertedRows=[];
_704.deletedRows=[];
};
function _706(_707){
var data=$.data(_707,"datagrid").data;
var ok=true;
for(var i=0,len=data.rows.length;i<len;i++){
if(_6cc(_707,i)){
$(_707).datagrid("endEdit",i);
}else{
ok=false;
}
}
if(ok){
_702(_707);
}
};
function _708(_709){
var _70a=$.data(_709,"datagrid");
var opts=_70a.options;
var _70b=_70a.originalRows;
var _70c=_70a.insertedRows;
var _70d=_70a.deletedRows;
var _70e=_70a.selectedRows;
var _70f=_70a.checkedRows;
var data=_70a.data;
function _710(a){
var ids=[];
for(var i=0;i<a.length;i++){
ids.push(a[i][opts.idField]);
}
return ids;
};
function _711(ids,_712){
for(var i=0;i<ids.length;i++){
var _713=_68f(_709,ids[i]);
if(_713>=0){
(_712=="s"?_62f:_62c)(_709,_713,true);
}
}
};
for(var i=0;i<data.rows.length;i++){
$(_709).datagrid("cancelEdit",i);
}
var _714=_710(_70e);
var _715=_710(_70f);
_70e.splice(0,_70e.length);
_70f.splice(0,_70f.length);
data.total+=_70d.length-_70c.length;
data.rows=_70b;
_647(_709,data);
_711(_714,"s");
_711(_715,"c");
_702(_709);
};
function _646(_716,_717){
var opts=$.data(_716,"datagrid").options;
if(_717){
opts.queryParams=_717;
}
var _718=$.extend({},opts.queryParams);
if(opts.pagination){
$.extend(_718,{page:opts.pageNumber||1,rows:opts.pageSize});
}
if(opts.sortName){
$.extend(_718,{sort:opts.sortName,order:opts.sortOrder});
}
if(opts.onBeforeLoad.call(_716,_718)==false){
return;
}
$(_716).datagrid("loading");
var _719=opts.loader.call(_716,_718,function(data){
$(_716).datagrid("loaded");
$(_716).datagrid("loadData",data);
},function(){
$(_716).datagrid("loaded");
opts.onLoadError.apply(_716,arguments);
});
if(_719==false){
$(_716).datagrid("loaded");
}
};
function _71a(_71b,_71c){
var opts=$.data(_71b,"datagrid").options;
_71c.type=_71c.type||"body";
_71c.rowspan=_71c.rowspan||1;
_71c.colspan=_71c.colspan||1;
if(_71c.rowspan==1&&_71c.colspan==1){
return;
}
var tr=opts.finder.getTr(_71b,(_71c.index!=undefined?_71c.index:_71c.id),_71c.type);
if(!tr.length){
return;
}
var td=tr.find("td[field=\""+_71c.field+"\"]");
td.attr("rowspan",_71c.rowspan).attr("colspan",_71c.colspan);
td.addClass("datagrid-td-merged");
_71d(td.next(),_71c.colspan-1);
for(var i=1;i<_71c.rowspan;i++){
tr=tr.next();
if(!tr.length){
break;
}
td=tr.find("td[field=\""+_71c.field+"\"]");
_71d(td,_71c.colspan);
}
_66b(_71b);
function _71d(td,_71e){
for(var i=0;i<_71e;i++){
td.hide();
td=td.next();
}
};
};
$.fn.datagrid=function(_71f,_720){
if(typeof _71f=="string"){
return $.fn.datagrid.methods[_71f](this,_720);
}
_71f=_71f||{};
return this.each(function(){
var _721=$.data(this,"datagrid");
var opts;
if(_721){
opts=$.extend(_721.options,_71f);
_721.options=opts;
}else{
opts=$.extend({},$.extend({},$.fn.datagrid.defaults,{queryParams:{}}),$.fn.datagrid.parseOptions(this),_71f);
$(this).css("width","").css("height","");
var _722=_5f7(this,opts.rownumbers);
if(!opts.columns){
opts.columns=_722.columns;
}
if(!opts.frozenColumns){
opts.frozenColumns=_722.frozenColumns;
}
opts.columns=$.extend(true,[],opts.columns);
opts.frozenColumns=$.extend(true,[],opts.frozenColumns);
opts.view=$.extend({},opts.view);
$.data(this,"datagrid",{options:opts,panel:_722.panel,dc:_722.dc,ss:null,selectedRows:[],checkedRows:[],data:{total:0,rows:[]},originalRows:[],updatedRows:[],insertedRows:[],deletedRows:[]});
}
_600(this);
_615(this);
_5cd(this);
if(opts.data){
$(this).datagrid("loadData",opts.data);
}else{
var data=$.fn.datagrid.parseData(this);
if(data.total>0){
$(this).datagrid("loadData",data);
}else{
opts.view.renderEmptyRow(this);
$(this).datagrid("autoSizeColumn");
}
}
_646(this);
});
};
function _723(_724){
var _725={};
$.map(_724,function(name){
_725[name]=_726(name);
});
return _725;
function _726(name){
function isA(_727){
return $.data($(_727)[0],name)!=undefined;
};
return {init:function(_728,_729){
var _72a=$("<input type=\"text\" class=\"datagrid-editable-input\">").appendTo(_728);
if(_72a[name]&&name!="text"){
return _72a[name](_729);
}else{
return _72a;
}
},destroy:function(_72b){
if(isA(_72b,name)){
$(_72b)[name]("destroy");
}
},getValue:function(_72c){
if(isA(_72c,name)){
var opts=$(_72c)[name]("options");
if(opts.multiple){
return $(_72c)[name]("getValues").join(opts.separator);
}else{
return $(_72c)[name]("getValue");
}
}else{
return $(_72c).val();
}
},setValue:function(_72d,_72e){
if(isA(_72d,name)){
var opts=$(_72d)[name]("options");
if(opts.multiple){
if(_72e){
$(_72d)[name]("setValues",_72e.split(opts.separator));
}else{
$(_72d)[name]("clear");
}
}else{
$(_72d)[name]("setValue",_72e);
}
}else{
$(_72d).val(_72e);
}
},resize:function(_72f,_730){
if(isA(_72f,name)){
$(_72f)[name]("resize",_730);
}else{
$(_72f)._outerWidth(_730)._outerHeight(22);
}
}};
};
};
var _731=$.extend({},_723(["text","textbox","numberbox","numberspinner","combobox","combotree","combogrid","datebox","datetimebox","timespinner","datetimespinner"]),{textarea:{init:function(_732,_733){
var _734=$("<textarea class=\"datagrid-editable-input\"></textarea>").appendTo(_732);
return _734;
},getValue:function(_735){
return $(_735).val();
},setValue:function(_736,_737){
$(_736).val(_737);
},resize:function(_738,_739){
$(_738)._outerWidth(_739);
}},checkbox:{init:function(_73a,_73b){
var _73c=$("<input type=\"checkbox\">").appendTo(_73a);
_73c.val(_73b.on);
_73c.attr("offval",_73b.off);
return _73c;
},getValue:function(_73d){
if($(_73d).is(":checked")){
return $(_73d).val();
}else{
return $(_73d).attr("offval");
}
},setValue:function(_73e,_73f){
var _740=false;
if($(_73e).val()==_73f){
_740=true;
}
$(_73e)._propAttr("checked",_740);
}},validatebox:{init:function(_741,_742){
var _743=$("<input type=\"text\" class=\"datagrid-editable-input\">").appendTo(_741);
_743.validatebox(_742);
return _743;
},destroy:function(_744){
$(_744).validatebox("destroy");
},getValue:function(_745){
return $(_745).val();
},setValue:function(_746,_747){
$(_746).val(_747);
},resize:function(_748,_749){
$(_748)._outerWidth(_749)._outerHeight(22);
}}});
$.fn.datagrid.methods={options:function(jq){
var _74a=$.data(jq[0],"datagrid").options;
var _74b=$.data(jq[0],"datagrid").panel.panel("options");
var opts=$.extend(_74a,{width:_74b.width,height:_74b.height,closed:_74b.closed,collapsed:_74b.collapsed,minimized:_74b.minimized,maximized:_74b.maximized});
return opts;
},setSelectionState:function(jq){
return jq.each(function(){
_687(this);
});
},createStyleSheet:function(jq){
return _5be(jq[0]);
},getPanel:function(jq){
return $.data(jq[0],"datagrid").panel;
},getPager:function(jq){
return $.data(jq[0],"datagrid").panel.children("div.datagrid-pager");
},getColumnFields:function(jq,_74c){
return _613(jq[0],_74c);
},getColumnOption:function(jq,_74d){
return _614(jq[0],_74d);
},resize:function(jq,_74e){
return jq.each(function(){
_5cd(this,_74e);
});
},load:function(jq,_74f){
return jq.each(function(){
var opts=$(this).datagrid("options");
if(typeof _74f=="string"){
opts.url=_74f;
_74f=null;
}
opts.pageNumber=1;
var _750=$(this).datagrid("getPager");
_750.pagination("refresh",{pageNumber:1});
_646(this,_74f);
});
},reload:function(jq,_751){
return jq.each(function(){
var opts=$(this).datagrid("options");
if(typeof _751=="string"){
opts.url=_751;
_751=null;
}
_646(this,_751);
});
},reloadFooter:function(jq,_752){
return jq.each(function(){
var opts=$.data(this,"datagrid").options;
var dc=$.data(this,"datagrid").dc;
if(_752){
$.data(this,"datagrid").footer=_752;
}
if(opts.showFooter){
opts.view.renderFooter.call(opts.view,this,dc.footer2,false);
opts.view.renderFooter.call(opts.view,this,dc.footer1,true);
if(opts.view.onAfterRender){
opts.view.onAfterRender.call(opts.view,this);
}
$(this).datagrid("fixRowHeight");
}
});
},loading:function(jq){
return jq.each(function(){
var opts=$.data(this,"datagrid").options;
$(this).datagrid("getPager").pagination("loading");
if(opts.loadMsg){
var _753=$(this).datagrid("getPanel");
if(!_753.children("div.datagrid-mask").length){
$("<div class=\"datagrid-mask\" style=\"display:block\"></div>").appendTo(_753);
var msg=$("<div class=\"datagrid-mask-msg\" style=\"display:block;left:50%\"></div>").html(opts.loadMsg).appendTo(_753);
msg._outerHeight(40);
msg.css({marginLeft:(-msg.outerWidth()/2),lineHeight:(msg.height()+"px")});
}
}
});
},loaded:function(jq){
return jq.each(function(){
$(this).datagrid("getPager").pagination("loaded");
var _754=$(this).datagrid("getPanel");
_754.children("div.datagrid-mask-msg").remove();
_754.children("div.datagrid-mask").remove();
});
},fitColumns:function(jq){
return jq.each(function(){
_648(this);
});
},fixColumnSize:function(jq,_755){
return jq.each(function(){
_666(this,_755);
});
},fixRowHeight:function(jq,_756){
return jq.each(function(){
_5e3(this,_756);
});
},freezeRow:function(jq,_757){
return jq.each(function(){
_5f0(this,_757);
});
},autoSizeColumn:function(jq,_758){
return jq.each(function(){
_65a(this,_758);
});
},loadData:function(jq,data){
return jq.each(function(){
_647(this,data);
_702(this);
});
},getData:function(jq){
return $.data(jq[0],"datagrid").data;
},getRows:function(jq){
return $.data(jq[0],"datagrid").data.rows;
},getFooterRows:function(jq){
return $.data(jq[0],"datagrid").footer;
},getRowIndex:function(jq,id){
return _68f(jq[0],id);
},getChecked:function(jq){
return _695(jq[0]);
},getSelected:function(jq){
var rows=_692(jq[0]);
return rows.length>0?rows[0]:null;
},getSelections:function(jq){
return _692(jq[0]);
},clearSelections:function(jq){
return jq.each(function(){
var _759=$.data(this,"datagrid");
var _75a=_759.selectedRows;
var _75b=_759.checkedRows;
_75a.splice(0,_75a.length);
_6a6(this);
if(_759.options.checkOnSelect){
_75b.splice(0,_75b.length);
}
});
},clearChecked:function(jq){
return jq.each(function(){
var _75c=$.data(this,"datagrid");
var _75d=_75c.selectedRows;
var _75e=_75c.checkedRows;
_75e.splice(0,_75e.length);
_6b6(this);
if(_75c.options.selectOnCheck){
_75d.splice(0,_75d.length);
}
});
},scrollTo:function(jq,_75f){
return jq.each(function(){
_698(this,_75f);
});
},highlightRow:function(jq,_760){
return jq.each(function(){
_628(this,_760);
_698(this,_760);
});
},selectAll:function(jq){
return jq.each(function(){
_6ab(this);
});
},unselectAll:function(jq){
return jq.each(function(){
_6a6(this);
});
},selectRow:function(jq,_761){
return jq.each(function(){
_62f(this,_761);
});
},selectRecord:function(jq,id){
return jq.each(function(){
var opts=$.data(this,"datagrid").options;
if(opts.idField){
var _762=_68f(this,id);
if(_762>=0){
$(this).datagrid("selectRow",_762);
}
}
});
},unselectRow:function(jq,_763){
return jq.each(function(){
_630(this,_763);
});
},checkRow:function(jq,_764){
return jq.each(function(){
_62c(this,_764);
});
},uncheckRow:function(jq,_765){
return jq.each(function(){
_62d(this,_765);
});
},checkAll:function(jq){
return jq.each(function(){
_6b0(this);
});
},uncheckAll:function(jq){
return jq.each(function(){
_6b6(this);
});
},beginEdit:function(jq,_766){
return jq.each(function(){
_6c7(this,_766);
});
},endEdit:function(jq,_767){
return jq.each(function(){
_6cd(this,_767,false);
});
},cancelEdit:function(jq,_768){
return jq.each(function(){
_6cd(this,_768,true);
});
},getEditors:function(jq,_769){
return _6da(jq[0],_769);
},getEditor:function(jq,_76a){
return _6de(jq[0],_76a);
},refreshRow:function(jq,_76b){
return jq.each(function(){
var opts=$.data(this,"datagrid").options;
opts.view.refreshRow.call(opts.view,this,_76b);
});
},validateRow:function(jq,_76c){
return _6cc(jq[0],_76c);
},updateRow:function(jq,_76d){
return jq.each(function(){
var opts=$.data(this,"datagrid").options;
opts.view.updateRow.call(opts.view,this,_76d.index,_76d.row);
});
},appendRow:function(jq,row){
return jq.each(function(){
_6ff(this,row);
});
},insertRow:function(jq,_76e){
return jq.each(function(){
_6fb(this,_76e);
});
},deleteRow:function(jq,_76f){
return jq.each(function(){
_6f5(this,_76f);
});
},getChanges:function(jq,_770){
return _6ef(jq[0],_770);
},acceptChanges:function(jq){
return jq.each(function(){
_706(this);
});
},rejectChanges:function(jq){
return jq.each(function(){
_708(this);
});
},mergeCells:function(jq,_771){
return jq.each(function(){
_71a(this,_771);
});
},showColumn:function(jq,_772){
return jq.each(function(){
var _773=$(this).datagrid("getPanel");
_773.find("td[field=\""+_772+"\"]").show();
$(this).datagrid("getColumnOption",_772).hidden=false;
$(this).datagrid("fitColumns");
});
},hideColumn:function(jq,_774){
return jq.each(function(){
var _775=$(this).datagrid("getPanel");
_775.find("td[field=\""+_774+"\"]").hide();
$(this).datagrid("getColumnOption",_774).hidden=true;
$(this).datagrid("fitColumns");
});
},sort:function(jq,_776){
return jq.each(function(){
_63b(this,_776);
});
}};
$.fn.datagrid.parseOptions=function(_777){
var t=$(_777);
return $.extend({},$.fn.panel.parseOptions(_777),$.parser.parseOptions(_777,["url","toolbar","idField","sortName","sortOrder","pagePosition","resizeHandle",{sharedStyleSheet:"boolean",fitColumns:"boolean",autoRowHeight:"boolean",striped:"boolean",nowrap:"boolean"},{rownumbers:"boolean",singleSelect:"boolean",ctrlSelect:"boolean",checkOnSelect:"boolean",selectOnCheck:"boolean"},{pagination:"boolean",pageSize:"number",pageNumber:"number"},{multiSort:"boolean",remoteSort:"boolean",showHeader:"boolean",showFooter:"boolean"},{scrollbarSize:"number"}]),{pageList:(t.attr("pageList")?eval(t.attr("pageList")):undefined),loadMsg:(t.attr("loadMsg")!=undefined?t.attr("loadMsg"):undefined),rowStyler:(t.attr("rowStyler")?eval(t.attr("rowStyler")):undefined)});
};
$.fn.datagrid.parseData=function(_778){
var t=$(_778);
var data={total:0,rows:[]};
var _779=t.datagrid("getColumnFields",true).concat(t.datagrid("getColumnFields",false));
t.find("tbody tr").each(function(){
data.total++;
var row={};
$.extend(row,$.parser.parseOptions(this,["iconCls","state"]));
for(var i=0;i<_779.length;i++){
row[_779[i]]=$(this).find("td:eq("+i+")").html();
}
data.rows.push(row);
});
return data;
};
var _77a={render:function(_77b,_77c,_77d){
var rows=$(_77b).datagrid("getRows");
$(_77c).html(this.renderTable(_77b,0,rows,_77d));
},renderFooter:function(_77e,_77f,_780){
var opts=$.data(_77e,"datagrid").options;
var rows=$.data(_77e,"datagrid").footer||[];
var _781=$(_77e).datagrid("getColumnFields",_780);
var _782=["<table class=\"datagrid-ftable\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>"];
for(var i=0;i<rows.length;i++){
_782.push("<tr class=\"datagrid-row\" datagrid-row-index=\""+i+"\">");
_782.push(this.renderRow.call(this,_77e,_781,_780,i,rows[i]));
_782.push("</tr>");
}
_782.push("</tbody></table>");
$(_77f).html(_782.join(""));
},renderTable:function(_783,_784,rows,_785){
var _786=$.data(_783,"datagrid");
var opts=_786.options;
if(_785){
if(!(opts.rownumbers||(opts.frozenColumns&&opts.frozenColumns.length))){
return "";
}
}
var _787=$(_783).datagrid("getColumnFields",_785);
var _788=["<table class=\"datagrid-btable\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>"];
for(var i=0;i<rows.length;i++){
var row=rows[i];
var css=opts.rowStyler?opts.rowStyler.call(_783,_784,row):"";
var _789="";
var _78a="";
if(typeof css=="string"){
_78a=css;
}else{
if(css){
_789=css["class"]||"";
_78a=css["style"]||"";
}
}
var cls="class=\"datagrid-row "+(_784%2&&opts.striped?"datagrid-row-alt ":" ")+_789+"\"";
var _78b=_78a?"style=\""+_78a+"\"":"";
var _78c=_786.rowIdPrefix+"-"+(_785?1:2)+"-"+_784;
_788.push("<tr id=\""+_78c+"\" datagrid-row-index=\""+_784+"\" "+cls+" "+_78b+">");
_788.push(this.renderRow.call(this,_783,_787,_785,_784,row));
_788.push("</tr>");
_784++;
}
_788.push("</tbody></table>");
return _788.join("");
},renderRow:function(_78d,_78e,_78f,_790,_791){
var opts=$.data(_78d,"datagrid").options;
var cc=[];
if(_78f&&opts.rownumbers){
var _792=_790+1;
if(opts.pagination){
_792+=(opts.pageNumber-1)*opts.pageSize;
}
cc.push("<td class=\"datagrid-td-rownumber\"><div class=\"datagrid-cell-rownumber\">"+_792+"</div></td>");
}
for(var i=0;i<_78e.length;i++){
var _793=_78e[i];
var col=$(_78d).datagrid("getColumnOption",_793);
if(col){
var _794=_791[_793];
var css=col.styler?(col.styler(_794,_791,_790)||""):"";
var _795="";
var _796="";
if(typeof css=="string"){
_796=css;
}else{
if(css){
_795=css["class"]||"";
_796=css["style"]||"";
}
}
var cls=_795?"class=\""+_795+"\"":"";
var _797=col.hidden?"style=\"display:none;"+_796+"\"":(_796?"style=\""+_796+"\"":"");
cc.push("<td field=\""+_793+"\" "+cls+" "+_797+">");
var _797="";
if(!col.checkbox){
if(col.align){
_797+="text-align:"+col.align+";";
}
if(!opts.nowrap){
_797+="white-space:normal;height:auto;";
}else{
if(opts.autoRowHeight){
_797+="height:auto;";
}
}
}
cc.push("<div style=\""+_797+"\" ");
cc.push(col.checkbox?"class=\"datagrid-cell-check\"":"class=\"datagrid-cell "+col.cellClass+"\"");
cc.push(">");
if(col.checkbox){
cc.push("<input type=\"checkbox\" "+(_791.checked?"checked=\"checked\"":""));
cc.push(" name=\""+_793+"\" value=\""+(_794!=undefined?_794:"")+"\">");
}else{
if(col.formatter){
cc.push(col.formatter(_794,_791,_790));
}else{
cc.push(_794);
}
}
cc.push("</div>");
cc.push("</td>");
}
}
return cc.join("");
},refreshRow:function(_798,_799){
this.updateRow.call(this,_798,_799,{});
},updateRow:function(_79a,_79b,row){
var opts=$.data(_79a,"datagrid").options;
var rows=$(_79a).datagrid("getRows");
var _79c=_79d(_79b);
$.extend(rows[_79b],row);
var _79e=_79d(_79b);
var _79f=_79c.c;
var _7a0=_79e.s;
var _7a1="datagrid-row "+(_79b%2&&opts.striped?"datagrid-row-alt ":" ")+_79e.c;
function _79d(_7a2){
var css=opts.rowStyler?opts.rowStyler.call(_79a,_7a2,rows[_7a2]):"";
var _7a3="";
var _7a4="";
if(typeof css=="string"){
_7a4=css;
}else{
if(css){
_7a3=css["class"]||"";
_7a4=css["style"]||"";
}
}
return {c:_7a3,s:_7a4};
};
function _7a5(_7a6){
var _7a7=$(_79a).datagrid("getColumnFields",_7a6);
var tr=opts.finder.getTr(_79a,_79b,"body",(_7a6?1:2));
var _7a8=tr.find("div.datagrid-cell-check input[type=checkbox]").is(":checked");
tr.html(this.renderRow.call(this,_79a,_7a7,_7a6,_79b,rows[_79b]));
tr.attr("style",_7a0).removeClass(_79f).addClass(_7a1);
if(_7a8){
tr.find("div.datagrid-cell-check input[type=checkbox]")._propAttr("checked",true);
}
};
_7a5.call(this,true);
_7a5.call(this,false);
$(_79a).datagrid("fixRowHeight",_79b);
},insertRow:function(_7a9,_7aa,row){
var _7ab=$.data(_7a9,"datagrid");
var opts=_7ab.options;
var dc=_7ab.dc;
var data=_7ab.data;
if(_7aa==undefined||_7aa==null){
_7aa=data.rows.length;
}
if(_7aa>data.rows.length){
_7aa=data.rows.length;
}
function _7ac(_7ad){
var _7ae=_7ad?1:2;
for(var i=data.rows.length-1;i>=_7aa;i--){
var tr=opts.finder.getTr(_7a9,i,"body",_7ae);
tr.attr("datagrid-row-index",i+1);
tr.attr("id",_7ab.rowIdPrefix+"-"+_7ae+"-"+(i+1));
if(_7ad&&opts.rownumbers){
var _7af=i+2;
if(opts.pagination){
_7af+=(opts.pageNumber-1)*opts.pageSize;
}
tr.find("div.datagrid-cell-rownumber").html(_7af);
}
if(opts.striped){
tr.removeClass("datagrid-row-alt").addClass((i+1)%2?"datagrid-row-alt":"");
}
}
};
function _7b0(_7b1){
var _7b2=_7b1?1:2;
var _7b3=$(_7a9).datagrid("getColumnFields",_7b1);
var _7b4=_7ab.rowIdPrefix+"-"+_7b2+"-"+_7aa;
var tr="<tr id=\""+_7b4+"\" class=\"datagrid-row\" datagrid-row-index=\""+_7aa+"\"></tr>";
if(_7aa>=data.rows.length){
if(data.rows.length){
opts.finder.getTr(_7a9,"","last",_7b2).after(tr);
}else{
var cc=_7b1?dc.body1:dc.body2;
cc.html("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>"+tr+"</tbody></table>");
}
}else{
opts.finder.getTr(_7a9,_7aa+1,"body",_7b2).before(tr);
}
};
_7ac.call(this,true);
_7ac.call(this,false);
_7b0.call(this,true);
_7b0.call(this,false);
data.total+=1;
data.rows.splice(_7aa,0,row);
this.refreshRow.call(this,_7a9,_7aa);
},deleteRow:function(_7b5,_7b6){
var _7b7=$.data(_7b5,"datagrid");
var opts=_7b7.options;
var data=_7b7.data;
function _7b8(_7b9){
var _7ba=_7b9?1:2;
for(var i=_7b6+1;i<data.rows.length;i++){
var tr=opts.finder.getTr(_7b5,i,"body",_7ba);
tr.attr("datagrid-row-index",i-1);
tr.attr("id",_7b7.rowIdPrefix+"-"+_7ba+"-"+(i-1));
if(_7b9&&opts.rownumbers){
var _7bb=i;
if(opts.pagination){
_7bb+=(opts.pageNumber-1)*opts.pageSize;
}
tr.find("div.datagrid-cell-rownumber").html(_7bb);
}
if(opts.striped){
tr.removeClass("datagrid-row-alt").addClass((i-1)%2?"datagrid-row-alt":"");
}
}
};
opts.finder.getTr(_7b5,_7b6).remove();
_7b8.call(this,true);
_7b8.call(this,false);
data.total-=1;
data.rows.splice(_7b6,1);
},onBeforeRender:function(_7bc,rows){
},onAfterRender:function(_7bd){
var _7be=$.data(_7bd,"datagrid");
var opts=_7be.options;
if(opts.showFooter){
var _7bf=$(_7bd).datagrid("getPanel").find("div.datagrid-footer");
_7bf.find("div.datagrid-cell-rownumber,div.datagrid-cell-check").css("visibility","hidden");
}
if(opts.finder.getRows(_7bd).length==0){
this.renderEmptyRow(_7bd);
}
},renderEmptyRow:function(_7c0){
var cols=$.map($(_7c0).datagrid("getColumnFields"),function(_7c1){
return $(_7c0).datagrid("getColumnOption",_7c1);
});
$.map(cols,function(col){
col.formatter1=col.formatter;
col.styler1=col.styler;
col.formatter=col.styler=undefined;
});
var _7c2=$.data(_7c0,"datagrid").dc.body2;
_7c2.html(this.renderTable(_7c0,0,[{}],false));
_7c2.find("tbody *").css({height:1,borderColor:"transparent",background:"transparent"});
var tr=_7c2.find(".datagrid-row");
tr.removeClass("datagrid-row").removeAttr("datagrid-row-index");
tr.find(".datagrid-cell,.datagrid-cell-check").empty();
$.map(cols,function(col){
col.formatter=col.formatter1;
col.styler=col.styler1;
col.formatter1=col.styler1=undefined;
});
}};
$.fn.datagrid.defaults=$.extend({},$.fn.panel.defaults,{sharedStyleSheet:false,frozenColumns:undefined,columns:undefined,fitColumns:false,resizeHandle:"right",autoRowHeight:true,toolbar:null,striped:false,method:"post",nowrap:true,idField:null,url:null,data:null,loadMsg:"Processing, please wait ...",rownumbers:false,singleSelect:false,ctrlSelect:false,selectOnCheck:true,checkOnSelect:true,pagination:false,pagePosition:"bottom",pageNumber:1,pageSize:10,pageList:[10,20,30,40,50],queryParams:{},sortName:null,sortOrder:"asc",multiSort:false,remoteSort:true,showHeader:true,showFooter:false,scrollbarSize:18,rowEvents:{mouseover:_621(true),mouseout:_621(false),click:_629,dblclick:_633,contextmenu:_637},rowStyler:function(_7c3,_7c4){
},loader:function(_7c5,_7c6,_7c7){
var opts=$(this).datagrid("options");
if(!opts.url){
return false;
}
$.ajax({type:opts.method,url:opts.url,data:_7c5,dataType:"json",success:function(data){
_7c6(data);
},error:function(){
_7c7.apply(this,arguments);
}});
},loadFilter:function(data){
if(typeof data.length=="number"&&typeof data.splice=="function"){
return {total:data.length,rows:data};
}else{
return data;
}
},editors:_731,finder:{getTr:function(_7c8,_7c9,type,_7ca){
type=type||"body";
_7ca=_7ca||0;
var _7cb=$.data(_7c8,"datagrid");
var dc=_7cb.dc;
var opts=_7cb.options;
if(_7ca==0){
var tr1=opts.finder.getTr(_7c8,_7c9,type,1);
var tr2=opts.finder.getTr(_7c8,_7c9,type,2);
return tr1.add(tr2);
}else{
if(type=="body"){
var tr=$("#"+_7cb.rowIdPrefix+"-"+_7ca+"-"+_7c9);
if(!tr.length){
tr=(_7ca==1?dc.body1:dc.body2).find(">table>tbody>tr[datagrid-row-index="+_7c9+"]");
}
return tr;
}else{
if(type=="footer"){
return (_7ca==1?dc.footer1:dc.footer2).find(">table>tbody>tr[datagrid-row-index="+_7c9+"]");
}else{
if(type=="selected"){
return (_7ca==1?dc.body1:dc.body2).find(">table>tbody>tr.datagrid-row-selected");
}else{
if(type=="highlight"){
return (_7ca==1?dc.body1:dc.body2).find(">table>tbody>tr.datagrid-row-over");
}else{
if(type=="checked"){
return (_7ca==1?dc.body1:dc.body2).find(">table>tbody>tr.datagrid-row-checked");
}else{
if(type=="editing"){
return (_7ca==1?dc.body1:dc.body2).find(">table>tbody>tr.datagrid-row-editing");
}else{
if(type=="last"){
return (_7ca==1?dc.body1:dc.body2).find(">table>tbody>tr[datagrid-row-index]:last");
}else{
if(type=="allbody"){
return (_7ca==1?dc.body1:dc.body2).find(">table>tbody>tr[datagrid-row-index]");
}else{
if(type=="allfooter"){
return (_7ca==1?dc.footer1:dc.footer2).find(">table>tbody>tr[datagrid-row-index]");
}
}
}
}
}
}
}
}
}
}
},getRow:function(_7cc,p){
var _7cd=(typeof p=="object")?p.attr("datagrid-row-index"):p;
return $.data(_7cc,"datagrid").data.rows[parseInt(_7cd)];
},getRows:function(_7ce){
return $(_7ce).datagrid("getRows");
}},view:_77a,onBeforeLoad:function(_7cf){
},onLoadSuccess:function(){
},onLoadError:function(){
},onClickRow:function(_7d0,_7d1){
},onDblClickRow:function(_7d2,_7d3){
},onClickCell:function(_7d4,_7d5,_7d6){
},onDblClickCell:function(_7d7,_7d8,_7d9){
},onBeforeSortColumn:function(sort,_7da){
},onSortColumn:function(sort,_7db){
},onResizeColumn:function(_7dc,_7dd){
},onBeforeSelect:function(_7de,_7df){
},onSelect:function(_7e0,_7e1){
},onBeforeUnselect:function(_7e2,_7e3){
},onUnselect:function(_7e4,_7e5){
},onSelectAll:function(rows){
},onUnselectAll:function(rows){
},onBeforeCheck:function(_7e6,_7e7){
},onCheck:function(_7e8,_7e9){
},onBeforeUncheck:function(_7ea,_7eb){
},onUncheck:function(_7ec,_7ed){
},onCheckAll:function(rows){
},onUncheckAll:function(rows){
},onBeforeEdit:function(_7ee,_7ef){
},onBeginEdit:function(_7f0,_7f1){
},onEndEdit:function(_7f2,_7f3,_7f4){
},onAfterEdit:function(_7f5,_7f6,_7f7){
},onCancelEdit:function(_7f8,_7f9){
},onHeaderContextMenu:function(e,_7fa){
},onRowContextMenu:function(e,_7fb,_7fc){
}});
})(jQuery);
(function($){
var _7fd;
$(document).unbind(".propertygrid").bind("mousedown.propertygrid",function(e){
var p=$(e.target).closest("div.datagrid-view,div.combo-panel");
if(p.length){
return;
}
_7fe(_7fd);
_7fd=undefined;
});
function _7ff(_800){
var _801=$.data(_800,"propertygrid");
var opts=$.data(_800,"propertygrid").options;
$(_800).datagrid($.extend({},opts,{cls:"propertygrid",view:(opts.showGroup?opts.groupView:opts.view),onBeforeEdit:function(_802,row){
if(opts.onBeforeEdit.call(_800,_802,row)==false){
return false;
}
var dg=$(this);
var row=dg.datagrid("getRows")[_802];
var col=dg.datagrid("getColumnOption","value");
col.editor=row.editor;
},onClickCell:function(_803,_804,_805){
if(_7fd!=this){
_7fe(_7fd);
_7fd=this;
}
if(opts.editIndex!=_803){
_7fe(_7fd);
$(this).datagrid("beginEdit",_803);
var ed=$(this).datagrid("getEditor",{index:_803,field:_804});
if(!ed){
ed=$(this).datagrid("getEditor",{index:_803,field:"value"});
}
if(ed){
var t=$(ed.target);
var _806=t.data("textbox")?t.textbox("textbox"):t;
_806.focus();
opts.editIndex=_803;
}
}
opts.onClickCell.call(_800,_803,_804,_805);
},loadFilter:function(data){
_7fe(this);
return opts.loadFilter.call(this,data);
}}));
};
function _7fe(_807){
var t=$(_807);
if(!t.length){
return;
}
var opts=$.data(_807,"propertygrid").options;
opts.finder.getTr(_807,null,"editing").each(function(){
var _808=parseInt($(this).attr("datagrid-row-index"));
if(t.datagrid("validateRow",_808)){
t.datagrid("endEdit",_808);
}else{
t.datagrid("cancelEdit",_808);
}
});
opts.editIndex=undefined;
};
$.fn.propertygrid=function(_809,_80a){
if(typeof _809=="string"){
var _80b=$.fn.propertygrid.methods[_809];
if(_80b){
return _80b(this,_80a);
}else{
return this.datagrid(_809,_80a);
}
}
_809=_809||{};
return this.each(function(){
var _80c=$.data(this,"propertygrid");
if(_80c){
$.extend(_80c.options,_809);
}else{
var opts=$.extend({},$.fn.propertygrid.defaults,$.fn.propertygrid.parseOptions(this),_809);
opts.frozenColumns=$.extend(true,[],opts.frozenColumns);
opts.columns=$.extend(true,[],opts.columns);
$.data(this,"propertygrid",{options:opts});
}
_7ff(this);
});
};
$.fn.propertygrid.methods={options:function(jq){
return $.data(jq[0],"propertygrid").options;
}};
$.fn.propertygrid.parseOptions=function(_80d){
return $.extend({},$.fn.datagrid.parseOptions(_80d),$.parser.parseOptions(_80d,[{showGroup:"boolean"}]));
};
var _80e=$.extend({},$.fn.datagrid.defaults.view,{render:function(_80f,_810,_811){
var _812=[];
var _813=this.groups;
for(var i=0;i<_813.length;i++){
_812.push(this.renderGroup.call(this,_80f,i,_813[i],_811));
}
$(_810).html(_812.join(""));
},renderGroup:function(_814,_815,_816,_817){
var _818=$.data(_814,"datagrid");
var opts=_818.options;
var _819=$(_814).datagrid("getColumnFields",_817);
var _81a=[];
_81a.push("<div class=\"datagrid-group\" group-index="+_815+">");
_81a.push("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" style=\"height:100%\"><tbody>");
_81a.push("<tr>");
if((_817&&(opts.rownumbers||opts.frozenColumns.length))||(!_817&&!(opts.rownumbers||opts.frozenColumns.length))){
_81a.push("<td style=\"border:0;text-align:center;width:25px\"><span class=\"datagrid-row-expander datagrid-row-collapse\" style=\"display:inline-block;width:16px;height:16px;cursor:pointer\">&nbsp;</span></td>");
}
_81a.push("<td style=\"border:0;\">");
if(!_817){
_81a.push("<span class=\"datagrid-group-title\">");
_81a.push(opts.groupFormatter.call(_814,_816.value,_816.rows));
_81a.push("</span>");
}
_81a.push("</td>");
_81a.push("</tr>");
_81a.push("</tbody></table>");
_81a.push("</div>");
_81a.push("<table class=\"datagrid-btable\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>");
var _81b=_816.startIndex;
for(var j=0;j<_816.rows.length;j++){
var css=opts.rowStyler?opts.rowStyler.call(_814,_81b,_816.rows[j]):"";
var _81c="";
var _81d="";
if(typeof css=="string"){
_81d=css;
}else{
if(css){
_81c=css["class"]||"";
_81d=css["style"]||"";
}
}
var cls="class=\"datagrid-row "+(_81b%2&&opts.striped?"datagrid-row-alt ":" ")+_81c+"\"";
var _81e=_81d?"style=\""+_81d+"\"":"";
var _81f=_818.rowIdPrefix+"-"+(_817?1:2)+"-"+_81b;
_81a.push("<tr id=\""+_81f+"\" datagrid-row-index=\""+_81b+"\" "+cls+" "+_81e+">");
_81a.push(this.renderRow.call(this,_814,_819,_817,_81b,_816.rows[j]));
_81a.push("</tr>");
_81b++;
}
_81a.push("</tbody></table>");
return _81a.join("");
},bindEvents:function(_820){
var _821=$.data(_820,"datagrid");
var dc=_821.dc;
var body=dc.body1.add(dc.body2);
var _822=($.data(body[0],"events")||$._data(body[0],"events")).click[0].handler;
body.unbind("click").bind("click",function(e){
var tt=$(e.target);
var _823=tt.closest("span.datagrid-row-expander");
if(_823.length){
var _824=_823.closest("div.datagrid-group").attr("group-index");
if(_823.hasClass("datagrid-row-collapse")){
$(_820).datagrid("collapseGroup",_824);
}else{
$(_820).datagrid("expandGroup",_824);
}
}else{
_822(e);
}
e.stopPropagation();
});
},onBeforeRender:function(_825,rows){
var _826=$.data(_825,"datagrid");
var opts=_826.options;
_827();
var _828=[];
for(var i=0;i<rows.length;i++){
var row=rows[i];
var _829=_82a(row[opts.groupField]);
if(!_829){
_829={value:row[opts.groupField],rows:[row]};
_828.push(_829);
}else{
_829.rows.push(row);
}
}
var _82b=0;
var _82c=[];
for(var i=0;i<_828.length;i++){
var _829=_828[i];
_829.startIndex=_82b;
_82b+=_829.rows.length;
_82c=_82c.concat(_829.rows);
}
_826.data.rows=_82c;
this.groups=_828;
var that=this;
setTimeout(function(){
that.bindEvents(_825);
},0);
function _82a(_82d){
for(var i=0;i<_828.length;i++){
var _82e=_828[i];
if(_82e.value==_82d){
return _82e;
}
}
return null;
};
function _827(){
if(!$("#datagrid-group-style").length){
$("head").append("<style id=\"datagrid-group-style\">"+".datagrid-group{height:25px;overflow:hidden;font-weight:bold;border-bottom:1px solid #ccc;}"+"</style>");
}
};
}});
$.extend($.fn.datagrid.methods,{expandGroup:function(jq,_82f){
return jq.each(function(){
var view=$.data(this,"datagrid").dc.view;
var _830=view.find(_82f!=undefined?"div.datagrid-group[group-index=\""+_82f+"\"]":"div.datagrid-group");
var _831=_830.find("span.datagrid-row-expander");
if(_831.hasClass("datagrid-row-expand")){
_831.removeClass("datagrid-row-expand").addClass("datagrid-row-collapse");
_830.next("table").show();
}
$(this).datagrid("fixRowHeight");
});
},collapseGroup:function(jq,_832){
return jq.each(function(){
var view=$.data(this,"datagrid").dc.view;
var _833=view.find(_832!=undefined?"div.datagrid-group[group-index=\""+_832+"\"]":"div.datagrid-group");
var _834=_833.find("span.datagrid-row-expander");
if(_834.hasClass("datagrid-row-collapse")){
_834.removeClass("datagrid-row-collapse").addClass("datagrid-row-expand");
_833.next("table").hide();
}
$(this).datagrid("fixRowHeight");
});
}});
$.extend(_80e,{refreshGroupTitle:function(_835,_836){
var _837=$.data(_835,"datagrid");
var opts=_837.options;
var dc=_837.dc;
var _838=this.groups[_836];
var span=dc.body2.children("div.datagrid-group[group-index="+_836+"]").find("span.datagrid-group-title");
span.html(opts.groupFormatter.call(_835,_838.value,_838.rows));
},insertRow:function(_839,_83a,row){
var _83b=$.data(_839,"datagrid");
var opts=_83b.options;
var dc=_83b.dc;
var _83c=null;
var _83d;
for(var i=0;i<this.groups.length;i++){
if(this.groups[i].value==row[opts.groupField]){
_83c=this.groups[i];
_83d=i;
break;
}
}
if(_83c){
if(_83a==undefined||_83a==null){
_83a=_83b.data.rows.length;
}
if(_83a<_83c.startIndex){
_83a=_83c.startIndex;
}else{
if(_83a>_83c.startIndex+_83c.rows.length){
_83a=_83c.startIndex+_83c.rows.length;
}
}
$.fn.datagrid.defaults.view.insertRow.call(this,_839,_83a,row);
if(_83a>=_83c.startIndex+_83c.rows.length){
_83e(_83a,true);
_83e(_83a,false);
}
_83c.rows.splice(_83a-_83c.startIndex,0,row);
}else{
_83c={value:row[opts.groupField],rows:[row],startIndex:_83b.data.rows.length};
_83d=this.groups.length;
dc.body1.append(this.renderGroup.call(this,_839,_83d,_83c,true));
dc.body2.append(this.renderGroup.call(this,_839,_83d,_83c,false));
this.groups.push(_83c);
_83b.data.rows.push(row);
}
this.refreshGroupTitle(_839,_83d);
function _83e(_83f,_840){
var _841=_840?1:2;
var _842=opts.finder.getTr(_839,_83f-1,"body",_841);
var tr=opts.finder.getTr(_839,_83f,"body",_841);
tr.insertAfter(_842);
};
},updateRow:function(_843,_844,row){
var opts=$.data(_843,"datagrid").options;
$.fn.datagrid.defaults.view.updateRow.call(this,_843,_844,row);
var tb=opts.finder.getTr(_843,_844,"body",2).closest("table.datagrid-btable");
var _845=parseInt(tb.prev().attr("group-index"));
this.refreshGroupTitle(_843,_845);
},deleteRow:function(_846,_847){
var _848=$.data(_846,"datagrid");
var opts=_848.options;
var dc=_848.dc;
var body=dc.body1.add(dc.body2);
var tb=opts.finder.getTr(_846,_847,"body",2).closest("table.datagrid-btable");
var _849=parseInt(tb.prev().attr("group-index"));
$.fn.datagrid.defaults.view.deleteRow.call(this,_846,_847);
var _84a=this.groups[_849];
if(_84a.rows.length>1){
_84a.rows.splice(_847-_84a.startIndex,1);
this.refreshGroupTitle(_846,_849);
}else{
body.children("div.datagrid-group[group-index="+_849+"]").remove();
for(var i=_849+1;i<this.groups.length;i++){
body.children("div.datagrid-group[group-index="+i+"]").attr("group-index",i-1);
}
this.groups.splice(_849,1);
}
var _847=0;
for(var i=0;i<this.groups.length;i++){
var _84a=this.groups[i];
_84a.startIndex=_847;
_847+=_84a.rows.length;
}
}});
$.fn.propertygrid.defaults=$.extend({},$.fn.datagrid.defaults,{singleSelect:true,remoteSort:false,fitColumns:true,loadMsg:"",frozenColumns:[[{field:"f",width:16,resizable:false}]],columns:[[{field:"name",title:"Name",width:100,sortable:true},{field:"value",title:"Value",width:100,resizable:false}]],showGroup:false,groupView:_80e,groupField:"group",groupFormatter:function(_84b,rows){
return _84b;
}});
})(jQuery);
(function($){
function _84c(_84d){
var _84e=$.data(_84d,"treegrid");
var opts=_84e.options;
$(_84d).datagrid($.extend({},opts,{url:null,data:null,loader:function(){
return false;
},onBeforeLoad:function(){
return false;
},onLoadSuccess:function(){
},onResizeColumn:function(_84f,_850){
_85d(_84d);
opts.onResizeColumn.call(_84d,_84f,_850);
},onBeforeSortColumn:function(sort,_851){
if(opts.onBeforeSortColumn.call(_84d,sort,_851)==false){
return false;
}
},onSortColumn:function(sort,_852){
opts.sortName=sort;
opts.sortOrder=_852;
if(opts.remoteSort){
_85c(_84d);
}else{
var data=$(_84d).treegrid("getData");
_873(_84d,0,data);
}
opts.onSortColumn.call(_84d,sort,_852);
},onClickCell:function(_853,_854){
opts.onClickCell.call(_84d,_854,find(_84d,_853));
},onDblClickCell:function(_855,_856){
opts.onDblClickCell.call(_84d,_856,find(_84d,_855));
},onRowContextMenu:function(e,_857){
opts.onContextMenu.call(_84d,e,find(_84d,_857));
}}));
var _858=$.data(_84d,"datagrid").options;
opts.columns=_858.columns;
opts.frozenColumns=_858.frozenColumns;
_84e.dc=$.data(_84d,"datagrid").dc;
if(opts.pagination){
var _859=$(_84d).datagrid("getPager");
_859.pagination({pageNumber:opts.pageNumber,pageSize:opts.pageSize,pageList:opts.pageList,onSelectPage:function(_85a,_85b){
opts.pageNumber=_85a;
opts.pageSize=_85b;
_85c(_84d);
}});
opts.pageSize=_859.pagination("options").pageSize;
}
};
function _85d(_85e,_85f){
var opts=$.data(_85e,"datagrid").options;
var dc=$.data(_85e,"datagrid").dc;
if(!dc.body1.is(":empty")&&(!opts.nowrap||opts.autoRowHeight)){
if(_85f!=undefined){
var _860=_861(_85e,_85f);
for(var i=0;i<_860.length;i++){
_862(_860[i][opts.idField]);
}
}
}
$(_85e).datagrid("fixRowHeight",_85f);
function _862(_863){
var tr1=opts.finder.getTr(_85e,_863,"body",1);
var tr2=opts.finder.getTr(_85e,_863,"body",2);
tr1.css("height","");
tr2.css("height","");
var _864=Math.max(tr1.height(),tr2.height());
tr1.css("height",_864);
tr2.css("height",_864);
};
};
function _865(_866){
var dc=$.data(_866,"datagrid").dc;
var opts=$.data(_866,"treegrid").options;
if(!opts.rownumbers){
return;
}
dc.body1.find("div.datagrid-cell-rownumber").each(function(i){
$(this).html(i+1);
});
};
function _867(_868){
return function(e){
$.fn.datagrid.defaults.rowEvents[_868?"mouseover":"mouseout"](e);
var tt=$(e.target);
var fn=_868?"addClass":"removeClass";
if(tt.hasClass("tree-hit")){
tt.hasClass("tree-expanded")?tt[fn]("tree-expanded-hover"):tt[fn]("tree-collapsed-hover");
}
};
};
function _869(e){
var tt=$(e.target);
if(tt.hasClass("tree-hit")){
var tr=tt.closest("tr.datagrid-row");
var _86a=tr.closest("div.datagrid-view").children(".datagrid-f")[0];
_86b(_86a,tr.attr("node-id"));
}else{
$.fn.datagrid.defaults.rowEvents.click(e);
}
};
function _86c(_86d,_86e){
var opts=$.data(_86d,"treegrid").options;
var tr1=opts.finder.getTr(_86d,_86e,"body",1);
var tr2=opts.finder.getTr(_86d,_86e,"body",2);
var _86f=$(_86d).datagrid("getColumnFields",true).length+(opts.rownumbers?1:0);
var _870=$(_86d).datagrid("getColumnFields",false).length;
_871(tr1,_86f);
_871(tr2,_870);
function _871(tr,_872){
$("<tr class=\"treegrid-tr-tree\">"+"<td style=\"border:0px\" colspan=\""+_872+"\">"+"<div></div>"+"</td>"+"</tr>").insertAfter(tr);
};
};
function _873(_874,_875,data,_876){
var _877=$.data(_874,"treegrid");
var opts=_877.options;
var dc=_877.dc;
data=opts.loadFilter.call(_874,data,_875);
var node=find(_874,_875);
if(node){
var _878=opts.finder.getTr(_874,_875,"body",1);
var _879=opts.finder.getTr(_874,_875,"body",2);
var cc1=_878.next("tr.treegrid-tr-tree").children("td").children("div");
var cc2=_879.next("tr.treegrid-tr-tree").children("td").children("div");
if(!_876){
node.children=[];
}
}else{
var cc1=dc.body1;
var cc2=dc.body2;
if(!_876){
_877.data=[];
}
}
if(!_876){
cc1.empty();
cc2.empty();
}
if(opts.view.onBeforeRender){
opts.view.onBeforeRender.call(opts.view,_874,_875,data);
}
opts.view.render.call(opts.view,_874,cc1,true);
opts.view.render.call(opts.view,_874,cc2,false);
if(opts.showFooter){
opts.view.renderFooter.call(opts.view,_874,dc.footer1,true);
opts.view.renderFooter.call(opts.view,_874,dc.footer2,false);
}
if(opts.view.onAfterRender){
opts.view.onAfterRender.call(opts.view,_874);
}
if(!_875&&opts.pagination){
var _87a=$.data(_874,"treegrid").total;
var _87b=$(_874).datagrid("getPager");
if(_87b.pagination("options").total!=_87a){
_87b.pagination({total:_87a});
}
}
_85d(_874);
_865(_874);
$(_874).treegrid("showLines");
$(_874).treegrid("setSelectionState");
$(_874).treegrid("autoSizeColumn");
opts.onLoadSuccess.call(_874,node,data);
};
function _85c(_87c,_87d,_87e,_87f,_880){
var opts=$.data(_87c,"treegrid").options;
var body=$(_87c).datagrid("getPanel").find("div.datagrid-body");
if(_87e){
opts.queryParams=_87e;
}
var _881=$.extend({},opts.queryParams);
if(opts.pagination){
$.extend(_881,{page:opts.pageNumber,rows:opts.pageSize});
}
if(opts.sortName){
$.extend(_881,{sort:opts.sortName,order:opts.sortOrder});
}
var row=find(_87c,_87d);
if(opts.onBeforeLoad.call(_87c,row,_881)==false){
return;
}
var _882=body.find("tr[node-id=\""+_87d+"\"] span.tree-folder");
_882.addClass("tree-loading");
$(_87c).treegrid("loading");
var _883=opts.loader.call(_87c,_881,function(data){
_882.removeClass("tree-loading");
$(_87c).treegrid("loaded");
_873(_87c,_87d,data,_87f);
if(_880){
_880();
}
},function(){
_882.removeClass("tree-loading");
$(_87c).treegrid("loaded");
opts.onLoadError.apply(_87c,arguments);
if(_880){
_880();
}
});
if(_883==false){
_882.removeClass("tree-loading");
$(_87c).treegrid("loaded");
}
};
function _884(_885){
var rows=_886(_885);
if(rows.length){
return rows[0];
}else{
return null;
}
};
function _886(_887){
return $.data(_887,"treegrid").data;
};
function _888(_889,_88a){
var row=find(_889,_88a);
if(row._parentId){
return find(_889,row._parentId);
}else{
return null;
}
};
function _861(_88b,_88c){
var opts=$.data(_88b,"treegrid").options;
var body=$(_88b).datagrid("getPanel").find("div.datagrid-view2 div.datagrid-body");
var _88d=[];
if(_88c){
_88e(_88c);
}else{
var _88f=_886(_88b);
for(var i=0;i<_88f.length;i++){
_88d.push(_88f[i]);
_88e(_88f[i][opts.idField]);
}
}
function _88e(_890){
var _891=find(_88b,_890);
if(_891&&_891.children){
for(var i=0,len=_891.children.length;i<len;i++){
var _892=_891.children[i];
_88d.push(_892);
_88e(_892[opts.idField]);
}
}
};
return _88d;
};
function _893(_894,_895){
if(!_895){
return 0;
}
var opts=$.data(_894,"treegrid").options;
var view=$(_894).datagrid("getPanel").children("div.datagrid-view");
var node=view.find("div.datagrid-body tr[node-id=\""+_895+"\"]").children("td[field=\""+opts.treeField+"\"]");
return node.find("span.tree-indent,span.tree-hit").length;
};
function find(_896,_897){
var opts=$.data(_896,"treegrid").options;
var data=$.data(_896,"treegrid").data;
var cc=[data];
while(cc.length){
var c=cc.shift();
for(var i=0;i<c.length;i++){
var node=c[i];
if(node[opts.idField]==_897){
return node;
}else{
if(node["children"]){
cc.push(node["children"]);
}
}
}
}
return null;
};
function _898(_899,_89a){
var opts=$.data(_899,"treegrid").options;
var row=find(_899,_89a);
var tr=opts.finder.getTr(_899,_89a);
var hit=tr.find("span.tree-hit");
if(hit.length==0){
return;
}
if(hit.hasClass("tree-collapsed")){
return;
}
if(opts.onBeforeCollapse.call(_899,row)==false){
return;
}
hit.removeClass("tree-expanded tree-expanded-hover").addClass("tree-collapsed");
hit.next().removeClass("tree-folder-open");
row.state="closed";
tr=tr.next("tr.treegrid-tr-tree");
var cc=tr.children("td").children("div");
if(opts.animate){
cc.slideUp("normal",function(){
$(_899).treegrid("autoSizeColumn");
_85d(_899,_89a);
opts.onCollapse.call(_899,row);
});
}else{
cc.hide();
$(_899).treegrid("autoSizeColumn");
_85d(_899,_89a);
opts.onCollapse.call(_899,row);
}
};
function _89b(_89c,_89d){
var opts=$.data(_89c,"treegrid").options;
var tr=opts.finder.getTr(_89c,_89d);
var hit=tr.find("span.tree-hit");
var row=find(_89c,_89d);
if(hit.length==0){
return;
}
if(hit.hasClass("tree-expanded")){
return;
}
if(opts.onBeforeExpand.call(_89c,row)==false){
return;
}
hit.removeClass("tree-collapsed tree-collapsed-hover").addClass("tree-expanded");
hit.next().addClass("tree-folder-open");
var _89e=tr.next("tr.treegrid-tr-tree");
if(_89e.length){
var cc=_89e.children("td").children("div");
_89f(cc);
}else{
_86c(_89c,row[opts.idField]);
var _89e=tr.next("tr.treegrid-tr-tree");
var cc=_89e.children("td").children("div");
cc.hide();
var _8a0=$.extend({},opts.queryParams||{});
_8a0.id=row[opts.idField];
_85c(_89c,row[opts.idField],_8a0,true,function(){
if(cc.is(":empty")){
_89e.remove();
}else{
_89f(cc);
}
});
}
function _89f(cc){
row.state="open";
if(opts.animate){
cc.slideDown("normal",function(){
$(_89c).treegrid("autoSizeColumn");
_85d(_89c,_89d);
opts.onExpand.call(_89c,row);
});
}else{
cc.show();
$(_89c).treegrid("autoSizeColumn");
_85d(_89c,_89d);
opts.onExpand.call(_89c,row);
}
};
};
function _86b(_8a1,_8a2){
var opts=$.data(_8a1,"treegrid").options;
var tr=opts.finder.getTr(_8a1,_8a2);
var hit=tr.find("span.tree-hit");
if(hit.hasClass("tree-expanded")){
_898(_8a1,_8a2);
}else{
_89b(_8a1,_8a2);
}
};
function _8a3(_8a4,_8a5){
var opts=$.data(_8a4,"treegrid").options;
var _8a6=_861(_8a4,_8a5);
if(_8a5){
_8a6.unshift(find(_8a4,_8a5));
}
for(var i=0;i<_8a6.length;i++){
_898(_8a4,_8a6[i][opts.idField]);
}
};
function _8a7(_8a8,_8a9){
var opts=$.data(_8a8,"treegrid").options;
var _8aa=_861(_8a8,_8a9);
if(_8a9){
_8aa.unshift(find(_8a8,_8a9));
}
for(var i=0;i<_8aa.length;i++){
_89b(_8a8,_8aa[i][opts.idField]);
}
};
function _8ab(_8ac,_8ad){
var opts=$.data(_8ac,"treegrid").options;
var ids=[];
var p=_888(_8ac,_8ad);
while(p){
var id=p[opts.idField];
ids.unshift(id);
p=_888(_8ac,id);
}
for(var i=0;i<ids.length;i++){
_89b(_8ac,ids[i]);
}
};
function _8ae(_8af,_8b0){
var opts=$.data(_8af,"treegrid").options;
if(_8b0.parent){
var tr=opts.finder.getTr(_8af,_8b0.parent);
if(tr.next("tr.treegrid-tr-tree").length==0){
_86c(_8af,_8b0.parent);
}
var cell=tr.children("td[field=\""+opts.treeField+"\"]").children("div.datagrid-cell");
var _8b1=cell.children("span.tree-icon");
if(_8b1.hasClass("tree-file")){
_8b1.removeClass("tree-file").addClass("tree-folder tree-folder-open");
var hit=$("<span class=\"tree-hit tree-expanded\"></span>").insertBefore(_8b1);
if(hit.prev().length){
hit.prev().remove();
}
}
}
_873(_8af,_8b0.parent,_8b0.data,true);
};
function _8b2(_8b3,_8b4){
var ref=_8b4.before||_8b4.after;
var opts=$.data(_8b3,"treegrid").options;
var _8b5=_888(_8b3,ref);
_8ae(_8b3,{parent:(_8b5?_8b5[opts.idField]:null),data:[_8b4.data]});
var _8b6=_8b5?_8b5.children:$(_8b3).treegrid("getRoots");
for(var i=0;i<_8b6.length;i++){
if(_8b6[i][opts.idField]==ref){
var _8b7=_8b6[_8b6.length-1];
_8b6.splice(_8b4.before?i:(i+1),0,_8b7);
_8b6.splice(_8b6.length-1,1);
break;
}
}
_8b8(true);
_8b8(false);
_865(_8b3);
$(_8b3).treegrid("showLines");
function _8b8(_8b9){
var _8ba=_8b9?1:2;
var tr=opts.finder.getTr(_8b3,_8b4.data[opts.idField],"body",_8ba);
var _8bb=tr.closest("table.datagrid-btable");
tr=tr.parent().children();
var dest=opts.finder.getTr(_8b3,ref,"body",_8ba);
if(_8b4.before){
tr.insertBefore(dest);
}else{
var sub=dest.next("tr.treegrid-tr-tree");
tr.insertAfter(sub.length?sub:dest);
}
_8bb.remove();
};
};
function _8bc(_8bd,_8be){
var _8bf=$.data(_8bd,"treegrid");
$(_8bd).datagrid("deleteRow",_8be);
_865(_8bd);
_8bf.total-=1;
$(_8bd).datagrid("getPager").pagination("refresh",{total:_8bf.total});
$(_8bd).treegrid("showLines");
};
function _8c0(_8c1){
var t=$(_8c1);
var opts=t.treegrid("options");
if(opts.lines){
t.treegrid("getPanel").addClass("tree-lines");
}else{
t.treegrid("getPanel").removeClass("tree-lines");
return;
}
t.treegrid("getPanel").find("span.tree-indent").removeClass("tree-line tree-join tree-joinbottom");
t.treegrid("getPanel").find("div.datagrid-cell").removeClass("tree-node-last tree-root-first tree-root-one");
var _8c2=t.treegrid("getRoots");
if(_8c2.length>1){
_8c3(_8c2[0]).addClass("tree-root-first");
}else{
if(_8c2.length==1){
_8c3(_8c2[0]).addClass("tree-root-one");
}
}
_8c4(_8c2);
_8c5(_8c2);
function _8c4(_8c6){
$.map(_8c6,function(node){
if(node.children&&node.children.length){
_8c4(node.children);
}else{
var cell=_8c3(node);
cell.find(".tree-icon").prev().addClass("tree-join");
}
});
if(_8c6.length){
var cell=_8c3(_8c6[_8c6.length-1]);
cell.addClass("tree-node-last");
cell.find(".tree-join").removeClass("tree-join").addClass("tree-joinbottom");
}
};
function _8c5(_8c7){
$.map(_8c7,function(node){
if(node.children&&node.children.length){
_8c5(node.children);
}
});
for(var i=0;i<_8c7.length-1;i++){
var node=_8c7[i];
var _8c8=t.treegrid("getLevel",node[opts.idField]);
var tr=opts.finder.getTr(_8c1,node[opts.idField]);
var cc=tr.next().find("tr.datagrid-row td[field=\""+opts.treeField+"\"] div.datagrid-cell");
cc.find("span:eq("+(_8c8-1)+")").addClass("tree-line");
}
};
function _8c3(node){
var tr=opts.finder.getTr(_8c1,node[opts.idField]);
var cell=tr.find("td[field=\""+opts.treeField+"\"] div.datagrid-cell");
return cell;
};
};
$.fn.treegrid=function(_8c9,_8ca){
if(typeof _8c9=="string"){
var _8cb=$.fn.treegrid.methods[_8c9];
if(_8cb){
return _8cb(this,_8ca);
}else{
return this.datagrid(_8c9,_8ca);
}
}
_8c9=_8c9||{};
return this.each(function(){
var _8cc=$.data(this,"treegrid");
if(_8cc){
$.extend(_8cc.options,_8c9);
}else{
_8cc=$.data(this,"treegrid",{options:$.extend({},$.fn.treegrid.defaults,$.fn.treegrid.parseOptions(this),_8c9),data:[]});
}
_84c(this);
if(_8cc.options.data){
$(this).treegrid("loadData",_8cc.options.data);
}
_85c(this);
});
};
$.fn.treegrid.methods={options:function(jq){
return $.data(jq[0],"treegrid").options;
},resize:function(jq,_8cd){
return jq.each(function(){
$(this).datagrid("resize",_8cd);
});
},fixRowHeight:function(jq,_8ce){
return jq.each(function(){
_85d(this,_8ce);
});
},loadData:function(jq,data){
return jq.each(function(){
_873(this,data.parent,data);
});
},load:function(jq,_8cf){
return jq.each(function(){
$(this).treegrid("options").pageNumber=1;
$(this).treegrid("getPager").pagination({pageNumber:1});
$(this).treegrid("reload",_8cf);
});
},reload:function(jq,id){
return jq.each(function(){
var opts=$(this).treegrid("options");
var _8d0={};
if(typeof id=="object"){
_8d0=id;
}else{
_8d0=$.extend({},opts.queryParams);
_8d0.id=id;
}
if(_8d0.id){
var node=$(this).treegrid("find",_8d0.id);
if(node.children){
node.children.splice(0,node.children.length);
}
opts.queryParams=_8d0;
var tr=opts.finder.getTr(this,_8d0.id);
tr.next("tr.treegrid-tr-tree").remove();
tr.find("span.tree-hit").removeClass("tree-expanded tree-expanded-hover").addClass("tree-collapsed");
_89b(this,_8d0.id);
}else{
_85c(this,null,_8d0);
}
});
},reloadFooter:function(jq,_8d1){
return jq.each(function(){
var opts=$.data(this,"treegrid").options;
var dc=$.data(this,"datagrid").dc;
if(_8d1){
$.data(this,"treegrid").footer=_8d1;
}
if(opts.showFooter){
opts.view.renderFooter.call(opts.view,this,dc.footer1,true);
opts.view.renderFooter.call(opts.view,this,dc.footer2,false);
if(opts.view.onAfterRender){
opts.view.onAfterRender.call(opts.view,this);
}
$(this).treegrid("fixRowHeight");
}
});
},getData:function(jq){
return $.data(jq[0],"treegrid").data;
},getFooterRows:function(jq){
return $.data(jq[0],"treegrid").footer;
},getRoot:function(jq){
return _884(jq[0]);
},getRoots:function(jq){
return _886(jq[0]);
},getParent:function(jq,id){
return _888(jq[0],id);
},getChildren:function(jq,id){
return _861(jq[0],id);
},getLevel:function(jq,id){
return _893(jq[0],id);
},find:function(jq,id){
return find(jq[0],id);
},isLeaf:function(jq,id){
var opts=$.data(jq[0],"treegrid").options;
var tr=opts.finder.getTr(jq[0],id);
var hit=tr.find("span.tree-hit");
return hit.length==0;
},select:function(jq,id){
return jq.each(function(){
$(this).datagrid("selectRow",id);
});
},unselect:function(jq,id){
return jq.each(function(){
$(this).datagrid("unselectRow",id);
});
},collapse:function(jq,id){
return jq.each(function(){
_898(this,id);
});
},expand:function(jq,id){
return jq.each(function(){
_89b(this,id);
});
},toggle:function(jq,id){
return jq.each(function(){
_86b(this,id);
});
},collapseAll:function(jq,id){
return jq.each(function(){
_8a3(this,id);
});
},expandAll:function(jq,id){
return jq.each(function(){
_8a7(this,id);
});
},expandTo:function(jq,id){
return jq.each(function(){
_8ab(this,id);
});
},append:function(jq,_8d2){
return jq.each(function(){
_8ae(this,_8d2);
});
},insert:function(jq,_8d3){
return jq.each(function(){
_8b2(this,_8d3);
});
},remove:function(jq,id){
return jq.each(function(){
_8bc(this,id);
});
},pop:function(jq,id){
var row=jq.treegrid("find",id);
jq.treegrid("remove",id);
return row;
},refresh:function(jq,id){
return jq.each(function(){
var opts=$.data(this,"treegrid").options;
opts.view.refreshRow.call(opts.view,this,id);
});
},update:function(jq,_8d4){
return jq.each(function(){
var opts=$.data(this,"treegrid").options;
opts.view.updateRow.call(opts.view,this,_8d4.id,_8d4.row);
});
},beginEdit:function(jq,id){
return jq.each(function(){
$(this).datagrid("beginEdit",id);
$(this).treegrid("fixRowHeight",id);
});
},endEdit:function(jq,id){
return jq.each(function(){
$(this).datagrid("endEdit",id);
});
},cancelEdit:function(jq,id){
return jq.each(function(){
$(this).datagrid("cancelEdit",id);
});
},showLines:function(jq){
return jq.each(function(){
_8c0(this);
});
}};
$.fn.treegrid.parseOptions=function(_8d5){
return $.extend({},$.fn.datagrid.parseOptions(_8d5),$.parser.parseOptions(_8d5,["treeField",{animate:"boolean"}]));
};
var _8d6=$.extend({},$.fn.datagrid.defaults.view,{render:function(_8d7,_8d8,_8d9){
var opts=$.data(_8d7,"treegrid").options;
var _8da=$(_8d7).datagrid("getColumnFields",_8d9);
var _8db=$.data(_8d7,"datagrid").rowIdPrefix;
if(_8d9){
if(!(opts.rownumbers||(opts.frozenColumns&&opts.frozenColumns.length))){
return;
}
}
var view=this;
if(this.treeNodes&&this.treeNodes.length){
var _8dc=_8dd(_8d9,this.treeLevel,this.treeNodes);
$(_8d8).append(_8dc.join(""));
}
function _8dd(_8de,_8df,_8e0){
var _8e1=$(_8d7).treegrid("getParent",_8e0[0][opts.idField]);
var _8e2=(_8e1?_8e1.children.length:$(_8d7).treegrid("getRoots").length)-_8e0.length;
var _8e3=["<table class=\"datagrid-btable\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>"];
for(var i=0;i<_8e0.length;i++){
var row=_8e0[i];
if(row.state!="open"&&row.state!="closed"){
row.state="open";
}
var css=opts.rowStyler?opts.rowStyler.call(_8d7,row):"";
var _8e4="";
var _8e5="";
if(typeof css=="string"){
_8e5=css;
}else{
if(css){
_8e4=css["class"]||"";
_8e5=css["style"]||"";
}
}
var cls="class=\"datagrid-row "+(_8e2++%2&&opts.striped?"datagrid-row-alt ":" ")+_8e4+"\"";
var _8e6=_8e5?"style=\""+_8e5+"\"":"";
var _8e7=_8db+"-"+(_8de?1:2)+"-"+row[opts.idField];
_8e3.push("<tr id=\""+_8e7+"\" node-id=\""+row[opts.idField]+"\" "+cls+" "+_8e6+">");
_8e3=_8e3.concat(view.renderRow.call(view,_8d7,_8da,_8de,_8df,row));
_8e3.push("</tr>");
if(row.children&&row.children.length){
var tt=_8dd(_8de,_8df+1,row.children);
var v=row.state=="closed"?"none":"block";
_8e3.push("<tr class=\"treegrid-tr-tree\"><td style=\"border:0px\" colspan="+(_8da.length+(opts.rownumbers?1:0))+"><div style=\"display:"+v+"\">");
_8e3=_8e3.concat(tt);
_8e3.push("</div></td></tr>");
}
}
_8e3.push("</tbody></table>");
return _8e3;
};
},renderFooter:function(_8e8,_8e9,_8ea){
var opts=$.data(_8e8,"treegrid").options;
var rows=$.data(_8e8,"treegrid").footer||[];
var _8eb=$(_8e8).datagrid("getColumnFields",_8ea);
var _8ec=["<table class=\"datagrid-ftable\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>"];
for(var i=0;i<rows.length;i++){
var row=rows[i];
row[opts.idField]=row[opts.idField]||("foot-row-id"+i);
_8ec.push("<tr class=\"datagrid-row\" node-id=\""+row[opts.idField]+"\">");
_8ec.push(this.renderRow.call(this,_8e8,_8eb,_8ea,0,row));
_8ec.push("</tr>");
}
_8ec.push("</tbody></table>");
$(_8e9).html(_8ec.join(""));
},renderRow:function(_8ed,_8ee,_8ef,_8f0,row){
var opts=$.data(_8ed,"treegrid").options;
var cc=[];
if(_8ef&&opts.rownumbers){
cc.push("<td class=\"datagrid-td-rownumber\"><div class=\"datagrid-cell-rownumber\">0</div></td>");
}
for(var i=0;i<_8ee.length;i++){
var _8f1=_8ee[i];
var col=$(_8ed).datagrid("getColumnOption",_8f1);
if(col){
var css=col.styler?(col.styler(row[_8f1],row)||""):"";
var _8f2="";
var _8f3="";
if(typeof css=="string"){
_8f3=css;
}else{
if(cc){
_8f2=css["class"]||"";
_8f3=css["style"]||"";
}
}
var cls=_8f2?"class=\""+_8f2+"\"":"";
var _8f4=col.hidden?"style=\"display:none;"+_8f3+"\"":(_8f3?"style=\""+_8f3+"\"":"");
cc.push("<td field=\""+_8f1+"\" "+cls+" "+_8f4+">");
var _8f4="";
if(!col.checkbox){
if(col.align){
_8f4+="text-align:"+col.align+";";
}
if(!opts.nowrap){
_8f4+="white-space:normal;height:auto;";
}else{
if(opts.autoRowHeight){
_8f4+="height:auto;";
}
}
}
cc.push("<div style=\""+_8f4+"\" ");
if(col.checkbox){
cc.push("class=\"datagrid-cell-check ");
}else{
cc.push("class=\"datagrid-cell "+col.cellClass);
}
cc.push("\">");
if(col.checkbox){
if(row.checked){
cc.push("<input type=\"checkbox\" checked=\"checked\"");
}else{
cc.push("<input type=\"checkbox\"");
}
cc.push(" name=\""+_8f1+"\" value=\""+(row[_8f1]!=undefined?row[_8f1]:"")+"\">");
}else{
var val=null;
if(col.formatter){
val=col.formatter(row[_8f1],row);
}else{
val=row[_8f1];
}
if(_8f1==opts.treeField){
for(var j=0;j<_8f0;j++){
cc.push("<span class=\"tree-indent\"></span>");
}
if(row.state=="closed"){
cc.push("<span class=\"tree-hit tree-collapsed\"></span>");
cc.push("<span class=\"tree-icon tree-folder "+(row.iconCls?row.iconCls:"")+"\"></span>");
}else{
if(row.children&&row.children.length){
cc.push("<span class=\"tree-hit tree-expanded\"></span>");
cc.push("<span class=\"tree-icon tree-folder tree-folder-open "+(row.iconCls?row.iconCls:"")+"\"></span>");
}else{
cc.push("<span class=\"tree-indent\"></span>");
cc.push("<span class=\"tree-icon tree-file "+(row.iconCls?row.iconCls:"")+"\"></span>");
}
}
cc.push("<span class=\"tree-title\">"+val+"</span>");
}else{
cc.push(val);
}
}
cc.push("</div>");
cc.push("</td>");
}
}
return cc.join("");
},refreshRow:function(_8f5,id){
this.updateRow.call(this,_8f5,id,{});
},updateRow:function(_8f6,id,row){
var opts=$.data(_8f6,"treegrid").options;
var _8f7=$(_8f6).treegrid("find",id);
$.extend(_8f7,row);
var _8f8=$(_8f6).treegrid("getLevel",id)-1;
var _8f9=opts.rowStyler?opts.rowStyler.call(_8f6,_8f7):"";
var _8fa=$.data(_8f6,"datagrid").rowIdPrefix;
var _8fb=_8f7[opts.idField];
function _8fc(_8fd){
var _8fe=$(_8f6).treegrid("getColumnFields",_8fd);
var tr=opts.finder.getTr(_8f6,id,"body",(_8fd?1:2));
var _8ff=tr.find("div.datagrid-cell-rownumber").html();
var _900=tr.find("div.datagrid-cell-check input[type=checkbox]").is(":checked");
tr.html(this.renderRow(_8f6,_8fe,_8fd,_8f8,_8f7));
tr.attr("style",_8f9||"");
tr.find("div.datagrid-cell-rownumber").html(_8ff);
if(_900){
tr.find("div.datagrid-cell-check input[type=checkbox]")._propAttr("checked",true);
}
if(_8fb!=id){
tr.attr("id",_8fa+"-"+(_8fd?1:2)+"-"+_8fb);
tr.attr("node-id",_8fb);
}
};
_8fc.call(this,true);
_8fc.call(this,false);
$(_8f6).treegrid("fixRowHeight",id);
},deleteRow:function(_901,id){
var opts=$.data(_901,"treegrid").options;
var tr=opts.finder.getTr(_901,id);
tr.next("tr.treegrid-tr-tree").remove();
tr.remove();
var _902=del(id);
if(_902){
if(_902.children.length==0){
tr=opts.finder.getTr(_901,_902[opts.idField]);
tr.next("tr.treegrid-tr-tree").remove();
var cell=tr.children("td[field=\""+opts.treeField+"\"]").children("div.datagrid-cell");
cell.find(".tree-icon").removeClass("tree-folder").addClass("tree-file");
cell.find(".tree-hit").remove();
$("<span class=\"tree-indent\"></span>").prependTo(cell);
}
}
function del(id){
var cc;
var _903=$(_901).treegrid("getParent",id);
if(_903){
cc=_903.children;
}else{
cc=$(_901).treegrid("getData");
}
for(var i=0;i<cc.length;i++){
if(cc[i][opts.idField]==id){
cc.splice(i,1);
break;
}
}
return _903;
};
},onBeforeRender:function(_904,_905,data){
if($.isArray(_905)){
data={total:_905.length,rows:_905};
_905=null;
}
if(!data){
return false;
}
var _906=$.data(_904,"treegrid");
var opts=_906.options;
if(data.length==undefined){
if(data.footer){
_906.footer=data.footer;
}
if(data.total){
_906.total=data.total;
}
data=this.transfer(_904,_905,data.rows);
}else{
function _907(_908,_909){
for(var i=0;i<_908.length;i++){
var row=_908[i];
row._parentId=_909;
if(row.children&&row.children.length){
_907(row.children,row[opts.idField]);
}
}
};
_907(data,_905);
}
var node=find(_904,_905);
if(node){
if(node.children){
node.children=node.children.concat(data);
}else{
node.children=data;
}
}else{
_906.data=_906.data.concat(data);
}
this.sort(_904,data);
this.treeNodes=data;
this.treeLevel=$(_904).treegrid("getLevel",_905);
},sort:function(_90a,data){
var opts=$.data(_90a,"treegrid").options;
if(!opts.remoteSort&&opts.sortName){
var _90b=opts.sortName.split(",");
var _90c=opts.sortOrder.split(",");
_90d(data);
}
function _90d(rows){
rows.sort(function(r1,r2){
var r=0;
for(var i=0;i<_90b.length;i++){
var sn=_90b[i];
var so=_90c[i];
var col=$(_90a).treegrid("getColumnOption",sn);
var _90e=col.sorter||function(a,b){
return a==b?0:(a>b?1:-1);
};
r=_90e(r1[sn],r2[sn])*(so=="asc"?1:-1);
if(r!=0){
return r;
}
}
return r;
});
for(var i=0;i<rows.length;i++){
var _90f=rows[i].children;
if(_90f&&_90f.length){
_90d(_90f);
}
}
};
},transfer:function(_910,_911,data){
var opts=$.data(_910,"treegrid").options;
var rows=[];
for(var i=0;i<data.length;i++){
rows.push(data[i]);
}
var _912=[];
for(var i=0;i<rows.length;i++){
var row=rows[i];
if(!_911){
if(!row._parentId){
_912.push(row);
rows.splice(i,1);
i--;
}
}else{
if(row._parentId==_911){
_912.push(row);
rows.splice(i,1);
i--;
}
}
}
var toDo=[];
for(var i=0;i<_912.length;i++){
toDo.push(_912[i]);
}
while(toDo.length){
var node=toDo.shift();
for(var i=0;i<rows.length;i++){
var row=rows[i];
if(row._parentId==node[opts.idField]){
if(node.children){
node.children.push(row);
}else{
node.children=[row];
}
toDo.push(row);
rows.splice(i,1);
i--;
}
}
}
return _912;
}});
$.fn.treegrid.defaults=$.extend({},$.fn.datagrid.defaults,{treeField:null,lines:false,animate:false,singleSelect:true,view:_8d6,rowEvents:$.extend({},$.fn.datagrid.defaults.rowEvents,{mouseover:_867(true),mouseout:_867(false),click:_869}),loader:function(_913,_914,_915){
var opts=$(this).treegrid("options");
if(!opts.url){
return false;
}
$.ajax({type:opts.method,url:opts.url,data:_913,dataType:"json",success:function(data){
_914(data);
},error:function(){
_915.apply(this,arguments);
}});
},loadFilter:function(data,_916){
return data;
},finder:{getTr:function(_917,id,type,_918){
type=type||"body";
_918=_918||0;
var dc=$.data(_917,"datagrid").dc;
if(_918==0){
var opts=$.data(_917,"treegrid").options;
var tr1=opts.finder.getTr(_917,id,type,1);
var tr2=opts.finder.getTr(_917,id,type,2);
return tr1.add(tr2);
}else{
if(type=="body"){
var tr=$("#"+$.data(_917,"datagrid").rowIdPrefix+"-"+_918+"-"+id);
if(!tr.length){
tr=(_918==1?dc.body1:dc.body2).find("tr[node-id=\""+id+"\"]");
}
return tr;
}else{
if(type=="footer"){
return (_918==1?dc.footer1:dc.footer2).find("tr[node-id=\""+id+"\"]");
}else{
if(type=="selected"){
return (_918==1?dc.body1:dc.body2).find("tr.datagrid-row-selected");
}else{
if(type=="highlight"){
return (_918==1?dc.body1:dc.body2).find("tr.datagrid-row-over");
}else{
if(type=="checked"){
return (_918==1?dc.body1:dc.body2).find("tr.datagrid-row-checked");
}else{
if(type=="last"){
return (_918==1?dc.body1:dc.body2).find("tr:last[node-id]");
}else{
if(type=="allbody"){
return (_918==1?dc.body1:dc.body2).find("tr[node-id]");
}else{
if(type=="allfooter"){
return (_918==1?dc.footer1:dc.footer2).find("tr[node-id]");
}
}
}
}
}
}
}
}
}
},getRow:function(_919,p){
var id=(typeof p=="object")?p.attr("node-id"):p;
return $(_919).treegrid("find",id);
},getRows:function(_91a){
return $(_91a).treegrid("getChildren");
}},onBeforeLoad:function(row,_91b){
},onLoadSuccess:function(row,data){
},onLoadError:function(){
},onBeforeCollapse:function(row){
},onCollapse:function(row){
},onBeforeExpand:function(row){
},onExpand:function(row){
},onClickRow:function(row){
},onDblClickRow:function(row){
},onClickCell:function(_91c,row){
},onDblClickCell:function(_91d,row){
},onContextMenu:function(e,row){
},onBeforeEdit:function(row){
},onAfterEdit:function(row,_91e){
},onCancelEdit:function(row){
}});
})(jQuery);
(function($){
function _91f(_920){
var opts=$.data(_920,"datalist").options;
$(_920).datagrid($.extend({},opts,{cls:"datalist"+(opts.lines?" datalist-lines":""),frozenColumns:(opts.frozenColumns&&opts.frozenColumns.length)?opts.frozenColumns:(opts.checkbox?[[{field:"_ck",checkbox:true}]]:undefined),columns:(opts.columns&&opts.columns.length)?opts.columns:[[{field:opts.textField,width:"100%",formatter:function(_921,row,_922){
return opts.textFormatter?opts.textFormatter(_921,row,_922):_921;
}}]]}));
};
var _923=$.extend({},$.fn.datagrid.defaults.view,{render:function(_924,_925,_926){
var _927=$.data(_924,"datagrid");
var opts=_927.options;
if(opts.groupField){
var g=this.groupRows(_924,_927.data.rows);
this.groups=g.groups;
_927.data.rows=g.rows;
var _928=[];
for(var i=0;i<g.groups.length;i++){
_928.push(this.renderGroup.call(this,_924,i,g.groups[i],_926));
}
$(_925).html(_928.join(""));
}else{
$(_925).html(this.renderTable(_924,0,_927.data.rows,_926));
}
},renderGroup:function(_929,_92a,_92b,_92c){
var _92d=$.data(_929,"datagrid");
var opts=_92d.options;
var _92e=$(_929).datagrid("getColumnFields",_92c);
var _92f=[];
_92f.push("<div class=\"datagrid-group\" group-index="+_92a+">");
if(!_92c){
_92f.push("<span class=\"datagrid-group-title\">");
_92f.push(opts.groupFormatter.call(_929,_92b.value,_92b.rows));
_92f.push("</span>");
}
_92f.push("</div>");
_92f.push(this.renderTable(_929,_92b.startIndex,_92b.rows,_92c));
return _92f.join("");
},groupRows:function(_930,rows){
var _931=$.data(_930,"datagrid");
var opts=_931.options;
var _932=[];
for(var i=0;i<rows.length;i++){
var row=rows[i];
var _933=_934(row[opts.groupField]);
if(!_933){
_933={value:row[opts.groupField],rows:[row]};
_932.push(_933);
}else{
_933.rows.push(row);
}
}
var _935=0;
var rows=[];
for(var i=0;i<_932.length;i++){
var _933=_932[i];
_933.startIndex=_935;
_935+=_933.rows.length;
rows=rows.concat(_933.rows);
}
return {groups:_932,rows:rows};
function _934(_936){
for(var i=0;i<_932.length;i++){
var _937=_932[i];
if(_937.value==_936){
return _937;
}
}
return null;
};
}});
$.fn.datalist=function(_938,_939){
if(typeof _938=="string"){
var _93a=$.fn.datalist.methods[_938];
if(_93a){
return _93a(this,_939);
}else{
return this.datagrid(_938,_939);
}
}
_938=_938||{};
return this.each(function(){
var _93b=$.data(this,"datalist");
if(_93b){
$.extend(_93b.options,_938);
}else{
var opts=$.extend({},$.fn.datalist.defaults,$.fn.datalist.parseOptions(this),_938);
opts.columns=$.extend(true,[],opts.columns);
_93b=$.data(this,"datalist",{options:opts});
}
_91f(this);
if(!_93b.options.data){
var data=$.fn.datalist.parseData(this);
if(data.total){
$(this).datalist("loadData",data);
}
}
});
};
$.fn.datalist.methods={options:function(jq){
return $.data(jq[0],"datalist").options;
}};
$.fn.datalist.parseOptions=function(_93c){
return $.extend({},$.fn.datagrid.parseOptions(_93c),$.parser.parseOptions(_93c,["valueField","textField","groupField",{checkbox:"boolean",lines:"boolean"}]));
};
$.fn.datalist.parseData=function(_93d){
var opts=$.data(_93d,"datalist").options;
var data={total:0,rows:[]};
$(_93d).children().each(function(){
var _93e=$.parser.parseOptions(this,["value","group"]);
var row={};
var html=$(this).html();
row[opts.valueField]=_93e.value!=undefined?_93e.value:html;
row[opts.textField]=html;
if(opts.groupField){
row[opts.groupField]=_93e.group;
}
data.total++;
data.rows.push(row);
});
return data;
};
$.fn.datalist.defaults=$.extend({},$.fn.datagrid.defaults,{fitColumns:true,singleSelect:true,showHeader:false,checkbox:false,lines:false,valueField:"value",textField:"text",groupField:"",view:_923,textFormatter:function(_93f,row){
return _93f;
},groupFormatter:function(_940,rows){
return _940;
}});
})(jQuery);
(function($){
$(function(){
$(document).unbind(".combo").bind("mousedown.combo mousewheel.combo",function(e){
var p=$(e.target).closest("span.combo,div.combo-p,div.menu");
if(p.length){
_941(p);
return;
}
$("body>div.combo-p>div.combo-panel:visible").panel("close");
});
});
function _942(_943){
var _944=$.data(_943,"combo");
var opts=_944.options;
if(!_944.panel){
_944.panel=$("<div class=\"combo-panel\"></div>").appendTo("body");
_944.panel.panel({minWidth:opts.panelMinWidth,maxWidth:opts.panelMaxWidth,minHeight:opts.panelMinHeight,maxHeight:opts.panelMaxHeight,doSize:false,closed:true,cls:"combo-p",style:{position:"absolute",zIndex:10},onOpen:function(){
var _945=$(this).panel("options").comboTarget;
var _946=$.data(_945,"combo");
if(_946){
_946.options.onShowPanel.call(_945);
}
},onBeforeClose:function(){
_941(this);
},onClose:function(){
var _947=$(this).panel("options").comboTarget;
var _948=$(_947).data("combo");
if(_948){
_948.options.onHidePanel.call(_947);
}
}});
}
var _949=$.extend(true,[],opts.icons);
if(opts.hasDownArrow){
_949.push({iconCls:"combo-arrow",handler:function(e){
_94d(e.data.target);
}});
}
$(_943).addClass("combo-f").textbox($.extend({},opts,{icons:_949,onChange:function(){
}}));
$(_943).attr("comboName",$(_943).attr("textboxName"));
_944.combo=$(_943).next();
_944.combo.addClass("combo");
};
function _94a(_94b){
var _94c=$.data(_94b,"combo");
var opts=_94c.options;
var p=_94c.panel;
if(p.is(":visible")){
p.panel("close");
}
if(!opts.cloned){
p.panel("destroy");
}
$(_94b).textbox("destroy");
};
function _94d(_94e){
var _94f=$.data(_94e,"combo").panel;
if(_94f.is(":visible")){
_950(_94e);
}else{
var p=$(_94e).closest("div.combo-panel");
$("div.combo-panel:visible").not(_94f).not(p).panel("close");
$(_94e).combo("showPanel");
}
$(_94e).combo("textbox").focus();
};
function _941(_951){
$(_951).find(".combo-f").each(function(){
var p=$(this).combo("panel");
if(p.is(":visible")){
p.panel("close");
}
});
};
function _952(e){
var _953=e.data.target;
var _954=$.data(_953,"combo");
var opts=_954.options;
var _955=_954.panel;
if(!opts.editable){
_94d(_953);
}else{
var p=$(_953).closest("div.combo-panel");
$("div.combo-panel:visible").not(_955).not(p).panel("close");
}
};
function _956(e){
var _957=e.data.target;
var t=$(_957);
var _958=t.data("combo");
var opts=t.combo("options");
switch(e.keyCode){
case 38:
opts.keyHandler.up.call(_957,e);
break;
case 40:
opts.keyHandler.down.call(_957,e);
break;
case 37:
opts.keyHandler.left.call(_957,e);
break;
case 39:
opts.keyHandler.right.call(_957,e);
break;
case 13:
e.preventDefault();
opts.keyHandler.enter.call(_957,e);
return false;
case 9:
case 27:
_950(_957);
break;
default:
if(opts.editable){
if(_958.timer){
clearTimeout(_958.timer);
}
_958.timer=setTimeout(function(){
var q=t.combo("getText");
if(_958.previousText!=q){
_958.previousText=q;
t.combo("showPanel");
opts.keyHandler.query.call(_957,q,e);
t.combo("validate");
}
},opts.delay);
}
}
};
function _959(_95a){
var _95b=$.data(_95a,"combo");
var _95c=_95b.combo;
var _95d=_95b.panel;
var opts=$(_95a).combo("options");
var _95e=_95d.panel("options");
_95e.comboTarget=_95a;
if(_95e.closed){
_95d.panel("panel").show().css({zIndex:($.fn.menu?$.fn.menu.defaults.zIndex++:$.fn.window.defaults.zIndex++),left:-999999});
_95d.panel("resize",{width:(opts.panelWidth?opts.panelWidth:_95c._outerWidth()),height:opts.panelHeight});
_95d.panel("panel").hide();
_95d.panel("open");
}
(function(){
if(_95d.is(":visible")){
_95d.panel("move",{left:_95f(),top:_960()});
setTimeout(arguments.callee,200);
}
})();
function _95f(){
var left=_95c.offset().left;
if(opts.panelAlign=="right"){
left+=_95c._outerWidth()-_95d._outerWidth();
}
if(left+_95d._outerWidth()>$(window)._outerWidth()+$(document).scrollLeft()){
left=$(window)._outerWidth()+$(document).scrollLeft()-_95d._outerWidth();
}
if(left<0){
left=0;
}
return left;
};
function _960(){
var top=_95c.offset().top+_95c._outerHeight();
if(top+_95d._outerHeight()>$(window)._outerHeight()+$(document).scrollTop()){
top=_95c.offset().top-_95d._outerHeight();
}
if(top<$(document).scrollTop()){
top=_95c.offset().top+_95c._outerHeight();
}
return top;
};
};
function _950(_961){
var _962=$.data(_961,"combo").panel;
_962.panel("close");
};
function _963(_964,text){
var _965=$.data(_964,"combo");
var _966=$(_964).textbox("getText");
if(_966!=text){
$(_964).textbox("setText",text);
_965.previousText=text;
}
};
function _967(_968){
var _969=[];
var _96a=$.data(_968,"combo").combo;
_96a.find(".textbox-value").each(function(){
_969.push($(this).val());
});
return _969;
};
function _96b(_96c,_96d){
var _96e=$.data(_96c,"combo");
var opts=_96e.options;
var _96f=_96e.combo;
if(!$.isArray(_96d)){
_96d=_96d.split(opts.separator);
}
var _970=_967(_96c);
_96f.find(".textbox-value").remove();
var name=$(_96c).attr("textboxName")||"";
for(var i=0;i<_96d.length;i++){
var _971=$("<input type=\"hidden\" class=\"textbox-value\">").appendTo(_96f);
_971.attr("name",name);
if(opts.disabled){
_971.attr("disabled","disabled");
}
_971.val(_96d[i]);
}
var _972=(function(){
if(_970.length!=_96d.length){
return true;
}
var a1=$.extend(true,[],_970);
var a2=$.extend(true,[],_96d);
a1.sort();
a2.sort();
for(var i=0;i<a1.length;i++){
if(a1[i]!=a2[i]){
return true;
}
}
return false;
})();
if(_972){
if(opts.multiple){
opts.onChange.call(_96c,_96d,_970);
}else{
opts.onChange.call(_96c,_96d[0],_970[0]);
}
$(_96c).closest("form").trigger("_change",[_96c]);
}
};
function _973(_974){
var _975=_967(_974);
return _975[0];
};
function _976(_977,_978){
_96b(_977,[_978]);
};
function _979(_97a){
var opts=$.data(_97a,"combo").options;
var _97b=opts.onChange;
opts.onChange=function(){
};
if(opts.multiple){
_96b(_97a,opts.value?opts.value:[]);
}else{
_976(_97a,opts.value);
}
opts.onChange=_97b;
};
$.fn.combo=function(_97c,_97d){
if(typeof _97c=="string"){
var _97e=$.fn.combo.methods[_97c];
if(_97e){
return _97e(this,_97d);
}else{
return this.textbox(_97c,_97d);
}
}
_97c=_97c||{};
return this.each(function(){
var _97f=$.data(this,"combo");
if(_97f){
$.extend(_97f.options,_97c);
if(_97c.value!=undefined){
_97f.options.originalValue=_97c.value;
}
}else{
_97f=$.data(this,"combo",{options:$.extend({},$.fn.combo.defaults,$.fn.combo.parseOptions(this),_97c),previousText:""});
_97f.options.originalValue=_97f.options.value;
}
_942(this);
_979(this);
});
};
$.fn.combo.methods={options:function(jq){
var opts=jq.textbox("options");
return $.extend($.data(jq[0],"combo").options,{width:opts.width,height:opts.height,disabled:opts.disabled,readonly:opts.readonly});
},cloneFrom:function(jq,from){
return jq.each(function(){
$(this).textbox("cloneFrom",from);
$.data(this,"combo",{options:$.extend(true,{cloned:true},$(from).combo("options")),combo:$(this).next(),panel:$(from).combo("panel")});
$(this).addClass("combo-f").attr("comboName",$(this).attr("textboxName"));
});
},panel:function(jq){
return $.data(jq[0],"combo").panel;
},destroy:function(jq){
return jq.each(function(){
_94a(this);
});
},showPanel:function(jq){
return jq.each(function(){
_959(this);
});
},hidePanel:function(jq){
return jq.each(function(){
_950(this);
});
},clear:function(jq){
return jq.each(function(){
$(this).textbox("setText","");
var opts=$.data(this,"combo").options;
if(opts.multiple){
$(this).combo("setValues",[]);
}else{
$(this).combo("setValue","");
}
});
},reset:function(jq){
return jq.each(function(){
var opts=$.data(this,"combo").options;
if(opts.multiple){
$(this).combo("setValues",opts.originalValue);
}else{
$(this).combo("setValue",opts.originalValue);
}
});
},setText:function(jq,text){
return jq.each(function(){
_963(this,text);
});
},getValues:function(jq){
return _967(jq[0]);
},setValues:function(jq,_980){
return jq.each(function(){
_96b(this,_980);
});
},getValue:function(jq){
return _973(jq[0]);
},setValue:function(jq,_981){
return jq.each(function(){
_976(this,_981);
});
}};
$.fn.combo.parseOptions=function(_982){
var t=$(_982);
return $.extend({},$.fn.textbox.parseOptions(_982),$.parser.parseOptions(_982,["separator","panelAlign",{panelWidth:"number",hasDownArrow:"boolean",delay:"number",selectOnNavigation:"boolean"},{panelMinWidth:"number",panelMaxWidth:"number",panelMinHeight:"number",panelMaxHeight:"number"}]),{panelHeight:(t.attr("panelHeight")=="auto"?"auto":parseInt(t.attr("panelHeight"))||undefined),multiple:(t.attr("multiple")?true:undefined)});
};
$.fn.combo.defaults=$.extend({},$.fn.textbox.defaults,{inputEvents:{click:_952,keydown:_956,paste:_956,drop:_956},panelWidth:null,panelHeight:200,panelMinWidth:null,panelMaxWidth:null,panelMinHeight:null,panelMaxHeight:null,panelAlign:"left",multiple:false,selectOnNavigation:true,separator:",",hasDownArrow:true,delay:200,keyHandler:{up:function(e){
},down:function(e){
},left:function(e){
},right:function(e){
},enter:function(e){
},query:function(q,e){
}},onShowPanel:function(){
},onHidePanel:function(){
},onChange:function(_983,_984){
}});
})(jQuery);
(function($){
var _985=0;
function _986(_987,_988){
var _989=$.data(_987,"combobox");
var opts=_989.options;
var data=_989.data;
for(var i=0;i<data.length;i++){
if(data[i][opts.valueField]==_988){
return i;
}
}
return -1;
};
function _98a(_98b,_98c){
var opts=$.data(_98b,"combobox").options;
var _98d=$(_98b).combo("panel");
var item=opts.finder.getEl(_98b,_98c);
if(item.length){
if(item.position().top<=0){
var h=_98d.scrollTop()+item.position().top;
_98d.scrollTop(h);
}else{
if(item.position().top+item.outerHeight()>_98d.height()){
var h=_98d.scrollTop()+item.position().top+item.outerHeight()-_98d.height();
_98d.scrollTop(h);
}
}
}
};
function nav(_98e,dir){
var opts=$.data(_98e,"combobox").options;
var _98f=$(_98e).combobox("panel");
var item=_98f.children("div.combobox-item-hover");
if(!item.length){
item=_98f.children("div.combobox-item-selected");
}
item.removeClass("combobox-item-hover");
var _990="div.combobox-item:visible:not(.combobox-item-disabled):first";
var _991="div.combobox-item:visible:not(.combobox-item-disabled):last";
if(!item.length){
item=_98f.children(dir=="next"?_990:_991);
}else{
if(dir=="next"){
item=item.nextAll(_990);
if(!item.length){
item=_98f.children(_990);
}
}else{
item=item.prevAll(_990);
if(!item.length){
item=_98f.children(_991);
}
}
}
if(item.length){
item.addClass("combobox-item-hover");
var row=opts.finder.getRow(_98e,item);
if(row){
_98a(_98e,row[opts.valueField]);
if(opts.selectOnNavigation){
_992(_98e,row[opts.valueField]);
}
}
}
};
function _992(_993,_994){
var opts=$.data(_993,"combobox").options;
var _995=$(_993).combo("getValues");
if($.inArray(_994+"",_995)==-1){
if(opts.multiple){
_995.push(_994);
}else{
_995=[_994];
}
_996(_993,_995);
opts.onSelect.call(_993,opts.finder.getRow(_993,_994));
}
};
function _997(_998,_999){
var opts=$.data(_998,"combobox").options;
var _99a=$(_998).combo("getValues");
var _99b=$.inArray(_999+"",_99a);
if(_99b>=0){
_99a.splice(_99b,1);
_996(_998,_99a);
opts.onUnselect.call(_998,opts.finder.getRow(_998,_999));
}
};
function _996(_99c,_99d,_99e){
var opts=$.data(_99c,"combobox").options;
var _99f=$(_99c).combo("panel");
if(!$.isArray(_99d)){
_99d=_99d.split(opts.separator);
}
_99f.find("div.combobox-item-selected").removeClass("combobox-item-selected");
var vv=[],ss=[];
for(var i=0;i<_99d.length;i++){
var v=_99d[i];
var s=v;
opts.finder.getEl(_99c,v).addClass("combobox-item-selected");
var row=opts.finder.getRow(_99c,v);
if(row){
s=row[opts.textField];
}
vv.push(v);
ss.push(s);
}
if(!_99e){
$(_99c).combo("setText",ss.join(opts.separator));
}
$(_99c).combo("setValues",vv);
};
function _9a0(_9a1,data,_9a2){
var _9a3=$.data(_9a1,"combobox");
var opts=_9a3.options;
_9a3.data=opts.loadFilter.call(_9a1,data);
_9a3.groups=[];
data=_9a3.data;
var _9a4=$(_9a1).combobox("getValues");
var dd=[];
var _9a5=undefined;
for(var i=0;i<data.length;i++){
var row=data[i];
var v=row[opts.valueField]+"";
var s=row[opts.textField];
var g=row[opts.groupField];
if(g){
if(_9a5!=g){
_9a5=g;
_9a3.groups.push(g);
dd.push("<div id=\""+(_9a3.groupIdPrefix+"_"+(_9a3.groups.length-1))+"\" class=\"combobox-group\">");
dd.push(opts.groupFormatter?opts.groupFormatter.call(_9a1,g):g);
dd.push("</div>");
}
}else{
_9a5=undefined;
}
var cls="combobox-item"+(row.disabled?" combobox-item-disabled":"")+(g?" combobox-gitem":"");
dd.push("<div id=\""+(_9a3.itemIdPrefix+"_"+i)+"\" class=\""+cls+"\">");
dd.push(opts.formatter?opts.formatter.call(_9a1,row):s);
dd.push("</div>");
if(row["selected"]&&$.inArray(v,_9a4)==-1){
_9a4.push(v);
}
}
$(_9a1).combo("panel").html(dd.join(""));
if(opts.multiple){
_996(_9a1,_9a4,_9a2);
}else{
_996(_9a1,_9a4.length?[_9a4[_9a4.length-1]]:[],_9a2);
}
opts.onLoadSuccess.call(_9a1,data);
};
function _9a6(_9a7,url,_9a8,_9a9){
var opts=$.data(_9a7,"combobox").options;
if(url){
opts.url=url;
}
_9a8=$.extend({},opts.queryParams,_9a8||{});
if(opts.onBeforeLoad.call(_9a7,_9a8)==false){
return;
}
opts.loader.call(_9a7,_9a8,function(data){
_9a0(_9a7,data,_9a9);
},function(){
opts.onLoadError.apply(this,arguments);
});
};
function _9aa(_9ab,q){
var _9ac=$.data(_9ab,"combobox");
var opts=_9ac.options;
var qq=opts.multiple?q.split(opts.separator):[q];
if(opts.mode=="remote"){
_9ad(qq);
_9a6(_9ab,null,{q:q},true);
}else{
var _9ae=$(_9ab).combo("panel");
_9ae.find("div.combobox-item-selected,div.combobox-item-hover").removeClass("combobox-item-selected combobox-item-hover");
_9ae.find("div.combobox-item,div.combobox-group").hide();
var data=_9ac.data;
var vv=[];
$.map(qq,function(q){
q=$.trim(q);
var _9af=q;
var _9b0=undefined;
for(var i=0;i<data.length;i++){
var row=data[i];
if(opts.filter.call(_9ab,q,row)){
var v=row[opts.valueField];
var s=row[opts.textField];
var g=row[opts.groupField];
var item=opts.finder.getEl(_9ab,v).show();
if(s.toLowerCase()==q.toLowerCase()){
_9af=v;
item.addClass("combobox-item-selected");
opts.onSelect.call(_9ab,row);
}
if(opts.groupField&&_9b0!=g){
$("#"+_9ac.groupIdPrefix+"_"+$.inArray(g,_9ac.groups)).show();
_9b0=g;
}
}
}
vv.push(_9af);
});
_9ad(vv);
}
function _9ad(vv){
_996(_9ab,opts.multiple?(q?vv:[]):vv,true);
};
};
function _9b1(_9b2){
var t=$(_9b2);
var opts=t.combobox("options");
var _9b3=t.combobox("panel");
var item=_9b3.children("div.combobox-item-hover");
if(item.length){
var row=opts.finder.getRow(_9b2,item);
var _9b4=row[opts.valueField];
if(opts.multiple){
if(item.hasClass("combobox-item-selected")){
t.combobox("unselect",_9b4);
}else{
t.combobox("select",_9b4);
}
}else{
t.combobox("select",_9b4);
}
}
var vv=[];
$.map(t.combobox("getValues"),function(v){
if(_986(_9b2,v)>=0){
vv.push(v);
}
});
t.combobox("setValues",vv);
if(!opts.multiple){
t.combobox("hidePanel");
}
};
function _9b5(_9b6){
var _9b7=$.data(_9b6,"combobox");
var opts=_9b7.options;
_985++;
_9b7.itemIdPrefix="_easyui_combobox_i"+_985;
_9b7.groupIdPrefix="_easyui_combobox_g"+_985;
$(_9b6).addClass("combobox-f");
$(_9b6).combo($.extend({},opts,{onShowPanel:function(){
$(_9b6).combo("panel").find("div.combobox-item:hidden,div.combobox-group:hidden").show();
_98a(_9b6,$(_9b6).combobox("getValue"));
opts.onShowPanel.call(_9b6);
}}));
$(_9b6).combo("panel").unbind().bind("mouseover",function(e){
$(this).children("div.combobox-item-hover").removeClass("combobox-item-hover");
var item=$(e.target).closest("div.combobox-item");
if(!item.hasClass("combobox-item-disabled")){
item.addClass("combobox-item-hover");
}
e.stopPropagation();
}).bind("mouseout",function(e){
$(e.target).closest("div.combobox-item").removeClass("combobox-item-hover");
e.stopPropagation();
}).bind("click",function(e){
var item=$(e.target).closest("div.combobox-item");
if(!item.length||item.hasClass("combobox-item-disabled")){
return;
}
var row=opts.finder.getRow(_9b6,item);
if(!row){
return;
}
var _9b8=row[opts.valueField];
if(opts.multiple){
if(item.hasClass("combobox-item-selected")){
_997(_9b6,_9b8);
}else{
_992(_9b6,_9b8);
}
}else{
_992(_9b6,_9b8);
$(_9b6).combo("hidePanel");
}
e.stopPropagation();
});
};
$.fn.combobox=function(_9b9,_9ba){
if(typeof _9b9=="string"){
var _9bb=$.fn.combobox.methods[_9b9];
if(_9bb){
return _9bb(this,_9ba);
}else{
return this.combo(_9b9,_9ba);
}
}
_9b9=_9b9||{};
return this.each(function(){
var _9bc=$.data(this,"combobox");
if(_9bc){
$.extend(_9bc.options,_9b9);
}else{
_9bc=$.data(this,"combobox",{options:$.extend({},$.fn.combobox.defaults,$.fn.combobox.parseOptions(this),_9b9),data:[]});
}
_9b5(this);
if(_9bc.options.data){
_9a0(this,_9bc.options.data);
}else{
var data=$.fn.combobox.parseData(this);
if(data.length){
_9a0(this,data);
}
}
_9a6(this);
});
};
$.fn.combobox.methods={options:function(jq){
var _9bd=jq.combo("options");
return $.extend($.data(jq[0],"combobox").options,{width:_9bd.width,height:_9bd.height,originalValue:_9bd.originalValue,disabled:_9bd.disabled,readonly:_9bd.readonly});
},getData:function(jq){
return $.data(jq[0],"combobox").data;
},setValues:function(jq,_9be){
return jq.each(function(){
_996(this,_9be);
});
},setValue:function(jq,_9bf){
return jq.each(function(){
_996(this,[_9bf]);
});
},clear:function(jq){
return jq.each(function(){
$(this).combo("clear");
var _9c0=$(this).combo("panel");
_9c0.find("div.combobox-item-selected").removeClass("combobox-item-selected");
});
},reset:function(jq){
return jq.each(function(){
var opts=$(this).combobox("options");
if(opts.multiple){
$(this).combobox("setValues",opts.originalValue);
}else{
$(this).combobox("setValue",opts.originalValue);
}
});
},loadData:function(jq,data){
return jq.each(function(){
_9a0(this,data);
});
},reload:function(jq,url){
return jq.each(function(){
if(typeof url=="string"){
_9a6(this,url);
}else{
if(url){
var opts=$(this).combobox("options");
opts.queryParams=url;
}
_9a6(this);
}
});
},select:function(jq,_9c1){
return jq.each(function(){
_992(this,_9c1);
});
},unselect:function(jq,_9c2){
return jq.each(function(){
_997(this,_9c2);
});
}};
$.fn.combobox.parseOptions=function(_9c3){
var t=$(_9c3);
return $.extend({},$.fn.combo.parseOptions(_9c3),$.parser.parseOptions(_9c3,["valueField","textField","groupField","mode","method","url"]));
};
$.fn.combobox.parseData=function(_9c4){
var data=[];
var opts=$(_9c4).combobox("options");
$(_9c4).children().each(function(){
if(this.tagName.toLowerCase()=="optgroup"){
var _9c5=$(this).attr("label");
$(this).children().each(function(){
_9c6(this,_9c5);
});
}else{
_9c6(this);
}
});
return data;
function _9c6(el,_9c7){
var t=$(el);
var row={};
row[opts.valueField]=t.attr("value")!=undefined?t.attr("value"):t.text();
row[opts.textField]=t.text();
row["selected"]=t.is(":selected");
row["disabled"]=t.is(":disabled");
if(_9c7){
opts.groupField=opts.groupField||"group";
row[opts.groupField]=_9c7;
}
data.push(row);
};
};
$.fn.combobox.defaults=$.extend({},$.fn.combo.defaults,{valueField:"value",textField:"text",groupField:null,groupFormatter:function(_9c8){
return _9c8;
},mode:"local",method:"post",url:null,data:null,queryParams:{},keyHandler:{up:function(e){
nav(this,"prev");
e.preventDefault();
},down:function(e){
nav(this,"next");
e.preventDefault();
},left:function(e){
},right:function(e){
},enter:function(e){
_9b1(this);
},query:function(q,e){
_9aa(this,q);
}},filter:function(q,row){
var opts=$(this).combobox("options");
return row[opts.textField].toLowerCase().indexOf(q.toLowerCase())==0;
},formatter:function(row){
var opts=$(this).combobox("options");
return row[opts.textField];
},loader:function(_9c9,_9ca,_9cb){
var opts=$(this).combobox("options");
if(!opts.url){
return false;
}
$.ajax({type:opts.method,url:opts.url,data:_9c9,dataType:"json",success:function(data){
_9ca(data);
},error:function(){
_9cb.apply(this,arguments);
}});
},loadFilter:function(data){
return data;
},finder:{getEl:function(_9cc,_9cd){
var _9ce=_986(_9cc,_9cd);
var id=$.data(_9cc,"combobox").itemIdPrefix+"_"+_9ce;
return $("#"+id);
},getRow:function(_9cf,p){
var _9d0=$.data(_9cf,"combobox");
var _9d1=(p instanceof jQuery)?p.attr("id").substr(_9d0.itemIdPrefix.length+1):_986(_9cf,p);
return _9d0.data[parseInt(_9d1)];
}},onBeforeLoad:function(_9d2){
},onLoadSuccess:function(){
},onLoadError:function(){
},onSelect:function(_9d3){
},onUnselect:function(_9d4){
}});
})(jQuery);
(function($){
function _9d5(_9d6){
var _9d7=$.data(_9d6,"combotree");
var opts=_9d7.options;
var tree=_9d7.tree;
$(_9d6).addClass("combotree-f");
$(_9d6).combo(opts);
var _9d8=$(_9d6).combo("panel");
if(!tree){
tree=$("<ul></ul>").appendTo(_9d8);
$.data(_9d6,"combotree").tree=tree;
}
tree.tree($.extend({},opts,{checkbox:opts.multiple,onLoadSuccess:function(node,data){
var _9d9=$(_9d6).combotree("getValues");
if(opts.multiple){
var _9da=tree.tree("getChecked");
for(var i=0;i<_9da.length;i++){
var id=_9da[i].id;
(function(){
for(var i=0;i<_9d9.length;i++){
if(id==_9d9[i]){
return;
}
}
_9d9.push(id);
})();
}
}
$(_9d6).combotree("setValues",_9d9);
opts.onLoadSuccess.call(this,node,data);
},onClick:function(node){
if(opts.multiple){
$(this).tree(node.checked?"uncheck":"check",node.target);
}else{
$(_9d6).combo("hidePanel");
}
_9dc(_9d6);
opts.onClick.call(this,node);
},onCheck:function(node,_9db){
_9dc(_9d6);
opts.onCheck.call(this,node,_9db);
}}));
};
function _9dc(_9dd){
var _9de=$.data(_9dd,"combotree");
var opts=_9de.options;
var tree=_9de.tree;
var vv=[],ss=[];
if(opts.multiple){
var _9df=tree.tree("getChecked");
for(var i=0;i<_9df.length;i++){
vv.push(_9df[i].id);
ss.push(_9df[i].text);
}
}else{
var node=tree.tree("getSelected");
if(node){
vv.push(node.id);
ss.push(node.text);
}
}
$(_9dd).combo("setText",ss.join(opts.separator)).combo("setValues",opts.multiple?vv:(vv.length?vv:[""]));
};
function _9e0(_9e1,_9e2){
var _9e3=$.data(_9e1,"combotree");
var opts=_9e3.options;
var tree=_9e3.tree;
var _9e4=tree.tree("options");
var _9e5=_9e4.onCheck;
var _9e6=_9e4.onSelect;
_9e4.onCheck=_9e4.onSelect=function(){
};
tree.find("span.tree-checkbox").addClass("tree-checkbox0").removeClass("tree-checkbox1 tree-checkbox2");
if(!$.isArray(_9e2)){
_9e2=_9e2.split(opts.separator);
}
var vv=$.map(_9e2,function(_9e7){
return String(_9e7);
});
var ss=[];
$.map(vv,function(v){
var node=tree.tree("find",v);
if(node){
tree.tree("check",node.target).tree("select",node.target);
ss.push(node.text);
}else{
ss.push(v);
}
});
if(opts.multiple){
var _9e8=tree.tree("getChecked");
$.map(_9e8,function(node){
var id=String(node.id);
if($.inArray(id,vv)==-1){
vv.push(id);
ss.push(node.text);
}
});
}
_9e4.onCheck=_9e5;
_9e4.onSelect=_9e6;
$(_9e1).combo("setText",ss.join(opts.separator)).combo("setValues",opts.multiple?vv:(vv.length?vv:[""]));
};
$.fn.combotree=function(_9e9,_9ea){
if(typeof _9e9=="string"){
var _9eb=$.fn.combotree.methods[_9e9];
if(_9eb){
return _9eb(this,_9ea);
}else{
return this.combo(_9e9,_9ea);
}
}
_9e9=_9e9||{};
return this.each(function(){
var _9ec=$.data(this,"combotree");
if(_9ec){
$.extend(_9ec.options,_9e9);
}else{
$.data(this,"combotree",{options:$.extend({},$.fn.combotree.defaults,$.fn.combotree.parseOptions(this),_9e9)});
}
_9d5(this);
});
};
$.fn.combotree.methods={options:function(jq){
var _9ed=jq.combo("options");
return $.extend($.data(jq[0],"combotree").options,{width:_9ed.width,height:_9ed.height,originalValue:_9ed.originalValue,disabled:_9ed.disabled,readonly:_9ed.readonly});
},clone:function(jq,_9ee){
var t=jq.combo("clone",_9ee);
t.data("combotree",{options:$.extend(true,{},jq.combotree("options")),tree:jq.combotree("tree")});
return t;
},tree:function(jq){
return $.data(jq[0],"combotree").tree;
},loadData:function(jq,data){
return jq.each(function(){
var opts=$.data(this,"combotree").options;
opts.data=data;
var tree=$.data(this,"combotree").tree;
tree.tree("loadData",data);
});
},reload:function(jq,url){
return jq.each(function(){
var opts=$.data(this,"combotree").options;
var tree=$.data(this,"combotree").tree;
if(url){
opts.url=url;
}
tree.tree({url:opts.url});
});
},setValues:function(jq,_9ef){
return jq.each(function(){
_9e0(this,_9ef);
});
},setValue:function(jq,_9f0){
return jq.each(function(){
_9e0(this,[_9f0]);
});
},clear:function(jq){
return jq.each(function(){
var tree=$.data(this,"combotree").tree;
tree.find("div.tree-node-selected").removeClass("tree-node-selected");
var cc=tree.tree("getChecked");
for(var i=0;i<cc.length;i++){
tree.tree("uncheck",cc[i].target);
}
$(this).combo("clear");
});
},reset:function(jq){
return jq.each(function(){
var opts=$(this).combotree("options");
if(opts.multiple){
$(this).combotree("setValues",opts.originalValue);
}else{
$(this).combotree("setValue",opts.originalValue);
}
});
}};
$.fn.combotree.parseOptions=function(_9f1){
return $.extend({},$.fn.combo.parseOptions(_9f1),$.fn.tree.parseOptions(_9f1));
};
$.fn.combotree.defaults=$.extend({},$.fn.combo.defaults,$.fn.tree.defaults,{editable:false});
})(jQuery);
(function($){
function _9f2(_9f3){
var _9f4=$.data(_9f3,"combogrid");
var opts=_9f4.options;
var grid=_9f4.grid;
$(_9f3).addClass("combogrid-f").combo($.extend({},opts,{onShowPanel:function(){
var p=$(this).combogrid("panel");
var _9f5=p.outerHeight()-p.height();
var _9f6=p._size("minHeight");
var _9f7=p._size("maxHeight");
var dg=$(this).combogrid("grid");
dg.datagrid("resize",{width:"100%",height:(isNaN(parseInt(opts.panelHeight))?"auto":"100%"),minHeight:(_9f6?_9f6-_9f5:""),maxHeight:(_9f7?_9f7-_9f5:"")});
var row=dg.datagrid("getSelected");
if(row){
dg.datagrid("scrollTo",dg.datagrid("getRowIndex",row));
}
opts.onShowPanel.call(this);
}}));
var _9f8=$(_9f3).combo("panel");
if(!grid){
grid=$("<table></table>").appendTo(_9f8);
_9f4.grid=grid;
}
grid.datagrid($.extend({},opts,{border:false,singleSelect:(!opts.multiple),onLoadSuccess:function(data){
var _9f9=$(_9f3).combo("getValues");
var _9fa=opts.onSelect;
opts.onSelect=function(){
};
_a00(_9f3,_9f9,_9f4.remainText);
opts.onSelect=_9fa;
opts.onLoadSuccess.apply(_9f3,arguments);
},onClickRow:_9fb,onSelect:function(_9fc,row){
_9fd();
opts.onSelect.call(this,_9fc,row);
},onUnselect:function(_9fe,row){
_9fd();
opts.onUnselect.call(this,_9fe,row);
},onSelectAll:function(rows){
_9fd();
opts.onSelectAll.call(this,rows);
},onUnselectAll:function(rows){
if(opts.multiple){
_9fd();
}
opts.onUnselectAll.call(this,rows);
}}));
function _9fb(_9ff,row){
_9f4.remainText=false;
_9fd();
if(!opts.multiple){
$(_9f3).combo("hidePanel");
}
opts.onClickRow.call(this,_9ff,row);
};
function _9fd(){
var vv=$.map(grid.datagrid("getSelections"),function(row){
return row[opts.idField];
});
vv=vv.concat(opts.unselectedValues);
if(!opts.multiple){
vv=vv.length?[vv[0]]:[""];
}
_a00(_9f3,vv,_9f4.remainText);
};
};
function nav(_a01,dir){
var _a02=$.data(_a01,"combogrid");
var opts=_a02.options;
var grid=_a02.grid;
var _a03=grid.datagrid("getRows").length;
if(!_a03){
return;
}
var tr=opts.finder.getTr(grid[0],null,"highlight");
if(!tr.length){
tr=opts.finder.getTr(grid[0],null,"selected");
}
var _a04;
if(!tr.length){
_a04=(dir=="next"?0:_a03-1);
}else{
var _a04=parseInt(tr.attr("datagrid-row-index"));
_a04+=(dir=="next"?1:-1);
if(_a04<0){
_a04=_a03-1;
}
if(_a04>=_a03){
_a04=0;
}
}
grid.datagrid("highlightRow",_a04);
if(opts.selectOnNavigation){
_a02.remainText=false;
grid.datagrid("selectRow",_a04);
}
};
function _a00(_a05,_a06,_a07){
var _a08=$.data(_a05,"combogrid");
var opts=_a08.options;
var grid=_a08.grid;
var _a09=$(_a05).combo("getValues");
var _a0a=$(_a05).combo("options");
var _a0b=_a0a.onChange;
_a0a.onChange=function(){
};
var _a0c=grid.datagrid("options");
var _a0d=_a0c.onSelect;
var _a0e=_a0c.onUnselectAll;
_a0c.onSelect=_a0c.onUnselectAll=function(){
};
if(!$.isArray(_a06)){
_a06=_a06.split(opts.separator);
}
var _a0f=[];
$.map(grid.datagrid("getSelections"),function(row){
if($.inArray(row[opts.idField],_a06)>=0){
_a0f.push(row);
}
});
grid.datagrid("clearSelections");
grid.data("datagrid").selectedRows=_a0f;
var ss=[];
for(var i=0;i<_a06.length;i++){
var _a10=_a06[i];
var _a11=grid.datagrid("getRowIndex",_a10);
if(_a11>=0){
grid.datagrid("selectRow",_a11);
}
ss.push(_a12(_a10,grid.datagrid("getRows"))||_a12(_a10,grid.datagrid("getSelections"))||_a12(_a10,opts.mappingRows)||_a10);
}
opts.unselectedValues=[];
var _a13=$.map(_a0f,function(row){
return row[opts.idField];
});
$.map(_a06,function(_a14){
if($.inArray(_a14,_a13)==-1){
opts.unselectedValues.push(_a14);
}
});
$(_a05).combo("setValues",_a09);
_a0a.onChange=_a0b;
_a0c.onSelect=_a0d;
_a0c.onUnselectAll=_a0e;
if(!_a07){
var s=ss.join(opts.separator);
if($(_a05).combo("getText")!=s){
$(_a05).combo("setText",s);
}
}
$(_a05).combo("setValues",_a06);
function _a12(_a15,a){
for(var i=0;i<a.length;i++){
if(_a15==a[i][opts.idField]){
return a[i][opts.textField];
}
}
return undefined;
};
};
function _a16(_a17,q){
var _a18=$.data(_a17,"combogrid");
var opts=_a18.options;
var grid=_a18.grid;
_a18.remainText=true;
if(opts.multiple&&!q){
_a00(_a17,[],true);
}else{
_a00(_a17,[q],true);
}
if(opts.mode=="remote"){
grid.datagrid("clearSelections");
grid.datagrid("load",$.extend({},opts.queryParams,{q:q}));
}else{
if(!q){
return;
}
grid.datagrid("clearSelections").datagrid("highlightRow",-1);
var rows=grid.datagrid("getRows");
var qq=opts.multiple?q.split(opts.separator):[q];
$.map(qq,function(q){
q=$.trim(q);
if(q){
$.map(rows,function(row,i){
if(q==row[opts.textField]){
grid.datagrid("selectRow",i);
}else{
if(opts.filter.call(_a17,q,row)){
grid.datagrid("highlightRow",i);
}
}
});
}
});
}
};
function _a19(_a1a){
var _a1b=$.data(_a1a,"combogrid");
var opts=_a1b.options;
var grid=_a1b.grid;
var tr=opts.finder.getTr(grid[0],null,"highlight");
_a1b.remainText=false;
if(tr.length){
var _a1c=parseInt(tr.attr("datagrid-row-index"));
if(opts.multiple){
if(tr.hasClass("datagrid-row-selected")){
grid.datagrid("unselectRow",_a1c);
}else{
grid.datagrid("selectRow",_a1c);
}
}else{
grid.datagrid("selectRow",_a1c);
}
}
var vv=[];
$.map(grid.datagrid("getSelections"),function(row){
vv.push(row[opts.idField]);
});
$(_a1a).combogrid("setValues",vv);
if(!opts.multiple){
$(_a1a).combogrid("hidePanel");
}
};
$.fn.combogrid=function(_a1d,_a1e){
if(typeof _a1d=="string"){
var _a1f=$.fn.combogrid.methods[_a1d];
if(_a1f){
return _a1f(this,_a1e);
}else{
return this.combo(_a1d,_a1e);
}
}
_a1d=_a1d||{};
return this.each(function(){
var _a20=$.data(this,"combogrid");
if(_a20){
$.extend(_a20.options,_a1d);
}else{
_a20=$.data(this,"combogrid",{options:$.extend({},$.fn.combogrid.defaults,$.fn.combogrid.parseOptions(this),_a1d)});
}
_9f2(this);
});
};
$.fn.combogrid.methods={options:function(jq){
var _a21=jq.combo("options");
return $.extend($.data(jq[0],"combogrid").options,{width:_a21.width,height:_a21.height,originalValue:_a21.originalValue,disabled:_a21.disabled,readonly:_a21.readonly});
},grid:function(jq){
return $.data(jq[0],"combogrid").grid;
},setValues:function(jq,_a22){
return jq.each(function(){
var opts=$(this).combogrid("options");
if($.isArray(_a22)){
_a22=$.map(_a22,function(_a23){
if(typeof _a23=="object"){
var v=_a23[opts.idField];
(function(){
for(var i=0;i<opts.mappingRows.length;i++){
if(v==opts.mappingRows[i][opts.idField]){
return;
}
}
opts.mappingRows.push(_a23);
})();
return v;
}else{
return _a23;
}
});
}
_a00(this,_a22);
});
},setValue:function(jq,_a24){
return jq.each(function(){
$(this).combogrid("setValues",[_a24]);
});
},clear:function(jq){
return jq.each(function(){
$(this).combogrid("grid").datagrid("clearSelections");
$(this).combo("clear");
});
},reset:function(jq){
return jq.each(function(){
var opts=$(this).combogrid("options");
if(opts.multiple){
$(this).combogrid("setValues",opts.originalValue);
}else{
$(this).combogrid("setValue",opts.originalValue);
}
});
}};
$.fn.combogrid.parseOptions=function(_a25){
var t=$(_a25);
return $.extend({},$.fn.combo.parseOptions(_a25),$.fn.datagrid.parseOptions(_a25),$.parser.parseOptions(_a25,["idField","textField","mode"]));
};
$.fn.combogrid.defaults=$.extend({},$.fn.combo.defaults,$.fn.datagrid.defaults,{height:22,loadMsg:null,idField:null,textField:null,unselectedValues:[],mappingRows:[],mode:"local",keyHandler:{up:function(e){
nav(this,"prev");
e.preventDefault();
},down:function(e){
nav(this,"next");
e.preventDefault();
},left:function(e){
},right:function(e){
},enter:function(e){
_a19(this);
},query:function(q,e){
_a16(this,q);
}},filter:function(q,row){
var opts=$(this).combogrid("options");
return (row[opts.textField]||"").toLowerCase().indexOf(q.toLowerCase())==0;
}});
})(jQuery);
(function($){
function _a26(_a27){
var _a28=$.data(_a27,"datebox");
var opts=_a28.options;
$(_a27).addClass("datebox-f").combo($.extend({},opts,{onShowPanel:function(){
_a29(this);
_a2a(this);
_a2b(this);
_a39(this,$(this).datebox("getText"),true);
opts.onShowPanel.call(this);
}}));
if(!_a28.calendar){
var _a2c=$(_a27).combo("panel").css("overflow","hidden");
_a2c.panel("options").onBeforeDestroy=function(){
var c=$(this).find(".calendar-shared");
if(c.length){
c.insertBefore(c[0].pholder);
}
};
var cc=$("<div class=\"datebox-calendar-inner\"></div>").prependTo(_a2c);
if(opts.sharedCalendar){
var c=$(opts.sharedCalendar);
if(!c[0].pholder){
c[0].pholder=$("<div class=\"calendar-pholder\" style=\"display:none\"></div>").insertAfter(c);
}
c.addClass("calendar-shared").appendTo(cc);
if(!c.hasClass("calendar")){
c.calendar();
}
_a28.calendar=c;
}else{
_a28.calendar=$("<div></div>").appendTo(cc).calendar();
}
$.extend(_a28.calendar.calendar("options"),{fit:true,border:false,onSelect:function(date){
var _a2d=this.target;
var opts=$(_a2d).datebox("options");
_a39(_a2d,opts.formatter.call(_a2d,date));
$(_a2d).combo("hidePanel");
opts.onSelect.call(_a2d,date);
}});
}
$(_a27).combo("textbox").parent().addClass("datebox");
$(_a27).datebox("initValue",opts.value);
function _a29(_a2e){
var opts=$(_a2e).datebox("options");
var _a2f=$(_a2e).combo("panel");
_a2f.unbind(".datebox").bind("click.datebox",function(e){
if($(e.target).hasClass("datebox-button-a")){
var _a30=parseInt($(e.target).attr("datebox-button-index"));
opts.buttons[_a30].handler.call(e.target,_a2e);
}
});
};
function _a2a(_a31){
var _a32=$(_a31).combo("panel");
if(_a32.children("div.datebox-button").length){
return;
}
var _a33=$("<div class=\"datebox-button\"><table cellspacing=\"0\" cellpadding=\"0\" style=\"width:100%\"><tr></tr></table></div>").appendTo(_a32);
var tr=_a33.find("tr");
for(var i=0;i<opts.buttons.length;i++){
var td=$("<td></td>").appendTo(tr);
var btn=opts.buttons[i];
var t=$("<a class=\"datebox-button-a\" href=\"javascript:void(0)\"></a>").html($.isFunction(btn.text)?btn.text(_a31):btn.text).appendTo(td);
t.attr("datebox-button-index",i);
}
tr.find("td").css("width",(100/opts.buttons.length)+"%");
};
function _a2b(_a34){
var _a35=$(_a34).combo("panel");
var cc=_a35.children("div.datebox-calendar-inner");
_a35.children()._outerWidth(_a35.width());
_a28.calendar.appendTo(cc);
_a28.calendar[0].target=_a34;
if(opts.panelHeight!="auto"){
var _a36=_a35.height();
_a35.children().not(cc).each(function(){
_a36-=$(this).outerHeight();
});
cc._outerHeight(_a36);
}
_a28.calendar.calendar("resize");
};
};
function _a37(_a38,q){
_a39(_a38,q,true);
};
function _a3a(_a3b){
var _a3c=$.data(_a3b,"datebox");
var opts=_a3c.options;
var _a3d=_a3c.calendar.calendar("options").current;
if(_a3d){
_a39(_a3b,opts.formatter.call(_a3b,_a3d));
$(_a3b).combo("hidePanel");
}
};
function _a39(_a3e,_a3f,_a40){
var _a41=$.data(_a3e,"datebox");
var opts=_a41.options;
var _a42=_a41.calendar;
_a42.calendar("moveTo",opts.parser.call(_a3e,_a3f));
if(_a40){
$(_a3e).combo("setValue",_a3f);
}else{
if(_a3f){
_a3f=opts.formatter.call(_a3e,_a42.calendar("options").current);
}
$(_a3e).combo("setText",_a3f).combo("setValue",_a3f);
}
};
$.fn.datebox=function(_a43,_a44){
if(typeof _a43=="string"){
var _a45=$.fn.datebox.methods[_a43];
if(_a45){
return _a45(this,_a44);
}else{
return this.combo(_a43,_a44);
}
}
_a43=_a43||{};
return this.each(function(){
var _a46=$.data(this,"datebox");
if(_a46){
$.extend(_a46.options,_a43);
}else{
$.data(this,"datebox",{options:$.extend({},$.fn.datebox.defaults,$.fn.datebox.parseOptions(this),_a43)});
}
_a26(this);
});
};
$.fn.datebox.methods={options:function(jq){
var _a47=jq.combo("options");
return $.extend($.data(jq[0],"datebox").options,{width:_a47.width,height:_a47.height,originalValue:_a47.originalValue,disabled:_a47.disabled,readonly:_a47.readonly});
},cloneFrom:function(jq,from){
return jq.each(function(){
$(this).combo("cloneFrom",from);
$.data(this,"datebox",{options:$.extend(true,{},$(from).datebox("options")),calendar:$(from).datebox("calendar")});
$(this).addClass("datebox-f");
});
},calendar:function(jq){
return $.data(jq[0],"datebox").calendar;
},initValue:function(jq,_a48){
return jq.each(function(){
var opts=$(this).datebox("options");
var _a49=opts.value;
if(_a49){
_a49=opts.formatter.call(this,opts.parser.call(this,_a49));
}
$(this).combo("initValue",_a49).combo("setText",_a49);
});
},setValue:function(jq,_a4a){
return jq.each(function(){
_a39(this,_a4a);
});
},reset:function(jq){
return jq.each(function(){
var opts=$(this).datebox("options");
$(this).datebox("setValue",opts.originalValue);
});
}};
$.fn.datebox.parseOptions=function(_a4b){
return $.extend({},$.fn.combo.parseOptions(_a4b),$.parser.parseOptions(_a4b,["sharedCalendar"]));
};
$.fn.datebox.defaults=$.extend({},$.fn.combo.defaults,{panelWidth:180,panelHeight:"auto",sharedCalendar:null,keyHandler:{up:function(e){
},down:function(e){
},left:function(e){
},right:function(e){
},enter:function(e){
_a3a(this);
},query:function(q,e){
_a37(this,q);
}},currentText:"Today",closeText:"Close",okText:"Ok",buttons:[{text:function(_a4c){
return $(_a4c).datebox("options").currentText;
},handler:function(_a4d){
var now=new Date();
$(_a4d).datebox("calendar").calendar({year:now.getFullYear(),month:now.getMonth()+1,current:new Date(now.getFullYear(),now.getMonth(),now.getDate())});
_a3a(_a4d);
}},{text:function(_a4e){
return $(_a4e).datebox("options").closeText;
},handler:function(_a4f){
$(this).closest("div.combo-panel").panel("close");
}}],formatter:function(date){
var y=date.getFullYear();
var m=date.getMonth()+1;
var d=date.getDate();
return (m<10?("0"+m):m)+"/"+(d<10?("0"+d):d)+"/"+y;
},parser:function(s){
if(!s){
return new Date();
}
var ss=s.split("/");
var m=parseInt(ss[0],10);
var d=parseInt(ss[1],10);
var y=parseInt(ss[2],10);
if(!isNaN(y)&&!isNaN(m)&&!isNaN(d)){
return new Date(y,m-1,d);
}else{
return new Date();
}
},onSelect:function(date){
}});
})(jQuery);
(function($){
function _a50(_a51){
var _a52=$.data(_a51,"datetimebox");
var opts=_a52.options;
$(_a51).datebox($.extend({},opts,{onShowPanel:function(){
var _a53=$(this).datetimebox("getValue");
_a59(this,_a53,true);
opts.onShowPanel.call(this);
},formatter:$.fn.datebox.defaults.formatter,parser:$.fn.datebox.defaults.parser}));
$(_a51).removeClass("datebox-f").addClass("datetimebox-f");
$(_a51).datebox("calendar").calendar({onSelect:function(date){
opts.onSelect.call(this.target,date);
}});
if(!_a52.spinner){
var _a54=$(_a51).datebox("panel");
var p=$("<div style=\"padding:2px\"><input></div>").insertAfter(_a54.children("div.datebox-calendar-inner"));
_a52.spinner=p.children("input");
}
_a52.spinner.timespinner({width:opts.spinnerWidth,showSeconds:opts.showSeconds,separator:opts.timeSeparator});
$(_a51).datetimebox("initValue",opts.value);
};
function _a55(_a56){
var c=$(_a56).datetimebox("calendar");
var t=$(_a56).datetimebox("spinner");
var date=c.calendar("options").current;
return new Date(date.getFullYear(),date.getMonth(),date.getDate(),t.timespinner("getHours"),t.timespinner("getMinutes"),t.timespinner("getSeconds"));
};
function _a57(_a58,q){
_a59(_a58,q,true);
};
function _a5a(_a5b){
var opts=$.data(_a5b,"datetimebox").options;
var date=_a55(_a5b);
_a59(_a5b,opts.formatter.call(_a5b,date));
$(_a5b).combo("hidePanel");
};
function _a59(_a5c,_a5d,_a5e){
var opts=$.data(_a5c,"datetimebox").options;
$(_a5c).combo("setValue",_a5d);
if(!_a5e){
if(_a5d){
var date=opts.parser.call(_a5c,_a5d);
$(_a5c).combo("setText",opts.formatter.call(_a5c,date));
$(_a5c).combo("setValue",opts.formatter.call(_a5c,date));
}else{
$(_a5c).combo("setText",_a5d);
}
}
var date=opts.parser.call(_a5c,_a5d);
$(_a5c).datetimebox("calendar").calendar("moveTo",date);
$(_a5c).datetimebox("spinner").timespinner("setValue",_a5f(date));
function _a5f(date){
function _a60(_a61){
return (_a61<10?"0":"")+_a61;
};
var tt=[_a60(date.getHours()),_a60(date.getMinutes())];
if(opts.showSeconds){
tt.push(_a60(date.getSeconds()));
}
return tt.join($(_a5c).datetimebox("spinner").timespinner("options").separator);
};
};
$.fn.datetimebox=function(_a62,_a63){
if(typeof _a62=="string"){
var _a64=$.fn.datetimebox.methods[_a62];
if(_a64){
return _a64(this,_a63);
}else{
return this.datebox(_a62,_a63);
}
}
_a62=_a62||{};
return this.each(function(){
var _a65=$.data(this,"datetimebox");
if(_a65){
$.extend(_a65.options,_a62);
}else{
$.data(this,"datetimebox",{options:$.extend({},$.fn.datetimebox.defaults,$.fn.datetimebox.parseOptions(this),_a62)});
}
_a50(this);
});
};
$.fn.datetimebox.methods={options:function(jq){
var _a66=jq.datebox("options");
return $.extend($.data(jq[0],"datetimebox").options,{originalValue:_a66.originalValue,disabled:_a66.disabled,readonly:_a66.readonly});
},cloneFrom:function(jq,from){
return jq.each(function(){
$(this).datebox("cloneFrom",from);
$.data(this,"datetimebox",{options:$.extend(true,{},$(from).datetimebox("options")),spinner:$(from).datetimebox("spinner")});
$(this).removeClass("datebox-f").addClass("datetimebox-f");
});
},spinner:function(jq){
return $.data(jq[0],"datetimebox").spinner;
},initValue:function(jq,_a67){
return jq.each(function(){
var opts=$(this).datetimebox("options");
var _a68=opts.value;
if(_a68){
_a68=opts.formatter.call(this,opts.parser.call(this,_a68));
}
$(this).combo("initValue",_a68).combo("setText",_a68);
});
},setValue:function(jq,_a69){
return jq.each(function(){
_a59(this,_a69);
});
},reset:function(jq){
return jq.each(function(){
var opts=$(this).datetimebox("options");
$(this).datetimebox("setValue",opts.originalValue);
});
}};
$.fn.datetimebox.parseOptions=function(_a6a){
var t=$(_a6a);
return $.extend({},$.fn.datebox.parseOptions(_a6a),$.parser.parseOptions(_a6a,["timeSeparator","spinnerWidth",{showSeconds:"boolean"}]));
};
$.fn.datetimebox.defaults=$.extend({},$.fn.datebox.defaults,{spinnerWidth:"100%",showSeconds:true,timeSeparator:":",keyHandler:{up:function(e){
},down:function(e){
},left:function(e){
},right:function(e){
},enter:function(e){
_a5a(this);
},query:function(q,e){
_a57(this,q);
}},buttons:[{text:function(_a6b){
return $(_a6b).datetimebox("options").currentText;
},handler:function(_a6c){
var opts=$(_a6c).datetimebox("options");
_a59(_a6c,opts.formatter.call(_a6c,new Date()));
$(_a6c).datetimebox("hidePanel");
}},{text:function(_a6d){
return $(_a6d).datetimebox("options").okText;
},handler:function(_a6e){
_a5a(_a6e);
}},{text:function(_a6f){
return $(_a6f).datetimebox("options").closeText;
},handler:function(_a70){
$(_a70).datetimebox("hidePanel");
}}],formatter:function(date){
var h=date.getHours();
var M=date.getMinutes();
var s=date.getSeconds();
function _a71(_a72){
return (_a72<10?"0":"")+_a72;
};
var _a73=$(this).datetimebox("spinner").timespinner("options").separator;
var r=$.fn.datebox.defaults.formatter(date)+" "+_a71(h)+_a73+_a71(M);
if($(this).datetimebox("options").showSeconds){
r+=_a73+_a71(s);
}
return r;
},parser:function(s){
if($.trim(s)==""){
return new Date();
}
var dt=s.split(" ");
var d=$.fn.datebox.defaults.parser(dt[0]);
if(dt.length<2){
return d;
}
var _a74=$(this).datetimebox("spinner").timespinner("options").separator;
var tt=dt[1].split(_a74);
var hour=parseInt(tt[0],10)||0;
var _a75=parseInt(tt[1],10)||0;
var _a76=parseInt(tt[2],10)||0;
return new Date(d.getFullYear(),d.getMonth(),d.getDate(),hour,_a75,_a76);
}});
})(jQuery);
(function($){
function init(_a77){
var _a78=$("<div class=\"slider\">"+"<div class=\"slider-inner\">"+"<a href=\"javascript:void(0)\" class=\"slider-handle\"></a>"+"<span class=\"slider-tip\"></span>"+"</div>"+"<div class=\"slider-rule\"></div>"+"<div class=\"slider-rulelabel\"></div>"+"<div style=\"clear:both\"></div>"+"<input type=\"hidden\" class=\"slider-value\">"+"</div>").insertAfter(_a77);
var t=$(_a77);
t.addClass("slider-f").hide();
var name=t.attr("name");
if(name){
_a78.find("input.slider-value").attr("name",name);
t.removeAttr("name").attr("sliderName",name);
}
_a78.bind("_resize",function(e,_a79){
if($(this).hasClass("easyui-fluid")||_a79){
_a7a(_a77);
}
return false;
});
return _a78;
};
function _a7a(_a7b,_a7c){
var _a7d=$.data(_a7b,"slider");
var opts=_a7d.options;
var _a7e=_a7d.slider;
if(_a7c){
if(_a7c.width){
opts.width=_a7c.width;
}
if(_a7c.height){
opts.height=_a7c.height;
}
}
_a7e._size(opts);
if(opts.mode=="h"){
_a7e.css("height","");
_a7e.children("div").css("height","");
}else{
_a7e.css("width","");
_a7e.children("div").css("width","");
_a7e.children("div.slider-rule,div.slider-rulelabel,div.slider-inner")._outerHeight(_a7e._outerHeight());
}
_a7f(_a7b);
};
function _a80(_a81){
var _a82=$.data(_a81,"slider");
var opts=_a82.options;
var _a83=_a82.slider;
var aa=opts.mode=="h"?opts.rule:opts.rule.slice(0).reverse();
if(opts.reversed){
aa=aa.slice(0).reverse();
}
_a84(aa);
function _a84(aa){
var rule=_a83.find("div.slider-rule");
var _a85=_a83.find("div.slider-rulelabel");
rule.empty();
_a85.empty();
for(var i=0;i<aa.length;i++){
var _a86=i*100/(aa.length-1)+"%";
var span=$("<span></span>").appendTo(rule);
span.css((opts.mode=="h"?"left":"top"),_a86);
if(aa[i]!="|"){
span=$("<span></span>").appendTo(_a85);
span.html(aa[i]);
if(opts.mode=="h"){
span.css({left:_a86,marginLeft:-Math.round(span.outerWidth()/2)});
}else{
span.css({top:_a86,marginTop:-Math.round(span.outerHeight()/2)});
}
}
}
};
};
function _a87(_a88){
var _a89=$.data(_a88,"slider");
var opts=_a89.options;
var _a8a=_a89.slider;
_a8a.removeClass("slider-h slider-v slider-disabled");
_a8a.addClass(opts.mode=="h"?"slider-h":"slider-v");
_a8a.addClass(opts.disabled?"slider-disabled":"");
var _a8b=_a8a.find(".slider-inner");
_a8b.html("<a href=\"javascript:void(0)\" class=\"slider-handle\"></a>"+"<span class=\"slider-tip\"></span>");
if(opts.range){
_a8b.append("<a href=\"javascript:void(0)\" class=\"slider-handle\"></a>"+"<span class=\"slider-tip\"></span>");
}
_a8a.find("a.slider-handle").draggable({axis:opts.mode,cursor:"pointer",disabled:opts.disabled,onDrag:function(e){
var left=e.data.left;
var _a8c=_a8a.width();
if(opts.mode!="h"){
left=e.data.top;
_a8c=_a8a.height();
}
if(left<0||left>_a8c){
return false;
}else{
_a8d(left,this);
return false;
}
},onStartDrag:function(){
_a89.isDragging=true;
opts.onSlideStart.call(_a88,opts.value);
},onStopDrag:function(e){
_a8d(opts.mode=="h"?e.data.left:e.data.top,this);
opts.onSlideEnd.call(_a88,opts.value);
opts.onComplete.call(_a88,opts.value);
_a89.isDragging=false;
}});
_a8a.find("div.slider-inner").unbind(".slider").bind("mousedown.slider",function(e){
if(_a89.isDragging||opts.disabled){
return;
}
var pos=$(this).offset();
_a8d(opts.mode=="h"?(e.pageX-pos.left):(e.pageY-pos.top));
opts.onComplete.call(_a88,opts.value);
});
function _a8d(pos,_a8e){
var _a8f=_a90(_a88,pos);
var s=Math.abs(_a8f%opts.step);
if(s<opts.step/2){
_a8f-=s;
}else{
_a8f=_a8f-s+opts.step;
}
if(opts.range){
var v1=opts.value[0];
var v2=opts.value[1];
var m=parseFloat((v1+v2)/2);
if(_a8e){
var _a91=$(_a8e).nextAll(".slider-handle").length>0;
if(_a8f<=v2&&_a91){
v1=_a8f;
}else{
if(_a8f>=v1&&(!_a91)){
v2=_a8f;
}
}
}else{
if(_a8f<v1){
v1=_a8f;
}else{
if(_a8f>v2){
v2=_a8f;
}else{
_a8f<m?v1=_a8f:v2=_a8f;
}
}
}
$(_a88).slider("setValues",[v1,v2]);
}else{
$(_a88).slider("setValue",_a8f);
}
};
};
function _a92(_a93,_a94){
var _a95=$.data(_a93,"slider");
var opts=_a95.options;
var _a96=_a95.slider;
var _a97=$.isArray(opts.value)?opts.value:[opts.value];
var _a98=[];
if(!$.isArray(_a94)){
_a94=$.map(String(_a94).split(opts.separator),function(v){
return parseFloat(v);
});
}
_a96.find(".slider-value").remove();
var name=$(_a93).attr("sliderName")||"";
for(var i=0;i<_a94.length;i++){
var _a99=_a94[i];
if(_a99<opts.min){
_a99=opts.min;
}
if(_a99>opts.max){
_a99=opts.max;
}
var _a9a=$("<input type=\"hidden\" class=\"slider-value\">").appendTo(_a96);
_a9a.attr("name",name);
_a9a.val(_a99);
_a98.push(_a99);
var _a9b=_a96.find(".slider-handle:eq("+i+")");
var tip=_a9b.next();
var pos=_a9c(_a93,_a99);
if(opts.showTip){
tip.show();
tip.html(opts.tipFormatter.call(_a93,_a99));
}else{
tip.hide();
}
if(opts.mode=="h"){
var _a9d="left:"+pos+"px;";
_a9b.attr("style",_a9d);
tip.attr("style",_a9d+"margin-left:"+(-Math.round(tip.outerWidth()/2))+"px");
}else{
var _a9d="top:"+pos+"px;";
_a9b.attr("style",_a9d);
tip.attr("style",_a9d+"margin-left:"+(-Math.round(tip.outerWidth()))+"px");
}
}
opts.value=opts.range?_a98:_a98[0];
$(_a93).val(opts.range?_a98.join(opts.separator):_a98[0]);
if(_a97.join(",")!=_a98.join(",")){
opts.onChange.call(_a93,opts.value,(opts.range?_a97:_a97[0]));
}
};
function _a7f(_a9e){
var opts=$.data(_a9e,"slider").options;
var fn=opts.onChange;
opts.onChange=function(){
};
_a92(_a9e,opts.value);
opts.onChange=fn;
};
function _a9c(_a9f,_aa0){
var _aa1=$.data(_a9f,"slider");
var opts=_aa1.options;
var _aa2=_aa1.slider;
var size=opts.mode=="h"?_aa2.width():_aa2.height();
var pos=opts.converter.toPosition.call(_a9f,_aa0,size);
if(opts.mode=="v"){
pos=_aa2.height()-pos;
}
if(opts.reversed){
pos=size-pos;
}
return pos.toFixed(0);
};
function _a90(_aa3,pos){
var _aa4=$.data(_aa3,"slider");
var opts=_aa4.options;
var _aa5=_aa4.slider;
var size=opts.mode=="h"?_aa5.width():_aa5.height();
var pos=opts.mode=="h"?(opts.reversed?(size-pos):pos):(opts.reversed?pos:(size-pos));
var _aa6=opts.converter.toValue.call(_aa3,pos,size);
return _aa6.toFixed(0);
};
//$.fn.slider=function(_aa7,_aa8){
//if(typeof _aa7=="string"){
//return $.fn.slider.methods[_aa7](this,_aa8);
//}
//_aa7=_aa7||{};
//return this.each(function(){
//var _aa9=$.data(this,"slider");
//if(_aa9){
//$.extend(_aa9.options,_aa7);
//}else{
//_aa9=$.data(this,"slider",{options:$.extend({},$.fn.slider.defaults,$.fn.slider.parseOptions(this),_aa7),slider:init(this)});
//$(this).removeAttr("disabled");
//}
//var opts=_aa9.options;
//opts.min=parseFloat(opts.min);
//opts.max=parseFloat(opts.max);
//if(opts.range){
//if(!$.isArray(opts.value)){
//opts.value=$.map(String(opts.value).split(opts.separator),function(v){
//return parseFloat(v);
//});
//}
//if(opts.value.length<2){
//opts.value.push(opts.max);
//}
//}else{
//opts.value=parseFloat(opts.value);
//}
//opts.step=parseFloat(opts.step);
//opts.originalValue=opts.value;
//_a87(this);
//_a80(this);
//_a7a(this);
//});
//};
$.fn.slider.methods={options:function(jq){
return $.data(jq[0],"slider").options;
},destroy:function(jq){
return jq.each(function(){
$.data(this,"slider").slider.remove();
$(this).remove();
});
},resize:function(jq,_aaa){
return jq.each(function(){
_a7a(this,_aaa);
});
},getValue:function(jq){
return jq.slider("options").value;
},getValues:function(jq){
return jq.slider("options").value;
},setValue:function(jq,_aab){
return jq.each(function(){
_a92(this,[_aab]);
});
},setValues:function(jq,_aac){
return jq.each(function(){
_a92(this,_aac);
});
},clear:function(jq){
return jq.each(function(){
var opts=$(this).slider("options");
_a92(this,opts.range?[opts.min,opts.max]:[opts.min]);
});
},reset:function(jq){
return jq.each(function(){
var opts=$(this).slider("options");
$(this).slider(opts.range?"setValues":"setValue",opts.originalValue);
});
},enable:function(jq){
return jq.each(function(){
$.data(this,"slider").options.disabled=false;
_a87(this);
});
},disable:function(jq){
return jq.each(function(){
$.data(this,"slider").options.disabled=true;
_a87(this);
});
}};
$.fn.slider.parseOptions=function(_aad){
var t=$(_aad);
return $.extend({},$.parser.parseOptions(_aad,["width","height","mode",{reversed:"boolean",showTip:"boolean",range:"boolean",min:"number",max:"number",step:"number"}]),{value:(t.val()||undefined),disabled:(t.attr("disabled")?true:undefined),rule:(t.attr("rule")?eval(t.attr("rule")):undefined)});
};
$.fn.slider.defaults={width:"auto",height:"auto",mode:"h",reversed:false,showTip:false,disabled:false,range:false,value:0,separator:",",min:0,max:100,step:1,rule:[],tipFormatter:function(_aae){
return _aae;
},converter:{toPosition:function(_aaf,size){
var opts=$(this).slider("options");
return (_aaf-opts.min)/(opts.max-opts.min)*size;
},toValue:function(pos,size){
var opts=$(this).slider("options");
return opts.min+(opts.max-opts.min)*(pos/size);
}},onChange:function(_ab0,_ab1){
},onSlideStart:function(_ab2){
},onSlideEnd:function(_ab3){
},onComplete:function(_ab4){
}};
})(jQuery);

;
/**
 * jQuery EasyUI 1.4.3
 * 
 * Copyright (c) 2009-2015 www.jeasyui.com. All rights reserved.
 *
 * Licensed under the GPL license: http://www.gnu.org/licenses/gpl.txt
 * To use it on other terms please contact us at info@jeasyui.com
 *
 */
(function($){
function _1(_2){
var _3=$.data(_2,"combotree");
var _4=_3.options;
var _5=_3.tree;
$(_2).addClass("combotree-f");
$(_2).combo(_4);
var _6=$(_2).combo("panel");
if(!_5){
_5=$("<ul></ul>").appendTo(_6);
$.data(_2,"combotree").tree=_5;
}
_5.tree($.extend({},_4,{checkbox:_4.multiple,onLoadSuccess:function(_7,_8){
var _9=$(_2).combotree("getValues");
if(_4.multiple){
var _a=_5.tree("getChecked");
for(var i=0;i<_a.length;i++){
var id=_a[i].id;
(function(){
for(var i=0;i<_9.length;i++){
if(id==_9[i]){
return;
}
}
_9.push(id);
})();
}
}
$(_2).combotree("setValues",_9);
_4.onLoadSuccess.call(this,_7,_8);
},onClick:function(_b){
if(_4.multiple){
$(this).tree(_b.checked?"uncheck":"check",_b.target);
}else{
$(_2).combo("hidePanel");
}
_e(_2);
_4.onClick.call(this,_b);
},onCheck:function(_c,_d){
_e(_2);
_4.onCheck.call(this,_c,_d);
}}));
};
function _e(_f){
var _10=$.data(_f,"combotree");
var _11=_10.options;
var _12=_10.tree;
var vv=[],ss=[];
if(_11.multiple){
var _13=_12.tree("getChecked");
for(var i=0;i<_13.length;i++){
vv.push(_13[i].id);
ss.push(_13[i].text);
}
}else{
var _14=_12.tree("getSelected");
if(_14){
vv.push(_14.id);
ss.push(_14.text);
}
}
$(_f).combo("setText",ss.join(_11.separator)).combo("setValues",_11.multiple?vv:(vv.length?vv:[""]));
};
function _15(_16,_17){
var _18=$.data(_16,"combotree");
var _19=_18.options;
var _1a=_18.tree;
var _1b=_1a.tree("options");
var _1c=_1b.onCheck;
var _1d=_1b.onSelect;
_1b.onCheck=_1b.onSelect=function(){
};
_1a.find("span.tree-checkbox").addClass("tree-checkbox0").removeClass("tree-checkbox1 tree-checkbox2");
if(!$.isArray(_17)){
_17=_17.split(_19.separator);
}
var vv=$.map(_17,function(_1e){
return String(_1e);
});
var ss=[];
$.map(vv,function(v){
var _1f=_1a.tree("find",v);
if(_1f){
_1a.tree("check",_1f.target).tree("select",_1f.target);
ss.push(_1f.text);
}else{
ss.push(v);
}
});
if(_19.multiple){
var _20=_1a.tree("getChecked");
$.map(_20,function(_21){
var id=String(_21.id);
if($.inArray(id,vv)==-1){
vv.push(id);
ss.push(_21.text);
}
});
}
_1b.onCheck=_1c;
_1b.onSelect=_1d;
$(_16).combo("setText",ss.join(_19.separator)).combo("setValues",_19.multiple?vv:(vv.length?vv:[""]));
};
$.fn.combotree=function(_22,_23){
if(typeof _22=="string"){
var _24=$.fn.combotree.methods[_22];
if(_24){
return _24(this,_23);
}else{
return this.combo(_22,_23);
}
}
_22=_22||{};
return this.each(function(){
var _25=$.data(this,"combotree");
if(_25){
$.extend(_25.options,_22);
}else{
$.data(this,"combotree",{options:$.extend({},$.fn.combotree.defaults,$.fn.combotree.parseOptions(this),_22)});
}
_1(this);
});
};
$.fn.combotree.methods={options:function(jq){
var _26=jq.combo("options");
return $.extend($.data(jq[0],"combotree").options,{width:_26.width,height:_26.height,originalValue:_26.originalValue,disabled:_26.disabled,readonly:_26.readonly});
},clone:function(jq,_27){
var t=jq.combo("clone",_27);
t.data("combotree",{options:$.extend(true,{},jq.combotree("options")),tree:jq.combotree("tree")});
return t;
},tree:function(jq){
return $.data(jq[0],"combotree").tree;
},loadData:function(jq,_28){
return jq.each(function(){
var _29=$.data(this,"combotree").options;
_29.data=_28;
var _2a=$.data(this,"combotree").tree;
_2a.tree("loadData",_28);
});
},reload:function(jq,url){
return jq.each(function(){
var _2b=$.data(this,"combotree").options;
var _2c=$.data(this,"combotree").tree;
if(url){
_2b.url=url;
}
_2c.tree({url:_2b.url});
});
},setValues:function(jq,_2d){
return jq.each(function(){
_15(this,_2d);
});
},setValue:function(jq,_2e){
return jq.each(function(){
_15(this,[_2e]);
});
},clear:function(jq){
return jq.each(function(){
var _2f=$.data(this,"combotree").tree;
_2f.find("div.tree-node-selected").removeClass("tree-node-selected");
var cc=_2f.tree("getChecked");
for(var i=0;i<cc.length;i++){
_2f.tree("uncheck",cc[i].target);
}
$(this).combo("clear");
});
},reset:function(jq){
return jq.each(function(){
var _30=$(this).combotree("options");
if(_30.multiple){
$(this).combotree("setValues",_30.originalValue);
}else{
$(this).combotree("setValue",_30.originalValue);
}
});
}};
$.fn.combotree.parseOptions=function(_31){
return $.extend({},$.fn.combo.parseOptions(_31),$.fn.tree.parseOptions(_31));
};
$.fn.combotree.defaults=$.extend({},$.fn.combo.defaults,$.fn.tree.defaults,{editable:false});
})(jQuery);

;
/*!
 * Cropper.js v1.5.6
 * https://fengyuanchen.github.io/cropperjs
 *
 * Copyright 2015-present Chen Fengyuan
 * Released under the MIT license
 *
 * Date: 2019-10-04T04:33:48.372Z
 */

(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
        typeof define === 'function' && define.amd ? define(factory) :
            (global = global || self, global.Cropper = factory());
}(this, function () {
    'use strict';

    function _typeof(obj) {
        if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
            _typeof = function (obj) {
                return typeof obj;
            };
        } else {
            _typeof = function (obj) {
                return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
            };
        }

        return _typeof(obj);
    }

    function _classCallCheck(instance, Constructor) {
        if (!(instance instanceof Constructor)) {
            throw new TypeError("Cannot call a class as a function");
        }
    }

    function _defineProperties(target, props) {
        for (var i = 0; i < props.length; i++) {
            var descriptor = props[i];
            descriptor.enumerable = descriptor.enumerable || false;
            descriptor.configurable = true;
            if ("value" in descriptor) descriptor.writable = true;
            Object.defineProperty(target, descriptor.key, descriptor);
        }
    }

    function _createClass(Constructor, protoProps, staticProps) {
        if (protoProps) _defineProperties(Constructor.prototype, protoProps);
        if (staticProps) _defineProperties(Constructor, staticProps);
        return Constructor;
    }

    function _defineProperty(obj, key, value) {
        if (key in obj) {
            Object.defineProperty(obj, key, {
                value: value,
                enumerable: true,
                configurable: true,
                writable: true
            });
        } else {
            obj[key] = value;
        }

        return obj;
    }

    function ownKeys(object, enumerableOnly) {
        var keys = Object.keys(object);

        if (Object.getOwnPropertySymbols) {
            var symbols = Object.getOwnPropertySymbols(object);
            if (enumerableOnly) symbols = symbols.filter(function (sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
            keys.push.apply(keys, symbols);
        }

        return keys;
    }

    function _objectSpread2(target) {
        for (var i = 1; i < arguments.length; i++) {
            var source = arguments[i] != null ? arguments[i] : {};

            if (i % 2) {
                ownKeys(source, true).forEach(function (key) {
                    _defineProperty(target, key, source[key]);
                });
            } else if (Object.getOwnPropertyDescriptors) {
                Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
            } else {
                ownKeys(source).forEach(function (key) {
                    Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
                });
            }
        }

        return target;
    }

    function _toConsumableArray(arr) {
        return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
    }

    function _arrayWithoutHoles(arr) {
        if (Array.isArray(arr)) {
            for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];

            return arr2;
        }
    }

    function _iterableToArray(iter) {
        if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
    }

    function _nonIterableSpread() {
        throw new TypeError("Invalid attempt to spread non-iterable instance");
    }

    var IS_BROWSER = typeof window !== 'undefined' && typeof window.document !== 'undefined';
    var WINDOW = IS_BROWSER ? window : {};
    var IS_TOUCH_DEVICE = IS_BROWSER ? 'ontouchstart' in WINDOW.document.documentElement : false;
    var HAS_POINTER_EVENT = IS_BROWSER ? 'PointerEvent' in WINDOW : false;
    var NAMESPACE = 'cropper'; // Actions

    var ACTION_ALL = 'all';
    var ACTION_CROP = 'crop';
    var ACTION_MOVE = 'move';
    var ACTION_ZOOM = 'zoom';
    var ACTION_EAST = 'e';
    var ACTION_WEST = 'w';
    var ACTION_SOUTH = 's';
    var ACTION_NORTH = 'n';
    var ACTION_NORTH_EAST = 'ne';
    var ACTION_NORTH_WEST = 'nw';
    var ACTION_SOUTH_EAST = 'se';
    var ACTION_SOUTH_WEST = 'sw'; // Classes

    var CLASS_CROP = "".concat(NAMESPACE, "-crop");
    var CLASS_DISABLED = "".concat(NAMESPACE, "-disabled");
    var CLASS_HIDDEN = "".concat(NAMESPACE, "-hidden");
    var CLASS_HIDE = "".concat(NAMESPACE, "-hide");
    var CLASS_INVISIBLE = "".concat(NAMESPACE, "-invisible");
    var CLASS_MODAL = "".concat(NAMESPACE, "-modal");
    var CLASS_MOVE = "".concat(NAMESPACE, "-move"); // Data keys

    var DATA_ACTION = "".concat(NAMESPACE, "Action");
    var DATA_PREVIEW = "".concat(NAMESPACE, "Preview"); // Drag modes

    var DRAG_MODE_CROP = 'crop';
    var DRAG_MODE_MOVE = 'move';
    var DRAG_MODE_NONE = 'none'; // Events

    var EVENT_CROP = 'crop';
    var EVENT_CROP_END = 'cropend';
    var EVENT_CROP_MOVE = 'cropmove';
    var EVENT_CROP_START = 'cropstart';
    var EVENT_DBLCLICK = 'dblclick';
    var EVENT_TOUCH_START = IS_TOUCH_DEVICE ? 'touchstart' : 'mousedown';
    var EVENT_TOUCH_MOVE = IS_TOUCH_DEVICE ? 'touchmove' : 'mousemove';
    var EVENT_TOUCH_END = IS_TOUCH_DEVICE ? 'touchend touchcancel' : 'mouseup';
    var EVENT_POINTER_DOWN = HAS_POINTER_EVENT ? 'pointerdown' : EVENT_TOUCH_START;
    var EVENT_POINTER_MOVE = HAS_POINTER_EVENT ? 'pointermove' : EVENT_TOUCH_MOVE;
    var EVENT_POINTER_UP = HAS_POINTER_EVENT ? 'pointerup pointercancel' : EVENT_TOUCH_END;
    var EVENT_READY = 'ready';
    var EVENT_RESIZE = 'resize';
    var EVENT_WHEEL = 'wheel';
    var EVENT_ZOOM = 'zoom'; // Mime types

    var MIME_TYPE_JPEG = 'image/jpeg'; // RegExps

    var REGEXP_ACTIONS = /^e|w|s|n|se|sw|ne|nw|all|crop|move|zoom$/;
    var REGEXP_DATA_URL = /^data:/;
    var REGEXP_DATA_URL_JPEG = /^data:image\/jpeg;base64,/;
    var REGEXP_TAG_NAME = /^img|canvas$/i; // Misc
    // Inspired by the default width and height of a canvas element.

    var MIN_CONTAINER_WIDTH = 200;
    var MIN_CONTAINER_HEIGHT = 100;

    var DEFAULTS = {
        // Define the view mode of the cropper
        viewMode: 0,
        // 0, 1, 2, 3
        // Define the dragging mode of the cropper
        dragMode: DRAG_MODE_CROP,
        // 'crop', 'move' or 'none'
        // Define the initial aspect ratio of the crop box
        initialAspectRatio: NaN,
        // Define the aspect ratio of the crop box
        aspectRatio: NaN,
        // An object with the previous cropping result data
        data: null,
        // A selector for adding extra containers to preview
        preview: '',
        // Re-render the cropper when resize the window
        responsive: true,
        // Restore the cropped area after resize the window
        restore: true,
        // Check if the current image is a cross-origin image
        checkCrossOrigin: true,
        // Check the current image's Exif Orientation information
        checkOrientation: true,
        // Show the black modal
        modal: true,
        // Show the dashed lines for guiding
        guides: true,
        // Show the center indicator for guiding
        center: true,
        // Show the white modal to highlight the crop box
        highlight: true,
        // Show the grid background
        background: true,
        // Enable to crop the image automatically when initialize
        autoCrop: true,
        // Define the percentage of automatic cropping area when initializes
        autoCropArea: 0.8,
        // Enable to move the image
        movable: true,
        // Enable to rotate the image
        rotatable: true,
        // Enable to scale the image
        scalable: true,
        // Enable to zoom the image
        zoomable: true,
        // Enable to zoom the image by dragging touch
        zoomOnTouch: true,
        // Enable to zoom the image by wheeling mouse
        zoomOnWheel: true,
        // Define zoom ratio when zoom the image by wheeling mouse
        wheelZoomRatio: 0.1,
        // Enable to move the crop box
        cropBoxMovable: true,
        // Enable to resize the crop box
        cropBoxResizable: true,
        // Toggle drag mode between "crop" and "move" when click twice on the cropper
        toggleDragModeOnDblclick: true,
        // Size limitation
        minCanvasWidth: 0,
        minCanvasHeight: 0,
        minCropBoxWidth: 0,
        minCropBoxHeight: 0,
        minContainerWidth: 200,
        minContainerHeight: 100,
        // Shortcuts of events
        ready: null,
        cropstart: null,
        cropmove: null,
        cropend: null,
        crop: null,
        zoom: null
    };

    var TEMPLATE = '<div class="cropper-container" touch-action="none">' + '<div class="cropper-wrap-box">' + '<div class="cropper-canvas"></div>' + '</div>' + '<div class="cropper-drag-box"></div>' + '<div class="cropper-crop-box">' + '<span class="cropper-view-box"></span>' + '<span class="cropper-dashed dashed-h"></span>' + '<span class="cropper-dashed dashed-v"></span>' + '<span class="cropper-center"></span>' + '<span class="cropper-face"></span>' + '<span class="cropper-line line-e" data-cropper-action="e"></span>' + '<span class="cropper-line line-n" data-cropper-action="n"></span>' + '<span class="cropper-line line-w" data-cropper-action="w"></span>' + '<span class="cropper-line line-s" data-cropper-action="s"></span>' + '<span class="cropper-point point-e" data-cropper-action="e"></span>' + '<span class="cropper-point point-n" data-cropper-action="n"></span>' + '<span class="cropper-point point-w" data-cropper-action="w"></span>' + '<span class="cropper-point point-s" data-cropper-action="s"></span>' + '<span class="cropper-point point-ne" data-cropper-action="ne"></span>' + '<span class="cropper-point point-nw" data-cropper-action="nw"></span>' + '<span class="cropper-point point-sw" data-cropper-action="sw"></span>' + '<span class="cropper-point point-se" data-cropper-action="se"></span>' + '</div>' + '</div>';

    /**
     * Check if the given value is not a number.
     */

    var isNaN = Number.isNaN || WINDOW.isNaN;
    /**
     * Check if the given value is a number.
     * @param {*} value - The value to check.
     * @returns {boolean} Returns `true` if the given value is a number, else `false`.
     */

    function isNumber(value) {
        return typeof value === 'number' && !isNaN(value);
    }
    /**
     * Check if the given value is a positive number.
     * @param {*} value - The value to check.
     * @returns {boolean} Returns `true` if the given value is a positive number, else `false`.
     */

    var isPositiveNumber = function isPositiveNumber(value) {
        return value > 0 && value < Infinity;
    };
    /**
     * Check if the given value is undefined.
     * @param {*} value - The value to check.
     * @returns {boolean} Returns `true` if the given value is undefined, else `false`.
     */

    function isUndefined(value) {
        return typeof value === 'undefined';
    }
    /**
     * Check if the given value is an object.
     * @param {*} value - The value to check.
     * @returns {boolean} Returns `true` if the given value is an object, else `false`.
     */

    function isObject(value) {
        return _typeof(value) === 'object' && value !== null;
    }
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    /**
     * Check if the given value is a plain object.
     * @param {*} value - The value to check.
     * @returns {boolean} Returns `true` if the given value is a plain object, else `false`.
     */

    function isPlainObject(value) {
        if (!isObject(value)) {
            return false;
        }

        try {
            var _constructor = value.constructor;
            var prototype = _constructor.prototype;
            return _constructor && prototype && hasOwnProperty.call(prototype, 'isPrototypeOf');
        } catch (error) {
            return false;
        }
    }
    /**
     * Check if the given value is a function.
     * @param {*} value - The value to check.
     * @returns {boolean} Returns `true` if the given value is a function, else `false`.
     */

    function isFunction(value) {
        return typeof value === 'function';
    }
    var slice = Array.prototype.slice;
    /**
     * Convert array-like or iterable object to an array.
     * @param {*} value - The value to convert.
     * @returns {Array} Returns a new array.
     */

    function toArray(value) {
        return Array.from ? Array.from(value) : slice.call(value);
    }
    /**
     * Iterate the given data.
     * @param {*} data - The data to iterate.
     * @param {Function} callback - The process function for each element.
     * @returns {*} The original data.
     */

    function forEach(data, callback) {
        if (data && isFunction(callback)) {
            if (Array.isArray(data) || isNumber(data.length)
                /* array-like */
            ) {
                toArray(data).forEach(function (value, key) {
                    callback.call(data, value, key, data);
                });
            } else if (isObject(data)) {
                Object.keys(data).forEach(function (key) {
                    callback.call(data, data[key], key, data);
                });
            }
        }

        return data;
    }
    /**
     * Extend the given object.
     * @param {*} target - The target object to extend.
     * @param {*} args - The rest objects for merging to the target object.
     * @returns {Object} The extended object.
     */

    var assign = Object.assign || function assign(target) {
        for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
            args[_key - 1] = arguments[_key];
        }

        if (isObject(target) && args.length > 0) {
            args.forEach(function (arg) {
                if (isObject(arg)) {
                    Object.keys(arg).forEach(function (key) {
                        target[key] = arg[key];
                    });
                }
            });
        }

        return target;
    };
    var REGEXP_DECIMALS = /\.\d*(?:0|9){12}\d*$/;
    /**
     * Normalize decimal number.
     * Check out {@link http://0.30000000000000004.com/}
     * @param {number} value - The value to normalize.
     * @param {number} [times=100000000000] - The times for normalizing.
     * @returns {number} Returns the normalized number.
     */

    function normalizeDecimalNumber(value) {
        var times = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100000000000;
        return REGEXP_DECIMALS.test(value) ? Math.round(value * times) / times : value;
    }
    var REGEXP_SUFFIX = /^width|height|left|top|marginLeft|marginTop$/;
    /**
     * Apply styles to the given element.
     * @param {Element} element - The target element.
     * @param {Object} styles - The styles for applying.
     */

    function setStyle(element, styles) {
        var style = element.style;
        forEach(styles, function (value, property) {
            if (REGEXP_SUFFIX.test(property) && isNumber(value)) {
                value = "".concat(value, "px");
            }

            style[property] = value;
        });
    }
    /**
     * Check if the given element has a special class.
     * @param {Element} element - The element to check.
     * @param {string} value - The class to search.
     * @returns {boolean} Returns `true` if the special class was found.
     */

    function hasClass(element, value) {
        return element.classList ? element.classList.contains(value) : element.className.indexOf(value) > -1;
    }
    /**
     * Add classes to the given element.
     * @param {Element} element - The target element.
     * @param {string} value - The classes to be added.
     */

    function addClass(element, value) {
        if (!value) {
            return;
        }

        if (isNumber(element.length)) {
            forEach(element, function (elem) {
                addClass(elem, value);
            });
            return;
        }

        if (element.classList) {
            element.classList.add(value);
            return;
        }

        var className = element.className.trim();

        if (!className) {
            element.className = value;
        } else if (className.indexOf(value) < 0) {
            element.className = "".concat(className, " ").concat(value);
        }
    }
    /**
     * Remove classes from the given element.
     * @param {Element} element - The target element.
     * @param {string} value - The classes to be removed.
     */

    function removeClass(element, value) {
        if (!value) {
            return;
        }

        if (isNumber(element.length)) {
            forEach(element, function (elem) {
                removeClass(elem, value);
            });
            return;
        }

        if (element.classList) {
            element.classList.remove(value);
            return;
        }

        if (element.className.indexOf(value) >= 0) {
            element.className = element.className.replace(value, '');
        }
    }
    /**
     * Add or remove classes from the given element.
     * @param {Element} element - The target element.
     * @param {string} value - The classes to be toggled.
     * @param {boolean} added - Add only.
     */

    function toggleClass(element, value, added) {
        if (!value) {
            return;
        }

        if (isNumber(element.length)) {
            forEach(element, function (elem) {
                toggleClass(elem, value, added);
            });
            return;
        } // IE10-11 doesn't support the second parameter of `classList.toggle`


        if (added) {
            addClass(element, value);
        } else {
            removeClass(element, value);
        }
    }
    var REGEXP_CAMEL_CASE = /([a-z\d])([A-Z])/g;
    /**
     * Transform the given string from camelCase to kebab-case
     * @param {string} value - The value to transform.
     * @returns {string} The transformed value.
     */

    function toParamCase(value) {
        return value.replace(REGEXP_CAMEL_CASE, '$1-$2').toLowerCase();
    }
    /**
     * Get data from the given element.
     * @param {Element} element - The target element.
     * @param {string} name - The data key to get.
     * @returns {string} The data value.
     */

    function getData(element, name) {
        if (isObject(element[name])) {
            return element[name];
        }

        if (element.dataset) {
            return element.dataset[name];
        }

        return element.getAttribute("data-".concat(toParamCase(name)));
    }
    /**
     * Set data to the given element.
     * @param {Element} element - The target element.
     * @param {string} name - The data key to set.
     * @param {string} data - The data value.
     */

    function setData(element, name, data) {
        if (isObject(data)) {
            element[name] = data;
        } else if (element.dataset) {
            element.dataset[name] = data;
        } else {
            element.setAttribute("data-".concat(toParamCase(name)), data);
        }
    }
    /**
     * Remove data from the given element.
     * @param {Element} element - The target element.
     * @param {string} name - The data key to remove.
     */

    function removeData(element, name) {
        if (isObject(element[name])) {
            try {
                delete element[name];
            } catch (error) {
                element[name] = undefined;
            }
        } else if (element.dataset) {
            // #128 Safari not allows to delete dataset property
            try {
                delete element.dataset[name];
            } catch (error) {
                element.dataset[name] = undefined;
            }
        } else {
            element.removeAttribute("data-".concat(toParamCase(name)));
        }
    }
    var REGEXP_SPACES = /\s\s*/;

    var onceSupported = function () {
        var supported = false;

        if (IS_BROWSER) {
            var once = false;

            var listener = function listener() { };

            var options = Object.defineProperty({}, 'once', {
                get: function get() {
                    supported = true;
                    return once;
                },

                /**
                 * This setter can fix a `TypeError` in strict mode
                 * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only}
                 * @param {boolean} value - The value to set
                 */
                set: function set(value) {
                    once = value;
                }
            });
            WINDOW.addEventListener('test', listener, options);
            WINDOW.removeEventListener('test', listener, options);
        }

        return supported;
    }();
    /**
     * Remove event listener from the target element.
     * @param {Element} element - The event target.
     * @param {string} type - The event type(s).
     * @param {Function} listener - The event listener.
     * @param {Object} options - The event options.
     */


    function removeListener(element, type, listener) {
        var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
        var handler = listener;
        type.trim().split(REGEXP_SPACES).forEach(function (event) {
            if (!onceSupported) {
                var listeners = element.listeners;

                if (listeners && listeners[event] && listeners[event][listener]) {
                    handler = listeners[event][listener];
                    delete listeners[event][listener];

                    if (Object.keys(listeners[event]).length === 0) {
                        delete listeners[event];
                    }

                    if (Object.keys(listeners).length === 0) {
                        delete element.listeners;
                    }
                }
            }

            element.removeEventListener(event, handler, options);
        });
    }
    /**
     * Add event listener to the target element.
     * @param {Element} element - The event target.
     * @param {string} type - The event type(s).
     * @param {Function} listener - The event listener.
     * @param {Object} options - The event options.
     */

    function addListener(element, type, listener) {
        var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
        var _handler = listener;
        type.trim().split(REGEXP_SPACES).forEach(function (event) {
            if (options.once && !onceSupported) {
                var _element$listeners = element.listeners,
                    listeners = _element$listeners === void 0 ? {} : _element$listeners;

                _handler = function handler() {
                    delete listeners[event][listener];
                    element.removeEventListener(event, _handler, options);

                    for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
                        args[_key2] = arguments[_key2];
                    }

                    listener.apply(element, args);
                };

                if (!listeners[event]) {
                    listeners[event] = {};
                }

                if (listeners[event][listener]) {
                    element.removeEventListener(event, listeners[event][listener], options);
                }

                listeners[event][listener] = _handler;
                element.listeners = listeners;
            }

            element.addEventListener(event, _handler, options);
        });
    }
    /**
     * Dispatch event on the target element.
     * @param {Element} element - The event target.
     * @param {string} type - The event type(s).
     * @param {Object} data - The additional event data.
     * @returns {boolean} Indicate if the event is default prevented or not.
     */

    function dispatchEvent(element, type, data) {
        var event; // Event and CustomEvent on IE9-11 are global objects, not constructors

        if (isFunction(Event) && isFunction(CustomEvent)) {
            event = new CustomEvent(type, {
                detail: data,
                bubbles: true,
                cancelable: true
            });
        } else {
            event = document.createEvent('CustomEvent');
            event.initCustomEvent(type, true, true, data);
        }

        return element.dispatchEvent(event);
    }
    /**
     * Get the offset base on the document.
     * @param {Element} element - The target element.
     * @returns {Object} The offset data.
     */

    function getOffset(element) {
        var box = element.getBoundingClientRect();
        return {
            left: box.left + (window.pageXOffset - document.documentElement.clientLeft),
            top: box.top + (window.pageYOffset - document.documentElement.clientTop)
        };
    }
    var location = WINDOW.location;
    var REGEXP_ORIGINS = /^(\w+:)\/\/([^:/?#]*):?(\d*)/i;
    /**
     * Check if the given URL is a cross origin URL.
     * @param {string} url - The target URL.
     * @returns {boolean} Returns `true` if the given URL is a cross origin URL, else `false`.
     */

    function isCrossOriginURL(url) {
        var parts = url.match(REGEXP_ORIGINS);
        return parts !== null && (parts[1] !== location.protocol || parts[2] !== location.hostname || parts[3] !== location.port);
    }
    /**
     * Add timestamp to the given URL.
     * @param {string} url - The target URL.
     * @returns {string} The result URL.
     */

    function addTimestamp(url) {
        var timestamp = "timestamp=".concat(new Date().getTime());
        return url + (url.indexOf('?') === -1 ? '?' : '&') + timestamp;
    }
    /**
     * Get transforms base on the given object.
     * @param {Object} obj - The target object.
     * @returns {string} A string contains transform values.
     */

    function getTransforms(_ref) {
        var rotate = _ref.rotate,
            scaleX = _ref.scaleX,
            scaleY = _ref.scaleY,
            translateX = _ref.translateX,
            translateY = _ref.translateY;
        var values = [];

        if (isNumber(translateX) && translateX !== 0) {
            values.push("translateX(".concat(translateX, "px)"));
        }

        if (isNumber(translateY) && translateY !== 0) {
            values.push("translateY(".concat(translateY, "px)"));
        } // Rotate should come first before scale to match orientation transform


        if (isNumber(rotate) && rotate !== 0) {
            values.push("rotate(".concat(rotate, "deg)"));
        }

        if (isNumber(scaleX) && scaleX !== 1) {
            values.push("scaleX(".concat(scaleX, ")"));
        }

        if (isNumber(scaleY) && scaleY !== 1) {
            values.push("scaleY(".concat(scaleY, ")"));
        }

        var transform = values.length ? values.join(' ') : 'none';
        return {
            WebkitTransform: transform,
            msTransform: transform,
            transform: transform
        };
    }
    /**
     * Get the max ratio of a group of pointers.
     * @param {string} pointers - The target pointers.
     * @returns {number} The result ratio.
     */

    function getMaxZoomRatio(pointers) {
        var pointers2 = _objectSpread2({}, pointers);

        var ratios = [];
        forEach(pointers, function (pointer, pointerId) {
            delete pointers2[pointerId];
            forEach(pointers2, function (pointer2) {
                var x1 = Math.abs(pointer.startX - pointer2.startX);
                var y1 = Math.abs(pointer.startY - pointer2.startY);
                var x2 = Math.abs(pointer.endX - pointer2.endX);
                var y2 = Math.abs(pointer.endY - pointer2.endY);
                var z1 = Math.sqrt(x1 * x1 + y1 * y1);
                var z2 = Math.sqrt(x2 * x2 + y2 * y2);
                var ratio = (z2 - z1) / z1;
                ratios.push(ratio);
            });
        });
        ratios.sort(function (a, b) {
            return Math.abs(a) < Math.abs(b);
        });
        return ratios[0];
    }
    /**
     * Get a pointer from an event object.
     * @param {Object} event - The target event object.
     * @param {boolean} endOnly - Indicates if only returns the end point coordinate or not.
     * @returns {Object} The result pointer contains start and/or end point coordinates.
     */

    function getPointer(_ref2, endOnly) {
        var pageX = _ref2.pageX,
            pageY = _ref2.pageY;
        var end = {
            endX: pageX,
            endY: pageY
        };
        return endOnly ? end : _objectSpread2({
            startX: pageX,
            startY: pageY
        }, end);
    }
    /**
     * Get the center point coordinate of a group of pointers.
     * @param {Object} pointers - The target pointers.
     * @returns {Object} The center point coordinate.
     */

    function getPointersCenter(pointers) {
        var pageX = 0;
        var pageY = 0;
        var count = 0;
        forEach(pointers, function (_ref3) {
            var startX = _ref3.startX,
                startY = _ref3.startY;
            pageX += startX;
            pageY += startY;
            count += 1;
        });
        pageX /= count;
        pageY /= count;
        return {
            pageX: pageX,
            pageY: pageY
        };
    }
    /**
     * Get the max sizes in a rectangle under the given aspect ratio.
     * @param {Object} data - The original sizes.
     * @param {string} [type='contain'] - The adjust type.
     * @returns {Object} The result sizes.
     */

    function getAdjustedSizes(_ref4) // or 'cover'
    {
        var aspectRatio = _ref4.aspectRatio,
            height = _ref4.height,
            width = _ref4.width;
        var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'contain';
        var isValidWidth = isPositiveNumber(width);
        var isValidHeight = isPositiveNumber(height);

        if (isValidWidth && isValidHeight) {
            var adjustedWidth = height * aspectRatio;

            if (type === 'contain' && adjustedWidth > width || type === 'cover' && adjustedWidth < width) {
                height = width / aspectRatio;
            } else {
                width = height * aspectRatio;
            }
        } else if (isValidWidth) {
            height = width / aspectRatio;
        } else if (isValidHeight) {
            width = height * aspectRatio;
        }

        return {
            width: width,
            height: height
        };
    }
    /**
     * Get the new sizes of a rectangle after rotated.
     * @param {Object} data - The original sizes.
     * @returns {Object} The result sizes.
     */

    function getRotatedSizes(_ref5) {
        var width = _ref5.width,
            height = _ref5.height,
            degree = _ref5.degree;
        degree = Math.abs(degree) % 180;

        if (degree === 90) {
            return {
                width: height,
                height: width
            };
        }

        var arc = degree % 90 * Math.PI / 180;
        var sinArc = Math.sin(arc);
        var cosArc = Math.cos(arc);
        var newWidth = width * cosArc + height * sinArc;
        var newHeight = width * sinArc + height * cosArc;
        return degree > 90 ? {
            width: newHeight,
            height: newWidth
        } : {
                width: newWidth,
                height: newHeight
            };
    }
    /**
     * Get a canvas which drew the given image.
     * @param {HTMLImageElement} image - The image for drawing.
     * @param {Object} imageData - The image data.
     * @param {Object} canvasData - The canvas data.
     * @param {Object} options - The options.
     * @returns {HTMLCanvasElement} The result canvas.
     */

    function getSourceCanvas(image, _ref6, _ref7, _ref8) {
        var imageAspectRatio = _ref6.aspectRatio,
            imageNaturalWidth = _ref6.naturalWidth,
            imageNaturalHeight = _ref6.naturalHeight,
            _ref6$rotate = _ref6.rotate,
            rotate = _ref6$rotate === void 0 ? 0 : _ref6$rotate,
            _ref6$scaleX = _ref6.scaleX,
            scaleX = _ref6$scaleX === void 0 ? 1 : _ref6$scaleX,
            _ref6$scaleY = _ref6.scaleY,
            scaleY = _ref6$scaleY === void 0 ? 1 : _ref6$scaleY;
        var aspectRatio = _ref7.aspectRatio,
            naturalWidth = _ref7.naturalWidth,
            naturalHeight = _ref7.naturalHeight;
        var _ref8$fillColor = _ref8.fillColor,
            fillColor = _ref8$fillColor === void 0 ? 'transparent' : _ref8$fillColor,
            _ref8$imageSmoothingE = _ref8.imageSmoothingEnabled,
            imageSmoothingEnabled = _ref8$imageSmoothingE === void 0 ? true : _ref8$imageSmoothingE,
            _ref8$imageSmoothingQ = _ref8.imageSmoothingQuality,
            imageSmoothingQuality = _ref8$imageSmoothingQ === void 0 ? 'low' : _ref8$imageSmoothingQ,
            _ref8$maxWidth = _ref8.maxWidth,
            maxWidth = _ref8$maxWidth === void 0 ? Infinity : _ref8$maxWidth,
            _ref8$maxHeight = _ref8.maxHeight,
            maxHeight = _ref8$maxHeight === void 0 ? Infinity : _ref8$maxHeight,
            _ref8$minWidth = _ref8.minWidth,
            minWidth = _ref8$minWidth === void 0 ? 0 : _ref8$minWidth,
            _ref8$minHeight = _ref8.minHeight,
            minHeight = _ref8$minHeight === void 0 ? 0 : _ref8$minHeight;
        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');
        var maxSizes = getAdjustedSizes({
            aspectRatio: aspectRatio,
            width: maxWidth,
            height: maxHeight
        });
        var minSizes = getAdjustedSizes({
            aspectRatio: aspectRatio,
            width: minWidth,
            height: minHeight
        }, 'cover');
        var width = Math.min(maxSizes.width, Math.max(minSizes.width, naturalWidth));
        var height = Math.min(maxSizes.height, Math.max(minSizes.height, naturalHeight)); // Note: should always use image's natural sizes for drawing as
        // imageData.naturalWidth === canvasData.naturalHeight when rotate % 180 === 90

        var destMaxSizes = getAdjustedSizes({
            aspectRatio: imageAspectRatio,
            width: maxWidth,
            height: maxHeight
        });
        var destMinSizes = getAdjustedSizes({
            aspectRatio: imageAspectRatio,
            width: minWidth,
            height: minHeight
        }, 'cover');
        var destWidth = Math.min(destMaxSizes.width, Math.max(destMinSizes.width, imageNaturalWidth));
        var destHeight = Math.min(destMaxSizes.height, Math.max(destMinSizes.height, imageNaturalHeight));
        var params = [-destWidth / 2, -destHeight / 2, destWidth, destHeight];
        canvas.width = normalizeDecimalNumber(width);
        canvas.height = normalizeDecimalNumber(height);
        context.fillStyle = fillColor;
        context.fillRect(0, 0, width, height);
        context.save();
        context.translate(width / 2, height / 2);
        context.rotate(rotate * Math.PI / 180);
        context.scale(scaleX, scaleY);
        context.imageSmoothingEnabled = imageSmoothingEnabled;
        context.imageSmoothingQuality = imageSmoothingQuality;
        context.drawImage.apply(context, [image].concat(_toConsumableArray(params.map(function (param) {
            return Math.floor(normalizeDecimalNumber(param));
        }))));
        context.restore();
        return canvas;
    }
    var fromCharCode = String.fromCharCode;
    /**
     * Get string from char code in data view.
     * @param {DataView} dataView - The data view for read.
     * @param {number} start - The start index.
     * @param {number} length - The read length.
     * @returns {string} The read result.
     */

    function getStringFromCharCode(dataView, start, length) {
        var str = '';
        length += start;

        for (var i = start; i < length; i += 1) {
            str += fromCharCode(dataView.getUint8(i));
        }

        return str;
    }
    var REGEXP_DATA_URL_HEAD = /^data:.*,/;
    /**
     * Transform Data URL to array buffer.
     * @param {string} dataURL - The Data URL to transform.
     * @returns {ArrayBuffer} The result array buffer.
     */

    function dataURLToArrayBuffer(dataURL) {
        var base64 = dataURL.replace(REGEXP_DATA_URL_HEAD, '');
        var binary = atob(base64);
        var arrayBuffer = new ArrayBuffer(binary.length);
        var uint8 = new Uint8Array(arrayBuffer);
        forEach(uint8, function (value, i) {
            uint8[i] = binary.charCodeAt(i);
        });
        return arrayBuffer;
    }
    /**
     * Transform array buffer to Data URL.
     * @param {ArrayBuffer} arrayBuffer - The array buffer to transform.
     * @param {string} mimeType - The mime type of the Data URL.
     * @returns {string} The result Data URL.
     */

    function arrayBufferToDataURL(arrayBuffer, mimeType) {
        var chunks = []; // Chunk Typed Array for better performance (#435)

        var chunkSize = 8192;
        var uint8 = new Uint8Array(arrayBuffer);

        while (uint8.length > 0) {
            // XXX: Babel's `toConsumableArray` helper will throw error in IE or Safari 9
            // eslint-disable-next-line prefer-spread
            chunks.push(fromCharCode.apply(null, toArray(uint8.subarray(0, chunkSize))));
            uint8 = uint8.subarray(chunkSize);
        }

        return "data:".concat(mimeType, ";base64,").concat(btoa(chunks.join('')));
    }
    /**
     * Get orientation value from given array buffer.
     * @param {ArrayBuffer} arrayBuffer - The array buffer to read.
     * @returns {number} The read orientation value.
     */

    function resetAndGetOrientation(arrayBuffer) {
        var dataView = new DataView(arrayBuffer);
        var orientation; // Ignores range error when the image does not have correct Exif information

        try {
            var littleEndian;
            var app1Start;
            var ifdStart; // Only handle JPEG image (start by 0xFFD8)

            if (dataView.getUint8(0) === 0xFF && dataView.getUint8(1) === 0xD8) {
                var length = dataView.byteLength;
                var offset = 2;

                while (offset + 1 < length) {
                    if (dataView.getUint8(offset) === 0xFF && dataView.getUint8(offset + 1) === 0xE1) {
                        app1Start = offset;
                        break;
                    }

                    offset += 1;
                }
            }

            if (app1Start) {
                var exifIDCode = app1Start + 4;
                var tiffOffset = app1Start + 10;

                if (getStringFromCharCode(dataView, exifIDCode, 4) === 'Exif') {
                    var endianness = dataView.getUint16(tiffOffset);
                    littleEndian = endianness === 0x4949;

                    if (littleEndian || endianness === 0x4D4D
                        /* bigEndian */
                    ) {
                        if (dataView.getUint16(tiffOffset + 2, littleEndian) === 0x002A) {
                            var firstIFDOffset = dataView.getUint32(tiffOffset + 4, littleEndian);

                            if (firstIFDOffset >= 0x00000008) {
                                ifdStart = tiffOffset + firstIFDOffset;
                            }
                        }
                    }
                }
            }

            if (ifdStart) {
                var _length = dataView.getUint16(ifdStart, littleEndian);

                var _offset;

                var i;

                for (i = 0; i < _length; i += 1) {
                    _offset = ifdStart + i * 12 + 2;

                    if (dataView.getUint16(_offset, littleEndian) === 0x0112
                        /* Orientation */
                    ) {
                        // 8 is the offset of the current tag's value
                        _offset += 8; // Get the original orientation value

                        orientation = dataView.getUint16(_offset, littleEndian); // Override the orientation with its default value

                        dataView.setUint16(_offset, 1, littleEndian);
                        break;
                    }
                }
            }
        } catch (error) {
            orientation = 1;
        }

        return orientation;
    }
    /**
     * Parse Exif Orientation value.
     * @param {number} orientation - The orientation to parse.
     * @returns {Object} The parsed result.
     */

    function parseOrientation(orientation) {
        var rotate = 0;
        var scaleX = 1;
        var scaleY = 1;

        switch (orientation) {
            // Flip horizontal
            case 2:
                scaleX = -1;
                break;
            // Rotate left 180�

            case 3:
                rotate = -180;
                break;
            // Flip vertical

            case 4:
                scaleY = -1;
                break;
            // Flip vertical and rotate right 90�

            case 5:
                rotate = 90;
                scaleY = -1;
                break;
            // Rotate right 90�

            case 6:
                rotate = 90;
                break;
            // Flip horizontal and rotate right 90�

            case 7:
                rotate = 90;
                scaleX = -1;
                break;
            // Rotate left 90�

            case 8:
                rotate = -90;
                break;

            default:
        }

        return {
            rotate: rotate,
            scaleX: scaleX,
            scaleY: scaleY
        };
    }

    var render = {
        render: function render() {
            this.initContainer();
            this.initCanvas();
            this.initCropBox();
            this.renderCanvas();

            if (this.cropped) {
                this.renderCropBox();
            }
        },
        initContainer: function initContainer() {
            var element = this.element,
                options = this.options,
                container = this.container,
                cropper = this.cropper;
            addClass(cropper, CLASS_HIDDEN);
            removeClass(element, CLASS_HIDDEN);
            var containerData = {
                width: Math.max(container.offsetWidth, Number(options.minContainerWidth) || 200),
                height: Math.max(container.offsetHeight, Number(options.minContainerHeight) || 100)
            };
            this.containerData = containerData;
            setStyle(cropper, {
                width: containerData.width,
                height: containerData.height
            });
            addClass(element, CLASS_HIDDEN);
            removeClass(cropper, CLASS_HIDDEN);
        },
        // Canvas (image wrapper)
        initCanvas: function initCanvas() {
            var containerData = this.containerData,
                imageData = this.imageData;
            var viewMode = this.options.viewMode;
            var rotated = Math.abs(imageData.rotate) % 180 === 90;
            var naturalWidth = rotated ? imageData.naturalHeight : imageData.naturalWidth;
            var naturalHeight = rotated ? imageData.naturalWidth : imageData.naturalHeight;
            var aspectRatio = naturalWidth / naturalHeight;
            var canvasWidth = containerData.width;
            var canvasHeight = containerData.height;

            if (containerData.height * aspectRatio > containerData.width) {
                if (viewMode === 3) {
                    canvasWidth = containerData.height * aspectRatio;
                } else {
                    canvasHeight = containerData.width / aspectRatio;
                }
            } else if (viewMode === 3) {
                canvasHeight = containerData.width / aspectRatio;
            } else {
                canvasWidth = containerData.height * aspectRatio;
            }

            var canvasData = {
                aspectRatio: aspectRatio,
                naturalWidth: naturalWidth,
                naturalHeight: naturalHeight,
                width: canvasWidth,
                height: canvasHeight
            };
            canvasData.left = (containerData.width - canvasWidth) / 2;
            canvasData.top = (containerData.height - canvasHeight) / 2;
            canvasData.oldLeft = canvasData.left;
            canvasData.oldTop = canvasData.top;
            this.canvasData = canvasData;
            this.limited = viewMode === 1 || viewMode === 2;
            this.limitCanvas(true, true);
            this.initialImageData = assign({}, imageData);
            this.initialCanvasData = assign({}, canvasData);
        },
        limitCanvas: function limitCanvas(sizeLimited, positionLimited) {
            var options = this.options,
                containerData = this.containerData,
                canvasData = this.canvasData,
                cropBoxData = this.cropBoxData;
            var viewMode = options.viewMode;
            var aspectRatio = canvasData.aspectRatio;
            var cropped = this.cropped && cropBoxData;

            if (sizeLimited) {
                var minCanvasWidth = Number(options.minCanvasWidth) || 0;
                var minCanvasHeight = Number(options.minCanvasHeight) || 0;

                if (viewMode > 1) {
                    minCanvasWidth = Math.max(minCanvasWidth, containerData.width);
                    minCanvasHeight = Math.max(minCanvasHeight, containerData.height);

                    if (viewMode === 3) {
                        if (minCanvasHeight * aspectRatio > minCanvasWidth) {
                            minCanvasWidth = minCanvasHeight * aspectRatio;
                        } else {
                            minCanvasHeight = minCanvasWidth / aspectRatio;
                        }
                    }
                } else if (viewMode > 0) {
                    if (minCanvasWidth) {
                        minCanvasWidth = Math.max(minCanvasWidth, cropped ? cropBoxData.width : 0);
                    } else if (minCanvasHeight) {
                        minCanvasHeight = Math.max(minCanvasHeight, cropped ? cropBoxData.height : 0);
                    } else if (cropped) {
                        minCanvasWidth = cropBoxData.width;
                        minCanvasHeight = cropBoxData.height;

                        if (minCanvasHeight * aspectRatio > minCanvasWidth) {
                            minCanvasWidth = minCanvasHeight * aspectRatio;
                        } else {
                            minCanvasHeight = minCanvasWidth / aspectRatio;
                        }
                    }
                }

                var _getAdjustedSizes = getAdjustedSizes({
                    aspectRatio: aspectRatio,
                    width: minCanvasWidth,
                    height: minCanvasHeight
                });

                minCanvasWidth = _getAdjustedSizes.width;
                minCanvasHeight = _getAdjustedSizes.height;
                canvasData.minWidth = minCanvasWidth;
                canvasData.minHeight = minCanvasHeight;
                canvasData.maxWidth = Infinity;
                canvasData.maxHeight = Infinity;
            }

            if (positionLimited) {
                if (viewMode > (cropped ? 0 : 1)) {
                    var newCanvasLeft = containerData.width - canvasData.width;
                    var newCanvasTop = containerData.height - canvasData.height;
                    canvasData.minLeft = Math.min(0, newCanvasLeft);
                    canvasData.minTop = Math.min(0, newCanvasTop);
                    canvasData.maxLeft = Math.max(0, newCanvasLeft);
                    canvasData.maxTop = Math.max(0, newCanvasTop);

                    if (cropped && this.limited) {
                        canvasData.minLeft = Math.min(cropBoxData.left, cropBoxData.left + (cropBoxData.width - canvasData.width));
                        canvasData.minTop = Math.min(cropBoxData.top, cropBoxData.top + (cropBoxData.height - canvasData.height));
                        canvasData.maxLeft = cropBoxData.left;
                        canvasData.maxTop = cropBoxData.top;

                        if (viewMode === 2) {
                            if (canvasData.width >= containerData.width) {
                                canvasData.minLeft = Math.min(0, newCanvasLeft);
                                canvasData.maxLeft = Math.max(0, newCanvasLeft);
                            }

                            if (canvasData.height >= containerData.height) {
                                canvasData.minTop = Math.min(0, newCanvasTop);
                                canvasData.maxTop = Math.max(0, newCanvasTop);
                            }
                        }
                    }
                } else {
                    canvasData.minLeft = -canvasData.width;
                    canvasData.minTop = -canvasData.height;
                    canvasData.maxLeft = containerData.width;
                    canvasData.maxTop = containerData.height;
                }
            }
        },
        renderCanvas: function renderCanvas(changed, transformed) {
            var canvasData = this.canvasData,
                imageData = this.imageData;

            if (transformed) {
                var _getRotatedSizes = getRotatedSizes({
                    width: imageData.naturalWidth * Math.abs(imageData.scaleX || 1),
                    height: imageData.naturalHeight * Math.abs(imageData.scaleY || 1),
                    degree: imageData.rotate || 0
                }),
                    naturalWidth = _getRotatedSizes.width,
                    naturalHeight = _getRotatedSizes.height;

                var width = canvasData.width * (naturalWidth / canvasData.naturalWidth);
                var height = canvasData.height * (naturalHeight / canvasData.naturalHeight);
                canvasData.left -= (width - canvasData.width) / 2;
                canvasData.top -= (height - canvasData.height) / 2;
                canvasData.width = width;
                canvasData.height = height;
                canvasData.aspectRatio = naturalWidth / naturalHeight;
                canvasData.naturalWidth = naturalWidth;
                canvasData.naturalHeight = naturalHeight;
                this.limitCanvas(true, false);
            }

            if (canvasData.width > canvasData.maxWidth || canvasData.width < canvasData.minWidth) {
                canvasData.left = canvasData.oldLeft;
            }

            if (canvasData.height > canvasData.maxHeight || canvasData.height < canvasData.minHeight) {
                canvasData.top = canvasData.oldTop;
            }

            canvasData.width = Math.min(Math.max(canvasData.width, canvasData.minWidth), canvasData.maxWidth);
            canvasData.height = Math.min(Math.max(canvasData.height, canvasData.minHeight), canvasData.maxHeight);
            this.limitCanvas(false, true);
            canvasData.left = Math.min(Math.max(canvasData.left, canvasData.minLeft), canvasData.maxLeft);
            canvasData.top = Math.min(Math.max(canvasData.top, canvasData.minTop), canvasData.maxTop);
            canvasData.oldLeft = canvasData.left;
            canvasData.oldTop = canvasData.top;
            setStyle(this.canvas, assign({
                width: canvasData.width,
                height: canvasData.height
            }, getTransforms({
                translateX: canvasData.left,
                translateY: canvasData.top
            })));
            this.renderImage(changed);

            if (this.cropped && this.limited) {
                this.limitCropBox(true, true);
            }
        },
        renderImage: function renderImage(changed) {
            var canvasData = this.canvasData,
                imageData = this.imageData;
            var width = imageData.naturalWidth * (canvasData.width / canvasData.naturalWidth);
            var height = imageData.naturalHeight * (canvasData.height / canvasData.naturalHeight);
            assign(imageData, {
                width: width,
                height: height,
                left: (canvasData.width - width) / 2,
                top: (canvasData.height - height) / 2
            });
            setStyle(this.image, assign({
                width: imageData.width,
                height: imageData.height
            }, getTransforms(assign({
                translateX: imageData.left,
                translateY: imageData.top
            }, imageData))));

            if (changed) {
                this.output();
            }
        },
        initCropBox: function initCropBox() {
            var options = this.options,
                canvasData = this.canvasData;
            var aspectRatio = options.aspectRatio || options.initialAspectRatio;
            var autoCropArea = Number(options.autoCropArea) || 0.8;
            var cropBoxData = {
                width: canvasData.width,
                height: canvasData.height
            };

            if (aspectRatio) {
                if (canvasData.height * aspectRatio > canvasData.width) {
                    cropBoxData.height = cropBoxData.width / aspectRatio;
                } else {
                    cropBoxData.width = cropBoxData.height * aspectRatio;
                }
            }

            this.cropBoxData = cropBoxData;
            this.limitCropBox(true, true); // Initialize auto crop area

            cropBoxData.width = Math.min(Math.max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth);
            cropBoxData.height = Math.min(Math.max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight); // The width/height of auto crop area must large than "minWidth/Height"

            cropBoxData.width = Math.max(cropBoxData.minWidth, cropBoxData.width * autoCropArea);
            cropBoxData.height = Math.max(cropBoxData.minHeight, cropBoxData.height * autoCropArea);
            cropBoxData.left = canvasData.left + (canvasData.width - cropBoxData.width) / 2;
            cropBoxData.top = canvasData.top + (canvasData.height - cropBoxData.height) / 2;
            cropBoxData.oldLeft = cropBoxData.left;
            cropBoxData.oldTop = cropBoxData.top;
            this.initialCropBoxData = assign({}, cropBoxData);
        },
        limitCropBox: function limitCropBox(sizeLimited, positionLimited) {
            var options = this.options,
                containerData = this.containerData,
                canvasData = this.canvasData,
                cropBoxData = this.cropBoxData,
                limited = this.limited;
            var aspectRatio = options.aspectRatio;

            if (sizeLimited) {
                var minCropBoxWidth = Number(options.minCropBoxWidth) || 0;
                var minCropBoxHeight = Number(options.minCropBoxHeight) || 0;
                var maxCropBoxWidth = limited ? Math.min(containerData.width, canvasData.width, canvasData.width + canvasData.left, containerData.width - canvasData.left) : containerData.width;
                var maxCropBoxHeight = limited ? Math.min(containerData.height, canvasData.height, canvasData.height + canvasData.top, containerData.height - canvasData.top) : containerData.height; // The min/maxCropBoxWidth/Height must be less than container's width/height

                minCropBoxWidth = Math.min(minCropBoxWidth, containerData.width);
                minCropBoxHeight = Math.min(minCropBoxHeight, containerData.height);

                if (aspectRatio) {
                    if (minCropBoxWidth && minCropBoxHeight) {
                        if (minCropBoxHeight * aspectRatio > minCropBoxWidth) {
                            minCropBoxHeight = minCropBoxWidth / aspectRatio;
                        } else {
                            minCropBoxWidth = minCropBoxHeight * aspectRatio;
                        }
                    } else if (minCropBoxWidth) {
                        minCropBoxHeight = minCropBoxWidth / aspectRatio;
                    } else if (minCropBoxHeight) {
                        minCropBoxWidth = minCropBoxHeight * aspectRatio;
                    }

                    if (maxCropBoxHeight * aspectRatio > maxCropBoxWidth) {
                        maxCropBoxHeight = maxCropBoxWidth / aspectRatio;
                    } else {
                        maxCropBoxWidth = maxCropBoxHeight * aspectRatio;
                    }
                } // The minWidth/Height must be less than maxWidth/Height


                cropBoxData.minWidth = Math.min(minCropBoxWidth, maxCropBoxWidth);
                cropBoxData.minHeight = Math.min(minCropBoxHeight, maxCropBoxHeight);
                cropBoxData.maxWidth = maxCropBoxWidth;
                cropBoxData.maxHeight = maxCropBoxHeight;
            }

            if (positionLimited) {
                if (limited) {
                    cropBoxData.minLeft = Math.max(0, canvasData.left);
                    cropBoxData.minTop = Math.max(0, canvasData.top);
                    cropBoxData.maxLeft = Math.min(containerData.width, canvasData.left + canvasData.width) - cropBoxData.width;
                    cropBoxData.maxTop = Math.min(containerData.height, canvasData.top + canvasData.height) - cropBoxData.height;
                } else {
                    cropBoxData.minLeft = 0;
                    cropBoxData.minTop = 0;
                    cropBoxData.maxLeft = containerData.width - cropBoxData.width;
                    cropBoxData.maxTop = containerData.height - cropBoxData.height;
                }
            }
        },
        renderCropBox: function renderCropBox() {
            var options = this.options,
                containerData = this.containerData,
                cropBoxData = this.cropBoxData;

            if (cropBoxData.width > cropBoxData.maxWidth || cropBoxData.width < cropBoxData.minWidth) {
                cropBoxData.left = cropBoxData.oldLeft;
            }

            if (cropBoxData.height > cropBoxData.maxHeight || cropBoxData.height < cropBoxData.minHeight) {
                cropBoxData.top = cropBoxData.oldTop;
            }

            cropBoxData.width = Math.min(Math.max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth);
            cropBoxData.height = Math.min(Math.max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight);
            this.limitCropBox(false, true);
            cropBoxData.left = Math.min(Math.max(cropBoxData.left, cropBoxData.minLeft), cropBoxData.maxLeft);
            cropBoxData.top = Math.min(Math.max(cropBoxData.top, cropBoxData.minTop), cropBoxData.maxTop);
            cropBoxData.oldLeft = cropBoxData.left;
            cropBoxData.oldTop = cropBoxData.top;

            if (options.movable && options.cropBoxMovable) {
                // Turn to move the canvas when the crop box is equal to the container
                setData(this.face, DATA_ACTION, cropBoxData.width >= containerData.width && cropBoxData.height >= containerData.height ? ACTION_MOVE : ACTION_ALL);
            }

            setStyle(this.cropBox, assign({
                width: cropBoxData.width,
                height: cropBoxData.height
            }, getTransforms({
                translateX: cropBoxData.left,
                translateY: cropBoxData.top
            })));

            if (this.cropped && this.limited) {
                this.limitCanvas(true, true);
            }

            if (!this.disabled) {
                this.output();
            }
        },
        output: function output() {
            this.preview();
            dispatchEvent(this.element, EVENT_CROP, this.getData());
        }
    };

    var preview = {
        initPreview: function initPreview() {
            var element = this.element,
                crossOrigin = this.crossOrigin;
            var preview = this.options.preview;
            var url = crossOrigin ? this.crossOriginUrl : this.url;
            var alt = element.alt || 'The image to preview';
            var image = document.createElement('img');

            if (crossOrigin) {
                image.crossOrigin = crossOrigin;
            }

            image.src = url;
            image.alt = alt;
            this.viewBox.appendChild(image);
            this.viewBoxImage = image;

            if (!preview) {
                return;
            }

            var previews = preview;

            if (typeof preview === 'string') {
                previews = element.ownerDocument.querySelectorAll(preview);
            } else if (preview.querySelector) {
                previews = [preview];
            }

            this.previews = previews;
            forEach(previews, function (el) {
                var img = document.createElement('img'); // Save the original size for recover

                setData(el, DATA_PREVIEW, {
                    width: el.offsetWidth,
                    height: el.offsetHeight,
                    html: el.innerHTML
                });

                if (crossOrigin) {
                    img.crossOrigin = crossOrigin;
                }

                img.src = url;
                img.alt = alt;
                /**
                 * Override img element styles
                 * Add `display:block` to avoid margin top issue
                 * Add `height:auto` to override `height` attribute on IE8
                 * (Occur only when margin-top <= -height)
                 */

                img.style.cssText = 'display:block;' + 'width:100%;' + 'height:auto;' + 'min-width:0!important;' + 'min-height:0!important;' + 'max-width:none!important;' + 'max-height:none!important;' + 'image-orientation:0deg!important;"';
                el.innerHTML = '';
                el.appendChild(img);
            });
        },
        resetPreview: function resetPreview() {
            forEach(this.previews, function (element) {
                var data = getData(element, DATA_PREVIEW);
                setStyle(element, {
                    width: data.width,
                    height: data.height
                });
                element.innerHTML = data.html;
                removeData(element, DATA_PREVIEW);
            });
        },
        preview: function preview() {
            var imageData = this.imageData,
                canvasData = this.canvasData,
                cropBoxData = this.cropBoxData;
            var cropBoxWidth = cropBoxData.width,
                cropBoxHeight = cropBoxData.height;
            var width = imageData.width,
                height = imageData.height;
            var left = cropBoxData.left - canvasData.left - imageData.left;
            var top = cropBoxData.top - canvasData.top - imageData.top;

            if (!this.cropped || this.disabled) {
                return;
            }

            setStyle(this.viewBoxImage, assign({
                width: width,
                height: height
            }, getTransforms(assign({
                translateX: -left,
                translateY: -top
            }, imageData))));
            forEach(this.previews, function (element) {
                var data = getData(element, DATA_PREVIEW);
                var originalWidth = data.width;
                var originalHeight = data.height;
                var newWidth = originalWidth;
                var newHeight = originalHeight;
                var ratio = 1;

                if (cropBoxWidth) {
                    ratio = originalWidth / cropBoxWidth;
                    newHeight = cropBoxHeight * ratio;
                }

                if (cropBoxHeight && newHeight > originalHeight) {
                    ratio = originalHeight / cropBoxHeight;
                    newWidth = cropBoxWidth * ratio;
                    newHeight = originalHeight;
                }

                setStyle(element, {
                    width: newWidth,
                    height: newHeight
                });
                setStyle(element.getElementsByTagName('img')[0], assign({
                    width: width * ratio,
                    height: height * ratio
                }, getTransforms(assign({
                    translateX: -left * ratio,
                    translateY: -top * ratio
                }, imageData))));
            });
        }
    };

    var events = {
        bind: function bind() {
            var element = this.element,
                options = this.options,
                cropper = this.cropper;

            if (isFunction(options.cropstart)) {
                addListener(element, EVENT_CROP_START, options.cropstart);
            }

            if (isFunction(options.cropmove)) {
                addListener(element, EVENT_CROP_MOVE, options.cropmove);
            }

            if (isFunction(options.cropend)) {
                addListener(element, EVENT_CROP_END, options.cropend);
            }

            if (isFunction(options.crop)) {
                addListener(element, EVENT_CROP, options.crop);
            }

            if (isFunction(options.zoom)) {
                addListener(element, EVENT_ZOOM, options.zoom);
            }

            addListener(cropper, EVENT_POINTER_DOWN, this.onCropStart = this.cropStart.bind(this));

            if (options.zoomable && options.zoomOnWheel) {
                addListener(cropper, EVENT_WHEEL, this.onWheel = this.wheel.bind(this), {
                    passive: false,
                    capture: true
                });
            }

            if (options.toggleDragModeOnDblclick) {
                addListener(cropper, EVENT_DBLCLICK, this.onDblclick = this.dblclick.bind(this));
            }

            addListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove = this.cropMove.bind(this));
            addListener(element.ownerDocument, EVENT_POINTER_UP, this.onCropEnd = this.cropEnd.bind(this));

            if (options.responsive) {
                addListener(window, EVENT_RESIZE, this.onResize = this.resize.bind(this));
            }
        },
        unbind: function unbind() {
            var element = this.element,
                options = this.options,
                cropper = this.cropper;

            if (isFunction(options.cropstart)) {
                removeListener(element, EVENT_CROP_START, options.cropstart);
            }

            if (isFunction(options.cropmove)) {
                removeListener(element, EVENT_CROP_MOVE, options.cropmove);
            }

            if (isFunction(options.cropend)) {
                removeListener(element, EVENT_CROP_END, options.cropend);
            }

            if (isFunction(options.crop)) {
                removeListener(element, EVENT_CROP, options.crop);
            }

            if (isFunction(options.zoom)) {
                removeListener(element, EVENT_ZOOM, options.zoom);
            }

            removeListener(cropper, EVENT_POINTER_DOWN, this.onCropStart);

            if (options.zoomable && options.zoomOnWheel) {
                removeListener(cropper, EVENT_WHEEL, this.onWheel, {
                    passive: false,
                    capture: true
                });
            }

            if (options.toggleDragModeOnDblclick) {
                removeListener(cropper, EVENT_DBLCLICK, this.onDblclick);
            }

            removeListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove);
            removeListener(element.ownerDocument, EVENT_POINTER_UP, this.onCropEnd);

            if (options.responsive) {
                removeListener(window, EVENT_RESIZE, this.onResize);
            }
        }
    };

    var handlers = {
        resize: function resize() {
            var options = this.options,
                container = this.container,
                containerData = this.containerData;
            var minContainerWidth = Number(options.minContainerWidth) || MIN_CONTAINER_WIDTH;
            var minContainerHeight = Number(options.minContainerHeight) || MIN_CONTAINER_HEIGHT;

            if (this.disabled || containerData.width <= minContainerWidth || containerData.height <= minContainerHeight) {
                return;
            }

            var ratio = container.offsetWidth / containerData.width; // Resize when width changed or height changed

            if (ratio !== 1 || container.offsetHeight !== containerData.height) {
                var canvasData;
                var cropBoxData;

                if (options.restore) {
                    canvasData = this.getCanvasData();
                    cropBoxData = this.getCropBoxData();
                }

                this.render();

                if (options.restore) {
                    this.setCanvasData(forEach(canvasData, function (n, i) {
                        canvasData[i] = n * ratio;
                    }));
                    this.setCropBoxData(forEach(cropBoxData, function (n, i) {
                        cropBoxData[i] = n * ratio;
                    }));
                }
            }
        },
        dblclick: function dblclick() {
            if (this.disabled || this.options.dragMode === DRAG_MODE_NONE) {
                return;
            }

            this.setDragMode(hasClass(this.dragBox, CLASS_CROP) ? DRAG_MODE_MOVE : DRAG_MODE_CROP);
        },
        wheel: function wheel(event) {
            var _this = this;

            var ratio = Number(this.options.wheelZoomRatio) || 0.1;
            var delta = 1;

            if (this.disabled) {
                return;
            }

            event.preventDefault(); // Limit wheel speed to prevent zoom too fast (#21)

            if (this.wheeling) {
                return;
            }

            this.wheeling = true;
            setTimeout(function () {
                _this.wheeling = false;
            }, 50);

            if (event.deltaY) {
                delta = event.deltaY > 0 ? 1 : -1;
            } else if (event.wheelDelta) {
                delta = -event.wheelDelta / 120;
            } else if (event.detail) {
                delta = event.detail > 0 ? 1 : -1;
            }

            this.zoom(-delta * ratio, event);
        },
        cropStart: function cropStart(event) {
            var buttons = event.buttons,
                button = event.button;

            if (this.disabled // Handle mouse event and pointer event and ignore touch event
                || (event.type === 'mousedown' || event.type === 'pointerdown' && event.pointerType === 'mouse') && ( // No primary button (Usually the left button)
                    isNumber(buttons) && buttons !== 1 || isNumber(button) && button !== 0 // Open context menu
                    || event.ctrlKey)) {
                return;
            }

            var options = this.options,
                pointers = this.pointers;
            var action;

            if (event.changedTouches) {
                // Handle touch event
                forEach(event.changedTouches, function (touch) {
                    pointers[touch.identifier] = getPointer(touch);
                });
            } else {
                // Handle mouse event and pointer event
                pointers[event.pointerId || 0] = getPointer(event);
            }

            if (Object.keys(pointers).length > 1 && options.zoomable && options.zoomOnTouch) {
                action = ACTION_ZOOM;
            } else {
                action = getData(event.target, DATA_ACTION);
            }

            if (!REGEXP_ACTIONS.test(action)) {
                return;
            }

            if (dispatchEvent(this.element, EVENT_CROP_START, {
                originalEvent: event,
                action: action
            }) === false) {
                return;
            } // This line is required for preventing page zooming in iOS browsers


            event.preventDefault();
            this.action = action;
            this.cropping = false;

            if (action === ACTION_CROP) {
                this.cropping = true;
                addClass(this.dragBox, CLASS_MODAL);
            }
        },
        cropMove: function cropMove(event) {
            var action = this.action;

            if (this.disabled || !action) {
                return;
            }

            var pointers = this.pointers;
            event.preventDefault();

            if (dispatchEvent(this.element, EVENT_CROP_MOVE, {
                originalEvent: event,
                action: action
            }) === false) {
                return;
            }

            if (event.changedTouches) {
                forEach(event.changedTouches, function (touch) {
                    // The first parameter should not be undefined (#432)
                    assign(pointers[touch.identifier] || {}, getPointer(touch, true));
                });
            } else {
                assign(pointers[event.pointerId || 0] || {}, getPointer(event, true));
            }

            this.change(event);
        },
        cropEnd: function cropEnd(event) {
            if (this.disabled) {
                return;
            }

            var action = this.action,
                pointers = this.pointers;

            if (event.changedTouches) {
                forEach(event.changedTouches, function (touch) {
                    delete pointers[touch.identifier];
                });
            } else {
                delete pointers[event.pointerId || 0];
            }

            if (!action) {
                return;
            }

            event.preventDefault();

            if (!Object.keys(pointers).length) {
                this.action = '';
            }

            if (this.cropping) {
                this.cropping = false;
                toggleClass(this.dragBox, CLASS_MODAL, this.cropped && this.options.modal);
            }

            dispatchEvent(this.element, EVENT_CROP_END, {
                originalEvent: event,
                action: action
            });
        }
    };

    var change = {
        change: function change(event) {
            var options = this.options,
                canvasData = this.canvasData,
                containerData = this.containerData,
                cropBoxData = this.cropBoxData,
                pointers = this.pointers;
            var action = this.action;
            var aspectRatio = options.aspectRatio;
            var left = cropBoxData.left,
                top = cropBoxData.top,
                width = cropBoxData.width,
                height = cropBoxData.height;
            var right = left + width;
            var bottom = top + height;
            var minLeft = 0;
            var minTop = 0;
            var maxWidth = containerData.width;
            var maxHeight = containerData.height;
            var renderable = true;
            var offset; // Locking aspect ratio in "free mode" by holding shift key

            if (!aspectRatio && event.shiftKey) {
                aspectRatio = width && height ? width / height : 1;
            }

            if (this.limited) {
                minLeft = cropBoxData.minLeft;
                minTop = cropBoxData.minTop;
                maxWidth = minLeft + Math.min(containerData.width, canvasData.width, canvasData.left + canvasData.width);
                maxHeight = minTop + Math.min(containerData.height, canvasData.height, canvasData.top + canvasData.height);
            }

            var pointer = pointers[Object.keys(pointers)[0]];
            var range = {
                x: pointer.endX - pointer.startX,
                y: pointer.endY - pointer.startY
            };

            var check = function check(side) {
                switch (side) {
                    case ACTION_EAST:
                        if (right + range.x > maxWidth) {
                            range.x = maxWidth - right;
                        }

                        break;

                    case ACTION_WEST:
                        if (left + range.x < minLeft) {
                            range.x = minLeft - left;
                        }

                        break;

                    case ACTION_NORTH:
                        if (top + range.y < minTop) {
                            range.y = minTop - top;
                        }

                        break;

                    case ACTION_SOUTH:
                        if (bottom + range.y > maxHeight) {
                            range.y = maxHeight - bottom;
                        }

                        break;

                    default:
                }
            };

            switch (action) {
                // Move crop box
                case ACTION_ALL:
                    left += range.x;
                    top += range.y;
                    break;
                // Resize crop box

                case ACTION_EAST:
                    if (range.x >= 0 && (right >= maxWidth || aspectRatio && (top <= minTop || bottom >= maxHeight))) {
                        renderable = false;
                        break;
                    }

                    check(ACTION_EAST);
                    width += range.x;

                    if (width < 0) {
                        action = ACTION_WEST;
                        width = -width;
                        left -= width;
                    }

                    if (aspectRatio) {
                        height = width / aspectRatio;
                        top += (cropBoxData.height - height) / 2;
                    }

                    break;

                case ACTION_NORTH:
                    if (range.y <= 0 && (top <= minTop || aspectRatio && (left <= minLeft || right >= maxWidth))) {
                        renderable = false;
                        break;
                    }

                    check(ACTION_NORTH);
                    height -= range.y;
                    top += range.y;

                    if (height < 0) {
                        action = ACTION_SOUTH;
                        height = -height;
                        top -= height;
                    }

                    if (aspectRatio) {
                        width = height * aspectRatio;
                        left += (cropBoxData.width - width) / 2;
                    }

                    break;

                case ACTION_WEST:
                    if (range.x <= 0 && (left <= minLeft || aspectRatio && (top <= minTop || bottom >= maxHeight))) {
                        renderable = false;
                        break;
                    }

                    check(ACTION_WEST);
                    width -= range.x;
                    left += range.x;

                    if (width < 0) {
                        action = ACTION_EAST;
                        width = -width;
                        left -= width;
                    }

                    if (aspectRatio) {
                        height = width / aspectRatio;
                        top += (cropBoxData.height - height) / 2;
                    }

                    break;

                case ACTION_SOUTH:
                    if (range.y >= 0 && (bottom >= maxHeight || aspectRatio && (left <= minLeft || right >= maxWidth))) {
                        renderable = false;
                        break;
                    }

                    check(ACTION_SOUTH);
                    height += range.y;

                    if (height < 0) {
                        action = ACTION_NORTH;
                        height = -height;
                        top -= height;
                    }

                    if (aspectRatio) {
                        width = height * aspectRatio;
                        left += (cropBoxData.width - width) / 2;
                    }

                    break;

                case ACTION_NORTH_EAST:
                    if (aspectRatio) {
                        if (range.y <= 0 && (top <= minTop || right >= maxWidth)) {
                            renderable = false;
                            break;
                        }

                        check(ACTION_NORTH);
                        height -= range.y;
                        top += range.y;
                        width = height * aspectRatio;
                    } else {
                        check(ACTION_NORTH);
                        check(ACTION_EAST);

                        if (range.x >= 0) {
                            if (right < maxWidth) {
                                width += range.x;
                            } else if (range.y <= 0 && top <= minTop) {
                                renderable = false;
                            }
                        } else {
                            width += range.x;
                        }

                        if (range.y <= 0) {
                            if (top > minTop) {
                                height -= range.y;
                                top += range.y;
                            }
                        } else {
                            height -= range.y;
                            top += range.y;
                        }
                    }

                    if (width < 0 && height < 0) {
                        action = ACTION_SOUTH_WEST;
                        height = -height;
                        width = -width;
                        top -= height;
                        left -= width;
                    } else if (width < 0) {
                        action = ACTION_NORTH_WEST;
                        width = -width;
                        left -= width;
                    } else if (height < 0) {
                        action = ACTION_SOUTH_EAST;
                        height = -height;
                        top -= height;
                    }

                    break;

                case ACTION_NORTH_WEST:
                    if (aspectRatio) {
                        if (range.y <= 0 && (top <= minTop || left <= minLeft)) {
                            renderable = false;
                            break;
                        }

                        check(ACTION_NORTH);
                        height -= range.y;
                        top += range.y;
                        width = height * aspectRatio;
                        left += cropBoxData.width - width;
                    } else {
                        check(ACTION_NORTH);
                        check(ACTION_WEST);

                        if (range.x <= 0) {
                            if (left > minLeft) {
                                width -= range.x;
                                left += range.x;
                            } else if (range.y <= 0 && top <= minTop) {
                                renderable = false;
                            }
                        } else {
                            width -= range.x;
                            left += range.x;
                        }

                        if (range.y <= 0) {
                            if (top > minTop) {
                                height -= range.y;
                                top += range.y;
                            }
                        } else {
                            height -= range.y;
                            top += range.y;
                        }
                    }

                    if (width < 0 && height < 0) {
                        action = ACTION_SOUTH_EAST;
                        height = -height;
                        width = -width;
                        top -= height;
                        left -= width;
                    } else if (width < 0) {
                        action = ACTION_NORTH_EAST;
                        width = -width;
                        left -= width;
                    } else if (height < 0) {
                        action = ACTION_SOUTH_WEST;
                        height = -height;
                        top -= height;
                    }

                    break;

                case ACTION_SOUTH_WEST:
                    if (aspectRatio) {
                        if (range.x <= 0 && (left <= minLeft || bottom >= maxHeight)) {
                            renderable = false;
                            break;
                        }

                        check(ACTION_WEST);
                        width -= range.x;
                        left += range.x;
                        height = width / aspectRatio;
                    } else {
                        check(ACTION_SOUTH);
                        check(ACTION_WEST);

                        if (range.x <= 0) {
                            if (left > minLeft) {
                                width -= range.x;
                                left += range.x;
                            } else if (range.y >= 0 && bottom >= maxHeight) {
                                renderable = false;
                            }
                        } else {
                            width -= range.x;
                            left += range.x;
                        }

                        if (range.y >= 0) {
                            if (bottom < maxHeight) {
                                height += range.y;
                            }
                        } else {
                            height += range.y;
                        }
                    }

                    if (width < 0 && height < 0) {
                        action = ACTION_NORTH_EAST;
                        height = -height;
                        width = -width;
                        top -= height;
                        left -= width;
                    } else if (width < 0) {
                        action = ACTION_SOUTH_EAST;
                        width = -width;
                        left -= width;
                    } else if (height < 0) {
                        action = ACTION_NORTH_WEST;
                        height = -height;
                        top -= height;
                    }

                    break;

                case ACTION_SOUTH_EAST:
                    if (aspectRatio) {
                        if (range.x >= 0 && (right >= maxWidth || bottom >= maxHeight)) {
                            renderable = false;
                            break;
                        }

                        check(ACTION_EAST);
                        width += range.x;
                        height = width / aspectRatio;
                    } else {
                        check(ACTION_SOUTH);
                        check(ACTION_EAST);

                        if (range.x >= 0) {
                            if (right < maxWidth) {
                                width += range.x;
                            } else if (range.y >= 0 && bottom >= maxHeight) {
                                renderable = false;
                            }
                        } else {
                            width += range.x;
                        }

                        if (range.y >= 0) {
                            if (bottom < maxHeight) {
                                height += range.y;
                            }
                        } else {
                            height += range.y;
                        }
                    }

                    if (width < 0 && height < 0) {
                        action = ACTION_NORTH_WEST;
                        height = -height;
                        width = -width;
                        top -= height;
                        left -= width;
                    } else if (width < 0) {
                        action = ACTION_SOUTH_WEST;
                        width = -width;
                        left -= width;
                    } else if (height < 0) {
                        action = ACTION_NORTH_EAST;
                        height = -height;
                        top -= height;
                    }

                    break;
                // Move canvas

                case ACTION_MOVE:
                    this.move(range.x, range.y);
                    renderable = false;
                    break;
                // Zoom canvas

                case ACTION_ZOOM:
                    this.zoom(getMaxZoomRatio(pointers), event);
                    renderable = false;
                    break;
                // Create crop box

                case ACTION_CROP:
                    if (!range.x || !range.y) {
                        renderable = false;
                        break;
                    }

                    offset = getOffset(this.cropper);
                    left = pointer.startX - offset.left;
                    top = pointer.startY - offset.top;
                    width = cropBoxData.minWidth;
                    height = cropBoxData.minHeight;

                    if (range.x > 0) {
                        action = range.y > 0 ? ACTION_SOUTH_EAST : ACTION_NORTH_EAST;
                    } else if (range.x < 0) {
                        left -= width;
                        action = range.y > 0 ? ACTION_SOUTH_WEST : ACTION_NORTH_WEST;
                    }

                    if (range.y < 0) {
                        top -= height;
                    } // Show the crop box if is hidden


                    if (!this.cropped) {
                        removeClass(this.cropBox, CLASS_HIDDEN);
                        this.cropped = true;

                        if (this.limited) {
                            this.limitCropBox(true, true);
                        }
                    }

                    break;

                default:
            }

            if (renderable) {
                cropBoxData.width = width;
                cropBoxData.height = height;
                cropBoxData.left = left;
                cropBoxData.top = top;
                this.action = action;
                this.renderCropBox();
            } // Override


            forEach(pointers, function (p) {
                p.startX = p.endX;
                p.startY = p.endY;
            });
        }
    };

    var methods = {
        // Show the crop box manually
        crop: function crop() {
            if (this.ready && !this.cropped && !this.disabled) {
                this.cropped = true;
                this.limitCropBox(true, true);

                if (this.options.modal) {
                    addClass(this.dragBox, CLASS_MODAL);
                }

                removeClass(this.cropBox, CLASS_HIDDEN);
                this.setCropBoxData(this.initialCropBoxData);
            }

            return this;
        },
        // Reset the image and crop box to their initial states
        reset: function reset() {
            if (this.ready && !this.disabled) {
                this.imageData = assign({}, this.initialImageData);
                this.canvasData = assign({}, this.initialCanvasData);
                this.cropBoxData = assign({}, this.initialCropBoxData);
                this.renderCanvas();

                if (this.cropped) {
                    this.renderCropBox();
                }
            }

            return this;
        },
        // Clear the crop box
        clear: function clear() {
            if (this.cropped && !this.disabled) {
                assign(this.cropBoxData, {
                    left: 0,
                    top: 0,
                    width: 0,
                    height: 0
                });
                this.cropped = false;
                this.renderCropBox();
                this.limitCanvas(true, true); // Render canvas after crop box rendered

                this.renderCanvas();
                removeClass(this.dragBox, CLASS_MODAL);
                addClass(this.cropBox, CLASS_HIDDEN);
            }

            return this;
        },

        /**
         * Replace the image's src and rebuild the cropper
         * @param {string} url - The new URL.
         * @param {boolean} [hasSameSize] - Indicate if the new image has the same size as the old one.
         * @returns {Cropper} this
         */
        replace: function replace(url) {
            var hasSameSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

            if (!this.disabled && url) {
                if (this.isImg) {
                    this.element.src = url;
                }

                if (hasSameSize) {
                    this.url = url;
                    this.image.src = url;

                    if (this.ready) {
                        this.viewBoxImage.src = url;
                        forEach(this.previews, function (element) {
                            element.getElementsByTagName('img')[0].src = url;
                        });
                    }
                } else {
                    if (this.isImg) {
                        this.replaced = true;
                    }

                    this.options.data = null;
                    this.uncreate();
                    this.load(url);
                }
            }

            return this;
        },
        // Enable (unfreeze) the cropper
        enable: function enable() {
            if (this.ready && this.disabled) {
                this.disabled = false;
                removeClass(this.cropper, CLASS_DISABLED);
            }

            return this;
        },
        // Disable (freeze) the cropper
        disable: function disable() {
            if (this.ready && !this.disabled) {
                this.disabled = true;
                addClass(this.cropper, CLASS_DISABLED);
            }

            return this;
        },

        /**
         * Destroy the cropper and remove the instance from the image
         * @returns {Cropper} this
         */
        destroy: function destroy() {
            var element = this.element;

            if (!element[NAMESPACE]) {
                return this;
            }

            element[NAMESPACE] = undefined;

            if (this.isImg && this.replaced) {
                element.src = this.originalUrl;
            }

            this.uncreate();
            return this;
        },

        /**
         * Move the canvas with relative offsets
         * @param {number} offsetX - The relative offset distance on the x-axis.
         * @param {number} [offsetY=offsetX] - The relative offset distance on the y-axis.
         * @returns {Cropper} this
         */
        move: function move(offsetX) {
            var offsetY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : offsetX;
            var _this$canvasData = this.canvasData,
                left = _this$canvasData.left,
                top = _this$canvasData.top;
            return this.moveTo(isUndefined(offsetX) ? offsetX : left + Number(offsetX), isUndefined(offsetY) ? offsetY : top + Number(offsetY));
        },

        /**
         * Move the canvas to an absolute point
         * @param {number} x - The x-axis coordinate.
         * @param {number} [y=x] - The y-axis coordinate.
         * @returns {Cropper} this
         */
        moveTo: function moveTo(x) {
            var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : x;
            var canvasData = this.canvasData;
            var changed = false;
            x = Number(x);
            y = Number(y);

            if (this.ready && !this.disabled && this.options.movable) {
                if (isNumber(x)) {
                    canvasData.left = x;
                    changed = true;
                }

                if (isNumber(y)) {
                    canvasData.top = y;
                    changed = true;
                }

                if (changed) {
                    this.renderCanvas(true);
                }
            }

            return this;
        },

        /**
         * Zoom the canvas with a relative ratio
         * @param {number} ratio - The target ratio.
         * @param {Event} _originalEvent - The original event if any.
         * @returns {Cropper} this
         */
        zoom: function zoom(ratio, _originalEvent) {
            var canvasData = this.canvasData;
            ratio = Number(ratio);

            if (ratio < 0) {
                ratio = 1 / (1 - ratio);
            } else {
                ratio = 1 + ratio;
            }

            return this.zoomTo(canvasData.width * ratio / canvasData.naturalWidth, null, _originalEvent);
        },

        /**
         * Zoom the canvas to an absolute ratio
         * @param {number} ratio - The target ratio.
         * @param {Object} pivot - The zoom pivot point coordinate.
         * @param {Event} _originalEvent - The original event if any.
         * @returns {Cropper} this
         */
        zoomTo: function zoomTo(ratio, pivot, _originalEvent) {
            var options = this.options,
                canvasData = this.canvasData;
            var width = canvasData.width,
                height = canvasData.height,
                naturalWidth = canvasData.naturalWidth,
                naturalHeight = canvasData.naturalHeight;
            ratio = Number(ratio);

            if (ratio >= 0 && this.ready && !this.disabled && options.zoomable) {
                var newWidth = naturalWidth * ratio;
                var newHeight = naturalHeight * ratio;

                if (dispatchEvent(this.element, EVENT_ZOOM, {
                    ratio: ratio,
                    oldRatio: width / naturalWidth,
                    originalEvent: _originalEvent
                }) === false) {
                    return this;
                }

                if (_originalEvent) {
                    var pointers = this.pointers;
                    var offset = getOffset(this.cropper);
                    var center = pointers && Object.keys(pointers).length ? getPointersCenter(pointers) : {
                        pageX: _originalEvent.pageX,
                        pageY: _originalEvent.pageY
                    }; // Zoom from the triggering point of the event

                    canvasData.left -= (newWidth - width) * ((center.pageX - offset.left - canvasData.left) / width);
                    canvasData.top -= (newHeight - height) * ((center.pageY - offset.top - canvasData.top) / height);
                } else if (isPlainObject(pivot) && isNumber(pivot.x) && isNumber(pivot.y)) {
                    canvasData.left -= (newWidth - width) * ((pivot.x - canvasData.left) / width);
                    canvasData.top -= (newHeight - height) * ((pivot.y - canvasData.top) / height);
                } else {
                    // Zoom from the center of the canvas
                    canvasData.left -= (newWidth - width) / 2;
                    canvasData.top -= (newHeight - height) / 2;
                }

                canvasData.width = newWidth;
                canvasData.height = newHeight;
                this.renderCanvas(true);
            }

            return this;
        },

        /**
         * Rotate the canvas with a relative degree
         * @param {number} degree - The rotate degree.
         * @returns {Cropper} this
         */
        rotate: function rotate(degree) {
            return this.rotateTo((this.imageData.rotate || 0) + Number(degree));
        },

        /**
         * Rotate the canvas to an absolute degree
         * @param {number} degree - The rotate degree.
         * @returns {Cropper} this
         */
        rotateTo: function rotateTo(degree) {
            degree = Number(degree);

            if (isNumber(degree) && this.ready && !this.disabled && this.options.rotatable) {
                this.imageData.rotate = degree % 360;
                this.renderCanvas(true, true);
            }

            return this;
        },

        /**
         * Scale the image on the x-axis.
         * @param {number} scaleX - The scale ratio on the x-axis.
         * @returns {Cropper} this
         */
        scaleX: function scaleX(_scaleX) {
            var scaleY = this.imageData.scaleY;
            return this.scale(_scaleX, isNumber(scaleY) ? scaleY : 1);
        },

        /**
         * Scale the image on the y-axis.
         * @param {number} scaleY - The scale ratio on the y-axis.
         * @returns {Cropper} this
         */
        scaleY: function scaleY(_scaleY) {
            var scaleX = this.imageData.scaleX;
            return this.scale(isNumber(scaleX) ? scaleX : 1, _scaleY);
        },

        /**
         * Scale the image
         * @param {number} scaleX - The scale ratio on the x-axis.
         * @param {number} [scaleY=scaleX] - The scale ratio on the y-axis.
         * @returns {Cropper} this
         */
        scale: function scale(scaleX) {
            var scaleY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : scaleX;
            var imageData = this.imageData;
            var transformed = false;
            scaleX = Number(scaleX);
            scaleY = Number(scaleY);

            if (this.ready && !this.disabled && this.options.scalable) {
                if (isNumber(scaleX)) {
                    imageData.scaleX = scaleX;
                    transformed = true;
                }

                if (isNumber(scaleY)) {
                    imageData.scaleY = scaleY;
                    transformed = true;
                }

                if (transformed) {
                    this.renderCanvas(true, true);
                }
            }

            return this;
        },

        /**
         * Get the cropped area position and size data (base on the original image)
         * @param {boolean} [rounded=false] - Indicate if round the data values or not.
         * @returns {Object} The result cropped data.
         */
        getData: function getData() {
            var rounded = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
            var options = this.options,
                imageData = this.imageData,
                canvasData = this.canvasData,
                cropBoxData = this.cropBoxData;
            var data;

            if (this.ready && this.cropped) {
                data = {
                    x: cropBoxData.left - canvasData.left,
                    y: cropBoxData.top - canvasData.top,
                    width: cropBoxData.width,
                    height: cropBoxData.height
                };
                var ratio = imageData.width / imageData.naturalWidth;
                forEach(data, function (n, i) {
                    data[i] = n / ratio;
                });

                if (rounded) {
                    // In case rounding off leads to extra 1px in right or bottom border
                    // we should round the top-left corner and the dimension (#343).
                    var bottom = Math.round(data.y + data.height);
                    var right = Math.round(data.x + data.width);
                    data.x = Math.round(data.x);
                    data.y = Math.round(data.y);
                    data.width = right - data.x;
                    data.height = bottom - data.y;
                }
            } else {
                data = {
                    x: 0,
                    y: 0,
                    width: 0,
                    height: 0
                };
            }

            if (options.rotatable) {
                data.rotate = imageData.rotate || 0;
            }

            if (options.scalable) {
                data.scaleX = imageData.scaleX || 1;
                data.scaleY = imageData.scaleY || 1;
            }

            return data;
        },

        /**
         * Set the cropped area position and size with new data
         * @param {Object} data - The new data.
         * @returns {Cropper} this
         */
        setData: function setData(data) {
            var options = this.options,
                imageData = this.imageData,
                canvasData = this.canvasData;
            var cropBoxData = {};

            if (this.ready && !this.disabled && isPlainObject(data)) {
                var transformed = false;

                if (options.rotatable) {
                    if (isNumber(data.rotate) && data.rotate !== imageData.rotate) {
                        imageData.rotate = data.rotate;
                        transformed = true;
                    }
                }

                if (options.scalable) {
                    if (isNumber(data.scaleX) && data.scaleX !== imageData.scaleX) {
                        imageData.scaleX = data.scaleX;
                        transformed = true;
                    }

                    if (isNumber(data.scaleY) && data.scaleY !== imageData.scaleY) {
                        imageData.scaleY = data.scaleY;
                        transformed = true;
                    }
                }

                if (transformed) {
                    this.renderCanvas(true, true);
                }

                var ratio = imageData.width / imageData.naturalWidth;

                if (isNumber(data.x)) {
                    cropBoxData.left = data.x * ratio + canvasData.left;
                }

                if (isNumber(data.y)) {
                    cropBoxData.top = data.y * ratio + canvasData.top;
                }

                if (isNumber(data.width)) {
                    cropBoxData.width = data.width * ratio;
                }

                if (isNumber(data.height)) {
                    cropBoxData.height = data.height * ratio;
                }

                this.setCropBoxData(cropBoxData);
            }

            return this;
        },

        /**
         * Get the container size data.
         * @returns {Object} The result container data.
         */
        getContainerData: function getContainerData() {
            return this.ready ? assign({}, this.containerData) : {};
        },

        /**
         * Get the image position and size data.
         * @returns {Object} The result image data.
         */
        getImageData: function getImageData() {
            return this.sized ? assign({}, this.imageData) : {};
        },

        /**
         * Get the canvas position and size data.
         * @returns {Object} The result canvas data.
         */
        getCanvasData: function getCanvasData() {
            var canvasData = this.canvasData;
            var data = {};

            if (this.ready) {
                forEach(['left', 'top', 'width', 'height', 'naturalWidth', 'naturalHeight'], function (n) {
                    data[n] = canvasData[n];
                });
            }

            return data;
        },

        /**
         * Set the canvas position and size with new data.
         * @param {Object} data - The new canvas data.
         * @returns {Cropper} this
         */
        setCanvasData: function setCanvasData(data) {
            var canvasData = this.canvasData;
            var aspectRatio = canvasData.aspectRatio;

            if (this.ready && !this.disabled && isPlainObject(data)) {
                if (isNumber(data.left)) {
                    canvasData.left = data.left;
                }

                if (isNumber(data.top)) {
                    canvasData.top = data.top;
                }

                if (isNumber(data.width)) {
                    canvasData.width = data.width;
                    canvasData.height = data.width / aspectRatio;
                } else if (isNumber(data.height)) {
                    canvasData.height = data.height;
                    canvasData.width = data.height * aspectRatio;
                }

                this.renderCanvas(true);
            }

            return this;
        },

        /**
         * Get the crop box position and size data.
         * @returns {Object} The result crop box data.
         */
        getCropBoxData: function getCropBoxData() {
            var cropBoxData = this.cropBoxData;
            var data;

            if (this.ready && this.cropped) {
                data = {
                    left: cropBoxData.left,
                    top: cropBoxData.top,
                    width: cropBoxData.width,
                    height: cropBoxData.height
                };
            }

            return data || {};
        },

        /**
         * Set the crop box position and size with new data.
         * @param {Object} data - The new crop box data.
         * @returns {Cropper} this
         */
        setCropBoxData: function setCropBoxData(data) {
            var cropBoxData = this.cropBoxData;
            var aspectRatio = this.options.aspectRatio;
            var widthChanged;
            var heightChanged;

            if (this.ready && this.cropped && !this.disabled && isPlainObject(data)) {
                if (isNumber(data.left)) {
                    cropBoxData.left = data.left;
                }

                if (isNumber(data.top)) {
                    cropBoxData.top = data.top;
                }

                if (isNumber(data.width) && data.width !== cropBoxData.width) {
                    widthChanged = true;
                    cropBoxData.width = data.width;
                }

                if (isNumber(data.height) && data.height !== cropBoxData.height) {
                    heightChanged = true;
                    cropBoxData.height = data.height;
                }

                if (aspectRatio) {
                    if (widthChanged) {
                        cropBoxData.height = cropBoxData.width / aspectRatio;
                    } else if (heightChanged) {
                        cropBoxData.width = cropBoxData.height * aspectRatio;
                    }
                }

                this.renderCropBox();
            }

            return this;
        },

        /**
         * Get a canvas drawn the cropped image.
         * @param {Object} [options={}] - The config options.
         * @returns {HTMLCanvasElement} - The result canvas.
         */
        getCroppedCanvas: function getCroppedCanvas() {
            var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

            if (!this.ready || !window.HTMLCanvasElement) {
                return null;
            }

            var canvasData = this.canvasData;
            var source = getSourceCanvas(this.image, this.imageData, canvasData, options); // Returns the source canvas if it is not cropped.

            if (!this.cropped) {
                return source;
            }

            var _this$getData = this.getData(),
                initialX = _this$getData.x,
                initialY = _this$getData.y,
                initialWidth = _this$getData.width,
                initialHeight = _this$getData.height;

            var ratio = source.width / Math.floor(canvasData.naturalWidth);

            if (ratio !== 1) {
                initialX *= ratio;
                initialY *= ratio;
                initialWidth *= ratio;
                initialHeight *= ratio;
            }

            var aspectRatio = initialWidth / initialHeight;
            var maxSizes = getAdjustedSizes({
                aspectRatio: aspectRatio,
                width: options.maxWidth || Infinity,
                height: options.maxHeight || Infinity
            });
            var minSizes = getAdjustedSizes({
                aspectRatio: aspectRatio,
                width: options.minWidth || 0,
                height: options.minHeight || 0
            }, 'cover');

            var _getAdjustedSizes = getAdjustedSizes({
                aspectRatio: aspectRatio,
                width: options.width || (ratio !== 1 ? source.width : initialWidth),
                height: options.height || (ratio !== 1 ? source.height : initialHeight)
            }),
                width = _getAdjustedSizes.width,
                height = _getAdjustedSizes.height;

            width = Math.min(maxSizes.width, Math.max(minSizes.width, width));
            height = Math.min(maxSizes.height, Math.max(minSizes.height, height));
            var canvas = document.createElement('canvas');
            var context = canvas.getContext('2d');
            canvas.width = normalizeDecimalNumber(width);
            canvas.height = normalizeDecimalNumber(height);
            context.fillStyle = options.fillColor || 'transparent';
            context.fillRect(0, 0, width, height);
            var _options$imageSmoothi = options.imageSmoothingEnabled,
                imageSmoothingEnabled = _options$imageSmoothi === void 0 ? true : _options$imageSmoothi,
                imageSmoothingQuality = options.imageSmoothingQuality;
            context.imageSmoothingEnabled = imageSmoothingEnabled;

            if (imageSmoothingQuality) {
                context.imageSmoothingQuality = imageSmoothingQuality;
            } // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D.drawImage


            var sourceWidth = source.width;
            var sourceHeight = source.height; // Source canvas parameters

            var srcX = initialX;
            var srcY = initialY;
            var srcWidth;
            var srcHeight; // Destination canvas parameters

            var dstX;
            var dstY;
            var dstWidth;
            var dstHeight;

            if (srcX <= -initialWidth || srcX > sourceWidth) {
                srcX = 0;
                srcWidth = 0;
                dstX = 0;
                dstWidth = 0;
            } else if (srcX <= 0) {
                dstX = -srcX;
                srcX = 0;
                srcWidth = Math.min(sourceWidth, initialWidth + srcX);
                dstWidth = srcWidth;
            } else if (srcX <= sourceWidth) {
                dstX = 0;
                srcWidth = Math.min(initialWidth, sourceWidth - srcX);
                dstWidth = srcWidth;
            }

            if (srcWidth <= 0 || srcY <= -initialHeight || srcY > sourceHeight) {
                srcY = 0;
                srcHeight = 0;
                dstY = 0;
                dstHeight = 0;
            } else if (srcY <= 0) {
                dstY = -srcY;
                srcY = 0;
                srcHeight = Math.min(sourceHeight, initialHeight + srcY);
                dstHeight = srcHeight;
            } else if (srcY <= sourceHeight) {
                dstY = 0;
                srcHeight = Math.min(initialHeight, sourceHeight - srcY);
                dstHeight = srcHeight;
            }

            var params = [srcX, srcY, srcWidth, srcHeight]; // Avoid "IndexSizeError"

            if (dstWidth > 0 && dstHeight > 0) {
                var scale = width / initialWidth;
                params.push(dstX * scale, dstY * scale, dstWidth * scale, dstHeight * scale);
            } // All the numerical parameters should be integer for `drawImage`
            // https://github.com/fengyuanchen/cropper/issues/476


            context.drawImage.apply(context, [source].concat(_toConsumableArray(params.map(function (param) {
                return Math.floor(normalizeDecimalNumber(param));
            }))));
            return canvas;
        },

        /**
         * Change the aspect ratio of the crop box.
         * @param {number} aspectRatio - The new aspect ratio.
         * @returns {Cropper} this
         */
        setAspectRatio: function setAspectRatio(aspectRatio) {
            var options = this.options;

            if (!this.disabled && !isUndefined(aspectRatio)) {
                // 0 -> NaN
                options.aspectRatio = Math.max(0, aspectRatio) || NaN;

                if (this.ready) {
                    this.initCropBox();

                    if (this.cropped) {
                        this.renderCropBox();
                    }
                }
            }

            return this;
        },

        /**
         * Change the drag mode.
         * @param {string} mode - The new drag mode.
         * @returns {Cropper} this
         */
        setDragMode: function setDragMode(mode) {
            var options = this.options,
                dragBox = this.dragBox,
                face = this.face;

            if (this.ready && !this.disabled) {
                var croppable = mode === DRAG_MODE_CROP;
                var movable = options.movable && mode === DRAG_MODE_MOVE;
                mode = croppable || movable ? mode : DRAG_MODE_NONE;
                options.dragMode = mode;
                setData(dragBox, DATA_ACTION, mode);
                toggleClass(dragBox, CLASS_CROP, croppable);
                toggleClass(dragBox, CLASS_MOVE, movable);

                if (!options.cropBoxMovable) {
                    // Sync drag mode to crop box when it is not movable
                    setData(face, DATA_ACTION, mode);
                    toggleClass(face, CLASS_CROP, croppable);
                    toggleClass(face, CLASS_MOVE, movable);
                }
            }

            return this;
        }
    };

    var AnotherCropper = WINDOW.Cropper;

    var Cropper =
        /*#__PURE__*/
        function () {
            /**
             * Create a new Cropper.
             * @param {Element} element - The target element for cropping.
             * @param {Object} [options={}] - The configuration options.
             */
            function Cropper(element) {
                var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

                _classCallCheck(this, Cropper);

                if (!element || !REGEXP_TAG_NAME.test(element.tagName)) {
                    throw new Error('The first argument is required and must be an <img> or <canvas> element.');
                }

                this.element = element;
                this.options = assign({}, DEFAULTS, isPlainObject(options) && options);
                this.cropped = false;
                this.disabled = false;
                this.pointers = {};
                this.ready = false;
                this.reloading = false;
                this.replaced = false;
                this.sized = false;
                this.sizing = false;
                this.init();
            }

            _createClass(Cropper, [{
                key: "init",
                value: function init() {
                    var element = this.element;
                    var tagName = element.tagName.toLowerCase();
                    var url;

                    if (element[NAMESPACE]) {
                        return;
                    }

                    element[NAMESPACE] = this;

                    if (tagName === 'img') {
                        this.isImg = true; // e.g.: "img/picture.jpg"

                        url = element.getAttribute('src') || '';
                        this.originalUrl = url; // Stop when it's a blank image

                        if (!url) {
                            return;
                        } // e.g.: "http://example.com/img/picture.jpg"


                        url = element.src;
                    } else if (tagName === 'canvas' && window.HTMLCanvasElement) {
                        url = element.toDataURL();
                    }

                    this.load(url);
                }
            }, {
                key: "load",
                value: function load(url) {
                    var _this = this;

                    if (!url) {
                        return;
                    }

                    this.url = url;
                    this.imageData = {};
                    var element = this.element,
                        options = this.options;

                    if (!options.rotatable && !options.scalable) {
                        options.checkOrientation = false;
                    } // Only IE10+ supports Typed Arrays


                    if (!options.checkOrientation || !window.ArrayBuffer) {
                        this.clone();
                        return;
                    } // Detect the mime type of the image directly if it is a Data URL


                    if (REGEXP_DATA_URL.test(url)) {
                        // Read ArrayBuffer from Data URL of JPEG images directly for better performance
                        if (REGEXP_DATA_URL_JPEG.test(url)) {
                            this.read(dataURLToArrayBuffer(url));
                        } else {
                            // Only a JPEG image may contains Exif Orientation information,
                            // the rest types of Data URLs are not necessary to check orientation at all.
                            this.clone();
                        }

                        return;
                    } // 1. Detect the mime type of the image by a XMLHttpRequest.
                    // 2. Load the image as ArrayBuffer for reading orientation if its a JPEG image.


                    var xhr = new XMLHttpRequest();
                    var clone = this.clone.bind(this);
                    this.reloading = true;
                    this.xhr = xhr; // 1. Cross origin requests are only supported for protocol schemes:
                    // http, https, data, chrome, chrome-extension.
                    // 2. Access to XMLHttpRequest from a Data URL will be blocked by CORS policy
                    // in some browsers as IE11 and Safari.

                    xhr.onabort = clone;
                    xhr.onerror = clone;
                    xhr.ontimeout = clone;

                    xhr.onprogress = function () {
                        // Abort the request directly if it not a JPEG image for better performance
                        if (xhr.getResponseHeader('content-type') !== MIME_TYPE_JPEG) {
                            xhr.abort();
                        }
                    };

                    xhr.onload = function () {
                        _this.read(xhr.response);
                    };

                    xhr.onloadend = function () {
                        _this.reloading = false;
                        _this.xhr = null;
                    }; // Bust cache when there is a "crossOrigin" property to avoid browser cache error


                    if (options.checkCrossOrigin && isCrossOriginURL(url) && element.crossOrigin) {
                        url = addTimestamp(url);
                    }

                    xhr.open('GET', url);
                    xhr.responseType = 'arraybuffer';
                    xhr.withCredentials = element.crossOrigin === 'use-credentials';
                    xhr.send();
                }
            }, {
                key: "read",
                value: function read(arrayBuffer) {
                    var options = this.options,
                        imageData = this.imageData; // Reset the orientation value to its default value 1
                    // as some iOS browsers will render image with its orientation

                    var orientation = resetAndGetOrientation(arrayBuffer);
                    var rotate = 0;
                    var scaleX = 1;
                    var scaleY = 1;

                    if (orientation > 1) {
                        // Generate a new URL which has the default orientation value
                        this.url = arrayBufferToDataURL(arrayBuffer, MIME_TYPE_JPEG);

                        var _parseOrientation = parseOrientation(orientation);

                        rotate = _parseOrientation.rotate;
                        scaleX = _parseOrientation.scaleX;
                        scaleY = _parseOrientation.scaleY;
                    }

                    if (options.rotatable) {
                        imageData.rotate = rotate;
                    }

                    if (options.scalable) {
                        imageData.scaleX = scaleX;
                        imageData.scaleY = scaleY;
                    }

                    this.clone();
                }
            }, {
                key: "clone",
                value: function clone() {
                    var element = this.element,
                        url = this.url;
                    var crossOrigin = element.crossOrigin;
                    var crossOriginUrl = url;

                    if (this.options.checkCrossOrigin && isCrossOriginURL(url)) {
                        if (!crossOrigin) {
                            crossOrigin = 'anonymous';
                        } // Bust cache when there is not a "crossOrigin" property (#519)


                        crossOriginUrl = addTimestamp(url);
                    }

                    this.crossOrigin = crossOrigin;
                    this.crossOriginUrl = crossOriginUrl;
                    var image = document.createElement('img');

                    if (crossOrigin) {
                        image.crossOrigin = crossOrigin;
                    }

                    image.src = crossOriginUrl || url;
                    image.alt = element.alt || 'The image to crop';
                    this.image = image;
                    image.onload = this.start.bind(this);
                    image.onerror = this.stop.bind(this);
                    addClass(image, CLASS_HIDE);
                    element.parentNode.insertBefore(image, element.nextSibling);
                }
            }, {
                key: "start",
                value: function start() {
                    var _this2 = this;

                    var image = this.image;
                    image.onload = null;
                    image.onerror = null;
                    this.sizing = true; // Match all browsers that use WebKit as the layout engine in iOS devices,
                    // such as Safari for iOS, Chrome for iOS, and in-app browsers.

                    var isIOSWebKit = WINDOW.navigator && /(?:iPad|iPhone|iPod).*?AppleWebKit/i.test(WINDOW.navigator.userAgent);

                    var done = function done(naturalWidth, naturalHeight) {
                        assign(_this2.imageData, {
                            naturalWidth: naturalWidth,
                            naturalHeight: naturalHeight,
                            aspectRatio: naturalWidth / naturalHeight
                        });
                        _this2.sizing = false;
                        _this2.sized = true;

                        _this2.build();
                    }; // Most modern browsers (excepts iOS WebKit)


                    if (image.naturalWidth && !isIOSWebKit) {
                        done(image.naturalWidth, image.naturalHeight);
                        return;
                    }

                    var sizingImage = document.createElement('img');
                    var body = document.body || document.documentElement;
                    this.sizingImage = sizingImage;

                    sizingImage.onload = function () {
                        done(sizingImage.width, sizingImage.height);

                        if (!isIOSWebKit) {
                            body.removeChild(sizingImage);
                        }
                    };

                    sizingImage.src = image.src; // iOS WebKit will convert the image automatically
                    // with its orientation once append it into DOM (#279)

                    if (!isIOSWebKit) {
                        sizingImage.style.cssText = 'left:0;' + 'max-height:none!important;' + 'max-width:none!important;' + 'min-height:0!important;' + 'min-width:0!important;' + 'opacity:0;' + 'position:absolute;' + 'top:0;' + 'z-index:-1;';
                        body.appendChild(sizingImage);
                    }
                }
            }, {
                key: "stop",
                value: function stop() {
                    var image = this.image;
                    image.onload = null;
                    image.onerror = null;
                    image.parentNode.removeChild(image);
                    this.image = null;
                }
            }, {
                key: "build",
                value: function build() {
                    if (!this.sized || this.ready) {
                        return;
                    }

                    var element = this.element,
                        options = this.options,
                        image = this.image; // Create cropper elements

                    var container = element.parentNode;
                    var template = document.createElement('div');
                    template.innerHTML = TEMPLATE;
                    var cropper = template.querySelector(".".concat(NAMESPACE, "-container"));
                    var canvas = cropper.querySelector(".".concat(NAMESPACE, "-canvas"));
                    var dragBox = cropper.querySelector(".".concat(NAMESPACE, "-drag-box"));
                    var cropBox = cropper.querySelector(".".concat(NAMESPACE, "-crop-box"));
                    var face = cropBox.querySelector(".".concat(NAMESPACE, "-face"));
                    this.container = container;
                    this.cropper = cropper;
                    this.canvas = canvas;
                    this.dragBox = dragBox;
                    this.cropBox = cropBox;
                    this.viewBox = cropper.querySelector(".".concat(NAMESPACE, "-view-box"));
                    this.face = face;
                    canvas.appendChild(image); // Hide the original image

                    addClass(element, CLASS_HIDDEN); // Inserts the cropper after to the current image

                    container.insertBefore(cropper, element.nextSibling); // Show the image if is hidden

                    if (!this.isImg) {
                        removeClass(image, CLASS_HIDE);
                    }

                    this.initPreview();
                    this.bind();
                    options.initialAspectRatio = Math.max(0, options.initialAspectRatio) || NaN;
                    options.aspectRatio = Math.max(0, options.aspectRatio) || NaN;
                    options.viewMode = Math.max(0, Math.min(3, Math.round(options.viewMode))) || 0;
                    addClass(cropBox, CLASS_HIDDEN);

                    if (!options.guides) {
                        addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-dashed")), CLASS_HIDDEN);
                    }

                    if (!options.center) {
                        addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-center")), CLASS_HIDDEN);
                    }

                    if (options.background) {
                        addClass(cropper, "".concat(NAMESPACE, "-bg"));
                    }

                    if (!options.highlight) {
                        addClass(face, CLASS_INVISIBLE);
                    }

                    if (options.cropBoxMovable) {
                        addClass(face, CLASS_MOVE);
                        setData(face, DATA_ACTION, ACTION_ALL);
                    }

                    if (!options.cropBoxResizable) {
                        addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-line")), CLASS_HIDDEN);
                        addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-point")), CLASS_HIDDEN);
                    }

                    this.render();
                    this.ready = true;
                    this.setDragMode(options.dragMode);

                    if (options.autoCrop) {
                        this.crop();
                    }

                    this.setData(options.data);

                    if (isFunction(options.ready)) {
                        addListener(element, EVENT_READY, options.ready, {
                            once: true
                        });
                    }

                    dispatchEvent(element, EVENT_READY);
                }
            }, {
                key: "unbuild",
                value: function unbuild() {
                    if (!this.ready) {
                        return;
                    }

                    this.ready = false;
                    this.unbind();
                    this.resetPreview();
                    this.cropper.parentNode.removeChild(this.cropper);
                    removeClass(this.element, CLASS_HIDDEN);
                }
            }, {
                key: "uncreate",
                value: function uncreate() {
                    if (this.ready) {
                        this.unbuild();
                        this.ready = false;
                        this.cropped = false;
                    } else if (this.sizing) {
                        this.sizingImage.onload = null;
                        this.sizing = false;
                        this.sized = false;
                    } else if (this.reloading) {
                        this.xhr.onabort = null;
                        this.xhr.abort();
                    } else if (this.image) {
                        this.stop();
                    }
                }
                /**
                 * Get the no conflict cropper class.
                 * @returns {Cropper} The cropper class.
                 */

            }], [{
                key: "noConflict",
                value: function noConflict() {
                    window.Cropper = AnotherCropper;
                    return Cropper;
                }
                /**
                 * Change the default options.
                 * @param {Object} options - The new default options.
                 */

            }, {
                key: "setDefaults",
                value: function setDefaults(options) {
                    assign(DEFAULTS, isPlainObject(options) && options);
                }
            }]);

            return Cropper;
        }();

    assign(Cropper.prototype, render, preview, events, handlers, change, methods);

    return Cropper;

}));
;
//! moment.js

; (function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
        typeof define === 'function' && define.amd ? define(factory) :
            global.moment = factory()
}(this, (function () {
    'use strict';

    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 isObjectEmpty(obj) {
        if (Object.getOwnPropertyNames) {
            return (Object.getOwnPropertyNames(obj).length === 0);
        } else {
            var k;
            for (k in obj) {
                if (obj.hasOwnProperty(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;
        for (i = 0; i < arr.length; ++i) {
            res.push(fn(arr[i], i));
        }
        return res;
    }

    function hasOwnProp(a, b) {
        return Object.prototype.hasOwnProperty.call(a, b);
    }

    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,
            invalidMonth: null,
            invalidFormat: false,
            userInvalidated: false,
            iso: false,
            parsedDateParts: [],
            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);
            var len = t.length >>> 0;

            for (var i = 0; i < len; i++) {
                if (i in t && fun.call(this, t[i], i, t)) {
                    return true;
                }
            }

            return false;
        };
    }

    function isValid(m) {
        if (m._isValid == null) {
            var flags = getParsingFlags(m);
            var parsedParts = some.call(flags.parsedDateParts, function (i) {
                return i != null;
            });
            var isNowValid = !isNaN(m._d.getTime()) &&
                flags.overflow < 0 &&
                !flags.empty &&
                !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 = [];

    function copyConfig(to, from) {
        var i, prop, val;

        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 (momentProperties.length > 0) {
            for (i = 0; i < momentProperties.length; i++) {
                prop = momentProperties[i];
                val = from[prop];
                if (!isUndefined(val)) {
                    to[prop] = val;
                }
            }
        }

        return to;
    }

    var updateInProgress = false;

    // 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 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;
    }

    // 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 ((dontConvert && array1[i] !== array2[i]) ||
                (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
                diffs++;
            }
        }
        return diffs + lengthDiff;
    }

    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 = [];
                var arg;
                for (var i = 0; i < arguments.length; i++) {
                    arg = '';
                    if (typeof arguments[i] === 'object') {
                        arg += '\n[' + i + '] ';
                        for (var key in arguments[0]) {
                            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 input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
    }

    function set(config) {
        var prop, i;
        for (i in config) {
            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;
    }

    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.replace(/MMMM|MM|DD|dddd/g, function (val) {
            return val.slice(1);
        });

        return this._longDateFormat[key];
    }

    var defaultInvalidDate = 'Invalid date';

    function invalidDate() {
        return this._invalidDate;
    }

    var defaultOrdinal = '%d';
    var 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',
        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 = {};

    function addUnitAlias(unit, shorthand) {
        var lowerCase = unit.toLowerCase();
        aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
    }

    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 = {};

    function addUnitPriority(unit, priority) {
        priorities[unit] = priority;
    }

    function getPrioritizedUnits(unitsObj) {
        var units = [];
        for (var u in unitsObj) {
            units.push({ unit: u, priority: priorities[u] });
        }
        units.sort(function (a, b) {
            return a.priority - b.priority;
        });
        return units;
    }

    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?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;

    var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;

    var formatFunctions = {};

    var 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 match1 = /\d/;            //       0 - 9
    var match2 = /\d\d/;          //      00 - 99
    var match3 = /\d{3}/;         //     000 - 999
    var match4 = /\d{4}/;         //    0000 - 9999
    var match6 = /[+-]?\d{6}/;    // -999999 - 999999
    var match1to2 = /\d\d?/;         //       0 - 99
    var match3to4 = /\d\d\d\d?/;     //     999 - 9999
    var match5to6 = /\d\d\d\d\d\d?/; //   99999 - 999999
    var match1to3 = /\d{1,3}/;       //       0 - 999
    var match1to4 = /\d{1,4}/;       //       0 - 9999
    var match1to6 = /[+-]?\d{1,6}/;  // -999999 - 999999

    var matchUnsigned = /\d+/;           //       0 - inf
    var matchSigned = /[+-]?\d+/;      //    -inf - inf

    var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
    var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z

    var 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
    var 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;

    var 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, '\\$&');
    }

    var tokens = {};

    function addParseToken(token, callback) {
        var i, func = callback;
        if (typeof token === 'string') {
            token = [token];
        }
        if (isNumber(callback)) {
            func = function (input, array) {
                array[callback] = toInt(input);
            };
        }
        for (i = 0; i < token.length; 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);
        }
    }

    var YEAR = 0;
    var MONTH = 1;
    var DATE = 2;
    var HOUR = 3;
    var MINUTE = 4;
    var SECOND = 5;
    var MILLISECOND = 6;
    var WEEK = 7;
    var WEEKDAY = 8;

    // FORMATTING

    addFormatToken('Y', 0, 0, function () {
        var y = this.year();
        return y <= 9999 ? '' + y : '+' + 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');

    // ALIASES

    addUnitAlias('year', 'y');

    // PRIORITIES

    addUnitPriority('year', 1);

    // 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;
    }

    function isLeapYear(year) {
        return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
    }

    // 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) {
        return mom.isValid() ?
            mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
    }

    function set$1(mom, unit, value) {
        if (mom.isValid() && !isNaN(value)) {
            if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) {
                mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()));
            }
            else {
                mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
            }
        }
    }

    // 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);
            for (var i = 0; i < prioritized.length; 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);
    });

    // ALIASES

    addUnitAlias('month', 'M');

    // PRIORITY

    addUnitPriority('month', 8);

    // PARSING

    addRegexToken('M', match1to2);
    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 MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
    var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
    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()];
    }

    var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
    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) {
        var dayOfMonth;

        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;
                }
            }
        }

        dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
        mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
        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());
    }

    var defaultMonthsShortRegex = matchWord;
    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;
        }
    }

    var defaultMonthsRegex = matchWord;
    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;
        for (i = 0; i < 12; i++) {
            // make the regex if we don't have it already
            mom = createUTC([2000, i]);
            shortPieces.push(this.monthsShort(mom, ''));
            longPieces.push(this.months(mom, ''));
            mixedPieces.push(this.months(mom, ''));
            mixedPieces.push(this.monthsShort(mom, ''));
        }
        // 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);
        for (i = 0; i < 12; i++) {
            shortPieces[i] = regexEscape(shortPieces[i]);
            longPieces[i] = regexEscape(longPieces[i]);
        }
        for (i = 0; i < 24; i++) {
            mixedPieces[i] = regexEscape(mixedPieces[i]);
        }

        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 = new Date(y, m, d, h, M, s, ms);

        // the date constructor remaps years 0-99 to 1900-1999
        if (y < 100 && y >= 0 && isFinite(date.getFullYear())) {
            date.setFullYear(y);
        }
        return date;
    }

    function createUTCDate(y) {
        var date = new Date(Date.UTC.apply(null, arguments));

        // the Date.UTC function remaps years 0-99 to 1900-1999
        if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) {
            date.setUTCFullYear(y);
        }
        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');

    // ALIASES

    addUnitAlias('week', 'w');
    addUnitAlias('isoWeek', 'W');

    // PRIORITIES

    addUnitPriority('week', 5);
    addUnitPriority('isoWeek', 5);

    // PARSING

    addRegexToken('w', match1to2);
    addRegexToken('ww', match1to2, match2);
    addRegexToken('W', match1to2);
    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 1st 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');

    // ALIASES

    addUnitAlias('day', 'd');
    addUnitAlias('weekday', 'e');
    addUnitAlias('isoWeekday', 'E');

    // PRIORITY
    addUnitPriority('day', 11);
    addUnitPriority('weekday', 11);
    addUnitPriority('isoWeekday', 11);

    // 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

    var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
    function localeWeekdays(m, format) {
        if (!m) {
            return isArray(this._weekdays) ? this._weekdays :
                this._weekdays['standalone'];
        }
        return isArray(this._weekdays) ? this._weekdays[m.day()] :
            this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()];
    }

    var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
    function localeWeekdaysShort(m) {
        return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
    }

    var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
    function localeWeekdaysMin(m) {
        return (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 = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
        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;
        }
    }

    var defaultWeekdaysRegex = matchWord;
    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;
        }
    }

    var defaultWeekdaysShortRegex = matchWord;
    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;
        }
    }

    var defaultWeekdaysMinRegex = matchWord;
    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 = this.weekdaysMin(mom, '');
            shortp = this.weekdaysShort(mom, '');
            longp = 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);
        for (i = 0; i < 7; i++) {
            shortPieces[i] = regexEscape(shortPieces[i]);
            longPieces[i] = regexEscape(longPieces[i]);
            mixedPieces[i] = regexEscape(mixedPieces[i]);
        }

        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);

    // ALIASES

    addUnitAlias('hour', 'h');

    // PRIORITY
    addUnitPriority('hour', 13);

    // PARSING

    function matchMeridiem(isStrict, locale) {
        return locale._meridiemParse;
    }

    addRegexToken('a', matchMeridiem);
    addRegexToken('A', matchMeridiem);
    addRegexToken('H', match1to2);
    addRegexToken('h', match1to2);
    addRegexToken('k', match1to2);
    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;
        var 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;
        var 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;
    function localeMeridiem(hours, minutes, isLower) {
        if (hours > 11) {
            return isLower ? 'pm' : 'PM';
        } else {
            return isLower ? 'am' : 'AM';
        }
    }


    // MOMENTS

    // 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.
    var getSetHour = makeGetSet('Hours', true);

    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 = {};
    var localeFamilies = {};
    var globalLocale;

    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 && compareArrays(split, next, true) >= j - 1) {
                    //the next array item is better than a shallower substring of this one
                    break;
                }
                j--;
            }
            i++;
        }
        return globalLocale;
    }

    function loadLocale(name) {
        var oldLocale = null;
        // TODO: Find a better way to register and load all the locales in Node
        if (!locales[name] && (typeof module !== 'undefined') &&
            module && module.exports) {
            try {
                oldLocale = globalLocale._abbr;
                var aliasedRequire = require;
                aliasedRequire('./locale/' + name);
                getSetGlobalLocale(oldLocale);
            } catch (e) { }
        }
        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;
            // MERGE
            tmpLocale = loadLocale(name);
            if (tmpLocale != null) {
                parentConfig = tmpLocale._config;
            }
            config = mergeConfigs(parentConfig, config);
            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;
                } 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;
        var 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;
    }

    // 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;

        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;

            var 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 begining of week
                weekday = w.e + dow;
                if (w.e < 0 || w.e > 6) {
                    weekdayOverflow = true;
                }
            } else {
                // default to begining 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;
        }
    }

    // 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)?)?$/;
    var 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)?)?$/;

    var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;

    var 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}/],
        // YYYYMM is NOT allowed by the standard
        ['GGGG[W]WWE', /\d{4}W\d{3}/],
        ['GGGG[W]WW', /\d{4}W\d{2}/, false],
        ['YYYYDDD', /\d{7}/]
    ];

    // iso time formats and regexes
    var 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/]
    ];

    var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;

    // date from iso format
    function configFromISO(config) {
        var i, l,
            string = config._i,
            match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
            allowTime, dateFormat, timeFormat, tzFormat;

        if (match) {
            getParsingFlags(config).iso = true;

            for (i = 0, l = isoDates.length; 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 = isoTimes.length; 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;
        }
    }

    // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
    var 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}))$/;

    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 indepentent 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;
    }

    var 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
    };

    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);
            var 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));
        if (match) {
            var 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 iso format or fallback
    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;
        }

        // 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 and will be removed in an upcoming major release. Please refer to ' +
        'http://momentjs.com/guides/#/warnings/js-date/ for more info.',
        function (config) {
            config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
        }
    );

    // 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;

        tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];

        for (i = 0; i < tokens.length; i++) {
            token = tokens[i];
            parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
            // console.log('token', token, 'parsedInput', parsedInput,
            //         'regex', getParseRegexForToken(token, config));
            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);

        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;

        if (config._f.length === 0) {
            getParsingFlags(config).invalidFormat = true;
            config._d = new Date(NaN);
            return;
        }

        for (i = 0; i < config._f.length; i++) {
            currentScore = 0;
            tempConfig = copyConfig({}, config);
            if (config._useUTC != null) {
                tempConfig._useUTC = config._useUTC;
            }
            tempConfig._f = config._f[i];
            configFromStringAndFormat(tempConfig);

            if (!isValid(tempConfig)) {
                continue;
            }

            // 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 (scoreToBeat == null || currentScore < scoreToBeat) {
                scoreToBeat = currentScore;
                bestMoment = tempConfig;
            }
        }

        extend(config, bestMoment || tempConfig);
    }

    function configFromObject(config) {
        if (config._d) {
            return;
        }

        var i = normalizeObjectUnits(config._i);
        config._a = map([i.year, i.month, i.day || i.date, 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 (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();
            }
        }
    );

    var 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) {
        for (var key in m) {
            if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
                return false;
            }
        }

        var unitHasDecimal = false;
        for (var i = 0; i < ordering.length; ++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 || 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);
        }
    }

    // FORMATTING

    function offset(token, separator) {
        addFormatToken(token, 0, 0, function () {
            var offset = this.utcOffset();
            var 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);

        if (matches === null) {
            return null;
        }

        var chunk = matches[matches.length - 1] || [];
        var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
        var 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() / 15) * 15;
    }

    // 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 = {};

        copyConfig(c, this);
        c = prepareConfig(c);

        if (c._a) {
            var 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
    var 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)) {
            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 : (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;
        }

        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 = { milliseconds: 0, months: 0 };

        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;
            }

            val = typeof val === 'string' ? +val : val;
            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');
    var subtract = createAdder(-1, 'subtract');

    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) {
        // 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';

        var 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(!isUndefined(units) ? 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(!isUndefined(units) ? 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) {
        inclusivity = inclusivity || '()';
        return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) &&
            (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, 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) {
        // 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;
        var 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';
        var zone = '';
        if (!this.isLocal()) {
            func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
            zone = 'Z';
        }
        var prefix = '[' + func + '("]';
        var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY';
        var datetime = '-MM-DD[T]HH:mm:ss.SSS';
        var 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;
    }

    function startOf(units) {
        units = normalizeUnits(units);
        // the following switch intentionally omits break keywords
        // to utilize falling through the cases.
        switch (units) {
            case 'year':
                this.month(0);
            /* falls through */
            case 'quarter':
            case 'month':
                this.date(1);
            /* falls through */
            case 'week':
            case 'isoWeek':
            case 'day':
            case 'date':
                this.hours(0);
            /* falls through */
            case 'hour':
                this.minutes(0);
            /* falls through */
            case 'minute':
                this.seconds(0);
            /* falls through */
            case 'second':
                this.milliseconds(0);
        }

        // weeks are a special case
        if (units === 'week') {
            this.weekday(0);
        }
        if (units === 'isoWeek') {
            this.isoWeekday(1);
        }

        // quarters are also special
        if (units === 'quarter') {
            this.month(Math.floor(this.month() / 3) * 3);
        }

        return this;
    }

    function endOf(units) {
        units = normalizeUnits(units);
        if (units === undefined || units === 'millisecond') {
            return this;
        }

        // 'date' is an alias for 'day', so it should be considered as such.
        if (units === 'date') {
            units = 'day';
        }

        return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
    }

    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
        };
    }

    // 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

    addUnitAlias('weekYear', 'gg');
    addUnitAlias('isoWeekYear', 'GG');

    // PRIORITY

    addUnitPriority('weekYear', 1);
    addUnitPriority('isoWeekYear', 1);


    // 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.doy);
    }

    function getSetISOWeekYear(input) {
        return getSetWeekYearHelper.call(this,
            input, this.isoWeek(), this.isoWeekday(), 1, 4);
    }

    function getISOWeeksInYear() {
        return weeksInYear(this.year(), 1, 4);
    }

    function getWeeksInYear() {
        var weekInfo = this.localeData()._week;
        return weeksInYear(this.year(), 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');

    // ALIASES

    addUnitAlias('quarter', 'Q');

    // PRIORITY

    addUnitPriority('quarter', 7);

    // 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');

    // ALIASES

    addUnitAlias('date', 'D');

    // PRIORITY
    addUnitPriority('date', 9);

    // PARSING

    addRegexToken('D', match1to2);
    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');

    // ALIASES

    addUnitAlias('dayOfYear', 'DDD');

    // PRIORITY
    addUnitPriority('dayOfYear', 4);

    // 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');

    // ALIASES

    addUnitAlias('minute', 'm');

    // PRIORITY

    addUnitPriority('minute', 14);

    // PARSING

    addRegexToken('m', match1to2);
    addRegexToken('mm', match1to2, match2);
    addParseToken(['m', 'mm'], MINUTE);

    // MOMENTS

    var getSetMinute = makeGetSet('Minutes', false);

    // FORMATTING

    addFormatToken('s', ['ss', 2], 0, 'second');

    // ALIASES

    addUnitAlias('second', 's');

    // PRIORITY

    addUnitPriority('second', 15);

    // PARSING

    addRegexToken('s', match1to2);
    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;
    });


    // ALIASES

    addUnitAlias('millisecond', 'ms');

    // PRIORITY

    addUnitPriority('millisecond', 16);

    // PARSING

    addRegexToken('S', match1to3, match1);
    addRegexToken('SS', match1to3, match2);
    addRegexToken('SSS', match1to3, match3);

    var token;
    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);
    }
    // MOMENTS

    var 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;
    proto.toJSON = toJSON;
    proto.toString = toString;
    proto.unix = unix;
    proto.valueOf = valueOf;
    proto.creationData = creationData;
    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.isoWeeksInYear = getISOWeeksInYear;
    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.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();
        var 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;
        var 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;

        if (index != null) {
            return get$1(format, (index + shift) % 7, field, 'day');
        }

        var i;
        var out = [];
        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', {
        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;
        var days = this._days;
        var months = this._months;
        var data = this._data;
        var 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;
        var months;
        var milliseconds = this._milliseconds;

        units = normalizeUnits(units);

        if (units === 'month' || units === 'year') {
            days = this._days + milliseconds / 864e5;
            months = this._months + daysToMonths(days);
            return units === 'month' ? months : 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);
            }
        }
    }

    // TODO: Use this.as('ms')?
    function valueOf$1() {
        if (!this.isValid()) {
            return NaN;
        }
        return (
            this._milliseconds +
            this._days * 864e5 +
            (this._months % 12) * 2592e6 +
            toInt(this._months / 12) * 31536e6
        );
    }

    function makeAs(alias) {
        return function () {
            return this.as(alias);
        };
    }

    var asMilliseconds = makeAs('ms');
    var asSeconds = makeAs('s');
    var asMinutes = makeAs('m');
    var asHours = makeAs('h');
    var asDays = makeAs('d');
    var asWeeks = makeAs('w');
    var asMonths = makeAs('M');
    var asYears = makeAs('y');

    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');
    var seconds = makeGetter('seconds');
    var minutes = makeGetter('minutes');
    var hours = makeGetter('hours');
    var days = makeGetter('days');
    var months = makeGetter('months');
    var years = makeGetter('years');

    function weeks() {
        return absFloor(this.days() / 7);
    }

    var round = Math.round;
    var 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
        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, locale) {
        var duration = createDuration(posNegDuration).abs();
        var seconds = round(duration.as('s'));
        var minutes = round(duration.as('m'));
        var hours = round(duration.as('h'));
        var days = round(duration.as('d'));
        var months = round(duration.as('M'));
        var years = round(duration.as('y'));

        var 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] ||
            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(withSuffix) {
        if (!this.isValid()) {
            return this.localeData().invalidDate();
        }

        var locale = this.localeData();
        var output = relativeTime$1(this, !withSuffix, 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;
        var days = abs$1(this._days);
        var months = abs$1(this._months);
        var minutes, hours, years;

        // 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
        var Y = years;
        var M = months;
        var D = days;
        var h = hours;
        var m = minutes;
        var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
        var total = this.asSeconds();

        if (!total) {
            // this is the same as C#'s (Noda) and python (isodate)...
            // but not other JS (goog.date)
            return 'P0D';
        }

        var totalSign = total < 0 ? '-' : '';
        var ymSign = sign(this._months) !== sign(total) ? '-' : '';
        var daysSign = sign(this._days) !== sign(total) ? '-' : '';
        var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';

        return totalSign + 'P' +
            (Y ? ymSign + Y + 'Y' : '') +
            (M ? ymSign + M + 'M' : '') +
            (D ? daysSign + D + 'D' : '') +
            ((h || m || s) ? 'T' : '') +
            (h ? hmsSign + h + 'H' : '') +
            (m ? hmsSign + m + 'M' : '') +
            (s ? 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.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;

    // Side effect imports

    // 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, 10) * 1000);
    });
    addParseToken('x', function (input, array, config) {
        config._d = new Date(toInt(input));
    });

    // Side effect imports


    hooks.version = '2.22.2';

    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: 'YYYY-[W]WW',                             // <input type="week" />
        MONTH: 'YYYY-MM'                                // <input type="month" />
    };

    return hooks;

})));;
; (function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
        typeof define === 'function' && define.amd ? define(factory) :
            global.moment = factory()
}(this, (function () {
    'use strict';

    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 isObjectEmpty(obj) {
        if (Object.getOwnPropertyNames) {
            return (Object.getOwnPropertyNames(obj).length === 0);
        } else {
            var k;
            for (k in obj) {
                if (obj.hasOwnProperty(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;
        for (i = 0; i < arr.length; ++i) {
            res.push(fn(arr[i], i));
        }
        return res;
    }

    function hasOwnProp(a, b) {
        return Object.prototype.hasOwnProperty.call(a, b);
    }

    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,
            invalidMonth: null,
            invalidFormat: false,
            userInvalidated: false,
            iso: false,
            parsedDateParts: [],
            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);
            var len = t.length >>> 0;

            for (var i = 0; i < len; i++) {
                if (i in t && fun.call(this, t[i], i, t)) {
                    return true;
                }
            }

            return false;
        };
    }

    function isValid(m) {
        if (m._isValid == null) {
            var flags = getParsingFlags(m);
            var parsedParts = some.call(flags.parsedDateParts, function (i) {
                return i != null;
            });
            var isNowValid = !isNaN(m._d.getTime()) &&
                flags.overflow < 0 &&
                !flags.empty &&
                !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 = [];

    function copyConfig(to, from) {
        var i, prop, val;

        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 (momentProperties.length > 0) {
            for (i = 0; i < momentProperties.length; i++) {
                prop = momentProperties[i];
                val = from[prop];
                if (!isUndefined(val)) {
                    to[prop] = val;
                }
            }
        }

        return to;
    }

    var updateInProgress = false;

    // 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 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;
    }

    // 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 ((dontConvert && array1[i] !== array2[i]) ||
                (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
                diffs++;
            }
        }
        return diffs + lengthDiff;
    }

    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 = [];
                var arg;
                for (var i = 0; i < arguments.length; i++) {
                    arg = '';
                    if (typeof arguments[i] === 'object') {
                        arg += '\n[' + i + '] ';
                        for (var key in arguments[0]) {
                            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 input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
    }

    function set(config) {
        var prop, i;
        for (i in config) {
            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;
    }

    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.replace(/MMMM|MM|DD|dddd/g, function (val) {
            return val.slice(1);
        });

        return this._longDateFormat[key];
    }

    var defaultInvalidDate = 'Invalid date';

    function invalidDate() {
        return this._invalidDate;
    }

    var defaultOrdinal = '%d';
    var 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',
        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 = {};

    function addUnitAlias(unit, shorthand) {
        var lowerCase = unit.toLowerCase();
        aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
    }

    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 = {};

    function addUnitPriority(unit, priority) {
        priorities[unit] = priority;
    }

    function getPrioritizedUnits(unitsObj) {
        var units = [];
        for (var u in unitsObj) {
            units.push({ unit: u, priority: priorities[u] });
        }
        units.sort(function (a, b) {
            return a.priority - b.priority;
        });
        return units;
    }

    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?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;

    var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;

    var formatFunctions = {};

    var 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 match1 = /\d/;            //       0 - 9
    var match2 = /\d\d/;          //      00 - 99
    var match3 = /\d{3}/;         //     000 - 999
    var match4 = /\d{4}/;         //    0000 - 9999
    var match6 = /[+-]?\d{6}/;    // -999999 - 999999
    var match1to2 = /\d\d?/;         //       0 - 99
    var match3to4 = /\d\d\d\d?/;     //     999 - 9999
    var match5to6 = /\d\d\d\d\d\d?/; //   99999 - 999999
    var match1to3 = /\d{1,3}/;       //       0 - 999
    var match1to4 = /\d{1,4}/;       //       0 - 9999
    var match1to6 = /[+-]?\d{1,6}/;  // -999999 - 999999

    var matchUnsigned = /\d+/;           //       0 - inf
    var matchSigned = /[+-]?\d+/;      //    -inf - inf

    var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
    var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z

    var 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
    var 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;

    var 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, '\\$&');
    }

    var tokens = {};

    function addParseToken(token, callback) {
        var i, func = callback;
        if (typeof token === 'string') {
            token = [token];
        }
        if (isNumber(callback)) {
            func = function (input, array) {
                array[callback] = toInt(input);
            };
        }
        for (i = 0; i < token.length; 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);
        }
    }

    var YEAR = 0;
    var MONTH = 1;
    var DATE = 2;
    var HOUR = 3;
    var MINUTE = 4;
    var SECOND = 5;
    var MILLISECOND = 6;
    var WEEK = 7;
    var WEEKDAY = 8;

    // FORMATTING

    addFormatToken('Y', 0, 0, function () {
        var y = this.year();
        return y <= 9999 ? '' + y : '+' + 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');

    // ALIASES

    addUnitAlias('year', 'y');

    // PRIORITIES

    addUnitPriority('year', 1);

    // 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;
    }

    function isLeapYear(year) {
        return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
    }

    // 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) {
        return mom.isValid() ?
            mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
    }

    function set$1(mom, unit, value) {
        if (mom.isValid() && !isNaN(value)) {
            if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) {
                mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()));
            }
            else {
                mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
            }
        }
    }

    // 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);
            for (var i = 0; i < prioritized.length; 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);
    });

    // ALIASES

    addUnitAlias('month', 'M');

    // PRIORITY

    addUnitPriority('month', 8);

    // PARSING

    addRegexToken('M', match1to2);
    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 MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
    var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
    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()];
    }

    var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
    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) {
        var dayOfMonth;

        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;
                }
            }
        }

        dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
        mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
        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());
    }

    var defaultMonthsShortRegex = matchWord;
    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;
        }
    }

    var defaultMonthsRegex = matchWord;
    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;
        for (i = 0; i < 12; i++) {
            // make the regex if we don't have it already
            mom = createUTC([2000, i]);
            shortPieces.push(this.monthsShort(mom, ''));
            longPieces.push(this.months(mom, ''));
            mixedPieces.push(this.months(mom, ''));
            mixedPieces.push(this.monthsShort(mom, ''));
        }
        // 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);
        for (i = 0; i < 12; i++) {
            shortPieces[i] = regexEscape(shortPieces[i]);
            longPieces[i] = regexEscape(longPieces[i]);
        }
        for (i = 0; i < 24; i++) {
            mixedPieces[i] = regexEscape(mixedPieces[i]);
        }

        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 = new Date(y, m, d, h, M, s, ms);

        // the date constructor remaps years 0-99 to 1900-1999
        if (y < 100 && y >= 0 && isFinite(date.getFullYear())) {
            date.setFullYear(y);
        }
        return date;
    }

    function createUTCDate(y) {
        var date = new Date(Date.UTC.apply(null, arguments));

        // the Date.UTC function remaps years 0-99 to 1900-1999
        if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) {
            date.setUTCFullYear(y);
        }
        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');

    // ALIASES

    addUnitAlias('week', 'w');
    addUnitAlias('isoWeek', 'W');

    // PRIORITIES

    addUnitPriority('week', 5);
    addUnitPriority('isoWeek', 5);

    // PARSING

    addRegexToken('w', match1to2);
    addRegexToken('ww', match1to2, match2);
    addRegexToken('W', match1to2);
    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 1st 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');

    // ALIASES

    addUnitAlias('day', 'd');
    addUnitAlias('weekday', 'e');
    addUnitAlias('isoWeekday', 'E');

    // PRIORITY
    addUnitPriority('day', 11);
    addUnitPriority('weekday', 11);
    addUnitPriority('isoWeekday', 11);

    // 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

    var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
    function localeWeekdays(m, format) {
        if (!m) {
            return isArray(this._weekdays) ? this._weekdays :
                this._weekdays['standalone'];
        }
        return isArray(this._weekdays) ? this._weekdays[m.day()] :
            this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()];
    }

    var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
    function localeWeekdaysShort(m) {
        return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
    }

    var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
    function localeWeekdaysMin(m) {
        return (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 = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
        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;
        }
    }

    var defaultWeekdaysRegex = matchWord;
    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;
        }
    }

    var defaultWeekdaysShortRegex = matchWord;
    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;
        }
    }

    var defaultWeekdaysMinRegex = matchWord;
    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 = this.weekdaysMin(mom, '');
            shortp = this.weekdaysShort(mom, '');
            longp = 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);
        for (i = 0; i < 7; i++) {
            shortPieces[i] = regexEscape(shortPieces[i]);
            longPieces[i] = regexEscape(longPieces[i]);
            mixedPieces[i] = regexEscape(mixedPieces[i]);
        }

        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);

    // ALIASES

    addUnitAlias('hour', 'h');

    // PRIORITY
    addUnitPriority('hour', 13);

    // PARSING

    function matchMeridiem(isStrict, locale) {
        return locale._meridiemParse;
    }

    addRegexToken('a', matchMeridiem);
    addRegexToken('A', matchMeridiem);
    addRegexToken('H', match1to2);
    addRegexToken('h', match1to2);
    addRegexToken('k', match1to2);
    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;
        var 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;
        var 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;
    function localeMeridiem(hours, minutes, isLower) {
        if (hours > 11) {
            return isLower ? 'pm' : 'PM';
        } else {
            return isLower ? 'am' : 'AM';
        }
    }


    // MOMENTS

    // 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.
    var getSetHour = makeGetSet('Hours', true);

    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 = {};
    var localeFamilies = {};
    var globalLocale;

    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 && compareArrays(split, next, true) >= j - 1) {
                    //the next array item is better than a shallower substring of this one
                    break;
                }
                j--;
            }
            i++;
        }
        return globalLocale;
    }

    function loadLocale(name) {
        var oldLocale = null;
        // TODO: Find a better way to register and load all the locales in Node
        if (!locales[name] && (typeof module !== 'undefined') &&
            module && module.exports) {
            try {
                oldLocale = globalLocale._abbr;
                var aliasedRequire = require;
                aliasedRequire('./locale/' + name);
                getSetGlobalLocale(oldLocale);
            } catch (e) { }
        }
        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;
            // MERGE
            tmpLocale = loadLocale(name);
            if (tmpLocale != null) {
                parentConfig = tmpLocale._config;
            }
            config = mergeConfigs(parentConfig, config);
            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;
                } 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;
        var 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;
    }

    // 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;

        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;

            var 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 begining of week
                weekday = w.e + dow;
                if (w.e < 0 || w.e > 6) {
                    weekdayOverflow = true;
                }
            } else {
                // default to begining 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;
        }
    }

    // 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)?)?$/;
    var 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)?)?$/;

    var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;

    var 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}/],
        // YYYYMM is NOT allowed by the standard
        ['GGGG[W]WWE', /\d{4}W\d{3}/],
        ['GGGG[W]WW', /\d{4}W\d{2}/, false],
        ['YYYYDDD', /\d{7}/]
    ];

    // iso time formats and regexes
    var 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/]
    ];

    var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;

    // date from iso format
    function configFromISO(config) {
        var i, l,
            string = config._i,
            match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
            allowTime, dateFormat, timeFormat, tzFormat;

        if (match) {
            getParsingFlags(config).iso = true;

            for (i = 0, l = isoDates.length; 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 = isoTimes.length; 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;
        }
    }

    // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
    var 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}))$/;

    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 indepentent 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;
    }

    var 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
    };

    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);
            var 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));
        if (match) {
            var 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 iso format or fallback
    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;
        }

        // 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 and will be removed in an upcoming major release. Please refer to ' +
        'http://momentjs.com/guides/#/warnings/js-date/ for more info.',
        function (config) {
            config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
        }
    );

    // 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;

        tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];

        for (i = 0; i < tokens.length; i++) {
            token = tokens[i];
            parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
            // console.log('token', token, 'parsedInput', parsedInput,
            //         'regex', getParseRegexForToken(token, config));
            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);

        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;

        if (config._f.length === 0) {
            getParsingFlags(config).invalidFormat = true;
            config._d = new Date(NaN);
            return;
        }

        for (i = 0; i < config._f.length; i++) {
            currentScore = 0;
            tempConfig = copyConfig({}, config);
            if (config._useUTC != null) {
                tempConfig._useUTC = config._useUTC;
            }
            tempConfig._f = config._f[i];
            configFromStringAndFormat(tempConfig);

            if (!isValid(tempConfig)) {
                continue;
            }

            // 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 (scoreToBeat == null || currentScore < scoreToBeat) {
                scoreToBeat = currentScore;
                bestMoment = tempConfig;
            }
        }

        extend(config, bestMoment || tempConfig);
    }

    function configFromObject(config) {
        if (config._d) {
            return;
        }

        var i = normalizeObjectUnits(config._i);
        config._a = map([i.year, i.month, i.day || i.date, 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 (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();
            }
        }
    );

    var 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) {
        for (var key in m) {
            if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
                return false;
            }
        }

        var unitHasDecimal = false;
        for (var i = 0; i < ordering.length; ++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 || 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);
        }
    }

    // FORMATTING

    function offset(token, separator) {
        addFormatToken(token, 0, 0, function () {
            var offset = this.utcOffset();
            var 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);

        if (matches === null) {
            return null;
        }

        var chunk = matches[matches.length - 1] || [];
        var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
        var 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() / 15) * 15;
    }

    // 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 = {};

        copyConfig(c, this);
        c = prepareConfig(c);

        if (c._a) {
            var 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
    var 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)) {
            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 : (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;
        }

        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 = { milliseconds: 0, months: 0 };

        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;
            }

            val = typeof val === 'string' ? +val : val;
            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');
    var subtract = createAdder(-1, 'subtract');

    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) {
        // 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';

        var 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(!isUndefined(units) ? 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(!isUndefined(units) ? 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) {
        inclusivity = inclusivity || '()';
        return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) &&
            (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, 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) {
        // 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;
        var 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';
        var zone = '';
        if (!this.isLocal()) {
            func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
            zone = 'Z';
        }
        var prefix = '[' + func + '("]';
        var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY';
        var datetime = '-MM-DD[T]HH:mm:ss.SSS';
        var 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;
    }

    function startOf(units) {
        units = normalizeUnits(units);
        // the following switch intentionally omits break keywords
        // to utilize falling through the cases.
        switch (units) {
            case 'year':
                this.month(0);
            /* falls through */
            case 'quarter':
            case 'month':
                this.date(1);
            /* falls through */
            case 'week':
            case 'isoWeek':
            case 'day':
            case 'date':
                this.hours(0);
            /* falls through */
            case 'hour':
                this.minutes(0);
            /* falls through */
            case 'minute':
                this.seconds(0);
            /* falls through */
            case 'second':
                this.milliseconds(0);
        }

        // weeks are a special case
        if (units === 'week') {
            this.weekday(0);
        }
        if (units === 'isoWeek') {
            this.isoWeekday(1);
        }

        // quarters are also special
        if (units === 'quarter') {
            this.month(Math.floor(this.month() / 3) * 3);
        }

        return this;
    }

    function endOf(units) {
        units = normalizeUnits(units);
        if (units === undefined || units === 'millisecond') {
            return this;
        }

        // 'date' is an alias for 'day', so it should be considered as such.
        if (units === 'date') {
            units = 'day';
        }

        return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
    }

    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
        };
    }

    // 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

    addUnitAlias('weekYear', 'gg');
    addUnitAlias('isoWeekYear', 'GG');

    // PRIORITY

    addUnitPriority('weekYear', 1);
    addUnitPriority('isoWeekYear', 1);


    // 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.doy);
    }

    function getSetISOWeekYear(input) {
        return getSetWeekYearHelper.call(this,
            input, this.isoWeek(), this.isoWeekday(), 1, 4);
    }

    function getISOWeeksInYear() {
        return weeksInYear(this.year(), 1, 4);
    }

    function getWeeksInYear() {
        var weekInfo = this.localeData()._week;
        return weeksInYear(this.year(), 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');

    // ALIASES

    addUnitAlias('quarter', 'Q');

    // PRIORITY

    addUnitPriority('quarter', 7);

    // 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');

    // ALIASES

    addUnitAlias('date', 'D');

    // PRIORITY
    addUnitPriority('date', 9);

    // PARSING

    addRegexToken('D', match1to2);
    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');

    // ALIASES

    addUnitAlias('dayOfYear', 'DDD');

    // PRIORITY
    addUnitPriority('dayOfYear', 4);

    // 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');

    // ALIASES

    addUnitAlias('minute', 'm');

    // PRIORITY

    addUnitPriority('minute', 14);

    // PARSING

    addRegexToken('m', match1to2);
    addRegexToken('mm', match1to2, match2);
    addParseToken(['m', 'mm'], MINUTE);

    // MOMENTS

    var getSetMinute = makeGetSet('Minutes', false);

    // FORMATTING

    addFormatToken('s', ['ss', 2], 0, 'second');

    // ALIASES

    addUnitAlias('second', 's');

    // PRIORITY

    addUnitPriority('second', 15);

    // PARSING

    addRegexToken('s', match1to2);
    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;
    });


    // ALIASES

    addUnitAlias('millisecond', 'ms');

    // PRIORITY

    addUnitPriority('millisecond', 16);

    // PARSING

    addRegexToken('S', match1to3, match1);
    addRegexToken('SS', match1to3, match2);
    addRegexToken('SSS', match1to3, match3);

    var token;
    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);
    }
    // MOMENTS

    var 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;
    proto.toJSON = toJSON;
    proto.toString = toString;
    proto.unix = unix;
    proto.valueOf = valueOf;
    proto.creationData = creationData;
    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.isoWeeksInYear = getISOWeeksInYear;
    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.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();
        var 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;
        var 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;

        if (index != null) {
            return get$1(format, (index + shift) % 7, field, 'day');
        }

        var i;
        var out = [];
        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', {
        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;
        var days = this._days;
        var months = this._months;
        var data = this._data;
        var 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;
        var months;
        var milliseconds = this._milliseconds;

        units = normalizeUnits(units);

        if (units === 'month' || units === 'year') {
            days = this._days + milliseconds / 864e5;
            months = this._months + daysToMonths(days);
            return units === 'month' ? months : 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);
            }
        }
    }

    // TODO: Use this.as('ms')?
    function valueOf$1() {
        if (!this.isValid()) {
            return NaN;
        }
        return (
            this._milliseconds +
            this._days * 864e5 +
            (this._months % 12) * 2592e6 +
            toInt(this._months / 12) * 31536e6
        );
    }

    function makeAs(alias) {
        return function () {
            return this.as(alias);
        };
    }

    var asMilliseconds = makeAs('ms');
    var asSeconds = makeAs('s');
    var asMinutes = makeAs('m');
    var asHours = makeAs('h');
    var asDays = makeAs('d');
    var asWeeks = makeAs('w');
    var asMonths = makeAs('M');
    var asYears = makeAs('y');

    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');
    var seconds = makeGetter('seconds');
    var minutes = makeGetter('minutes');
    var hours = makeGetter('hours');
    var days = makeGetter('days');
    var months = makeGetter('months');
    var years = makeGetter('years');

    function weeks() {
        return absFloor(this.days() / 7);
    }

    var round = Math.round;
    var 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
        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, locale) {
        var duration = createDuration(posNegDuration).abs();
        var seconds = round(duration.as('s'));
        var minutes = round(duration.as('m'));
        var hours = round(duration.as('h'));
        var days = round(duration.as('d'));
        var months = round(duration.as('M'));
        var years = round(duration.as('y'));

        var 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] ||
            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(withSuffix) {
        if (!this.isValid()) {
            return this.localeData().invalidDate();
        }

        var locale = this.localeData();
        var output = relativeTime$1(this, !withSuffix, 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;
        var days = abs$1(this._days);
        var months = abs$1(this._months);
        var minutes, hours, years;

        // 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
        var Y = years;
        var M = months;
        var D = days;
        var h = hours;
        var m = minutes;
        var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
        var total = this.asSeconds();

        if (!total) {
            // this is the same as C#'s (Noda) and python (isodate)...
            // but not other JS (goog.date)
            return 'P0D';
        }

        var totalSign = total < 0 ? '-' : '';
        var ymSign = sign(this._months) !== sign(total) ? '-' : '';
        var daysSign = sign(this._days) !== sign(total) ? '-' : '';
        var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';

        return totalSign + 'P' +
            (Y ? ymSign + Y + 'Y' : '') +
            (M ? ymSign + M + 'M' : '') +
            (D ? daysSign + D + 'D' : '') +
            ((h || m || s) ? 'T' : '') +
            (h ? hmsSign + h + 'H' : '') +
            (m ? hmsSign + m + 'M' : '') +
            (s ? 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.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;

    // Side effect imports

    // 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, 10) * 1000);
    });
    addParseToken('x', function (input, array, config) {
        config._d = new Date(toInt(input));
    });

    // Side effect imports

    //! moment.js

    hooks.version = '2.22.2';

    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: 'YYYY-[W]WW',                             // <input type="week" />
        MONTH: 'YYYY-MM'                                // <input type="month" />
    };

    //! moment.js locale configuration

    hooks.defineLocale('af', {
        months: 'Januarie_Februarie_Maart_April_Mei_Junie_Julie_Augustus_September_Oktober_November_Desember'.split('_'),
        monthsShort: 'Jan_Feb_Mrt_Apr_Mei_Jun_Jul_Aug_Sep_Okt_Nov_Des'.split('_'),
        weekdays: 'Sondag_Maandag_Dinsdag_Woensdag_Donderdag_Vrydag_Saterdag'.split('_'),
        weekdaysShort: 'Son_Maa_Din_Woe_Don_Vry_Sat'.split('_'),
        weekdaysMin: 'So_Ma_Di_Wo_Do_Vr_Sa'.split('_'),
        meridiemParse: /vm|nm/i,
        isPM: function (input) {
            return /^nm$/i.test(input);
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours < 12) {
                return isLower ? 'vm' : 'VM';
            } else {
                return isLower ? 'nm' : 'NM';
            }
        },
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Vandag om] LT',
            nextDay: '[Môre om] LT',
            nextWeek: 'dddd [om] LT',
            lastDay: '[Gister om] LT',
            lastWeek: '[Laas] dddd [om] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'oor %s',
            past: '%s gelede',
            s: '\'n paar sekondes',
            ss: '%d sekondes',
            m: '\'n minuut',
            mm: '%d minute',
            h: '\'n uur',
            hh: '%d ure',
            d: '\'n dag',
            dd: '%d dae',
            M: '\'n maand',
            MM: '%d maande',
            y: '\'n jaar',
            yy: '%d jaar'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/,
        ordinal: function (number) {
            return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); // Thanks to Joris Röling : https://github.com/jjupiter
        },
        week: {
            dow: 1, // Maandag is die eerste dag van die week.
            doy: 4  // Die week wat die 4de Januarie bevat is die eerste week van die jaar.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('ar-dz', {
        months: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
        monthsShort: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
        weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
        weekdaysShort: 'احد_اثنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'),
        weekdaysMin: 'أح_إث_ثلا_أر_خم_جم_سب'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[اليوم على الساعة] LT',
            nextDay: '[غدا على الساعة] LT',
            nextWeek: 'dddd [على الساعة] LT',
            lastDay: '[أمس على الساعة] LT',
            lastWeek: 'dddd [على الساعة] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'في %s',
            past: 'منذ %s',
            s: 'ثوان',
            ss: '%d ثانية',
            m: 'دقيقة',
            mm: '%d دقائق',
            h: 'ساعة',
            hh: '%d ساعات',
            d: 'يوم',
            dd: '%d أيام',
            M: 'شهر',
            MM: '%d أشهر',
            y: 'سنة',
            yy: '%d سنوات'
        },
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 4  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('ar-kw', {
        months: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'),
        monthsShort: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'),
        weekdays: 'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
        weekdaysShort: 'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'),
        weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[اليوم على الساعة] LT',
            nextDay: '[غدا على الساعة] LT',
            nextWeek: 'dddd [على الساعة] LT',
            lastDay: '[أمس على الساعة] LT',
            lastWeek: 'dddd [على الساعة] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'في %s',
            past: 'منذ %s',
            s: 'ثوان',
            ss: '%d ثانية',
            m: 'دقيقة',
            mm: '%d دقائق',
            h: 'ساعة',
            hh: '%d ساعات',
            d: 'يوم',
            dd: '%d أيام',
            M: 'شهر',
            MM: '%d أشهر',
            y: 'سنة',
            yy: '%d سنوات'
        },
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 12  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var symbolMap = {
        '1': '1',
        '2': '2',
        '3': '3',
        '4': '4',
        '5': '5',
        '6': '6',
        '7': '7',
        '8': '8',
        '9': '9',
        '0': '0'
    }, pluralForm = function (n) {
        return n === 0 ? 0 : n === 1 ? 1 : n === 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5;
    }, plurals = {
        s: ['أقل من ثانية', 'ثانية واحدة', ['ثانيتان', 'ثانيتين'], '%d ثوان', '%d ثانية', '%d ثانية'],
        m: ['أقل من دقيقة', 'دقيقة واحدة', ['دقيقتان', 'دقيقتين'], '%d دقائق', '%d دقيقة', '%d دقيقة'],
        h: ['أقل من ساعة', 'ساعة واحدة', ['ساعتان', 'ساعتين'], '%d ساعات', '%d ساعة', '%d ساعة'],
        d: ['أقل من يوم', 'يوم واحد', ['يومان', 'يومين'], '%d أيام', '%d يومًا', '%d يوم'],
        M: ['أقل من شهر', 'شهر واحد', ['شهران', 'شهرين'], '%d أشهر', '%d شهرا', '%d شهر'],
        y: ['أقل من عام', 'عام واحد', ['عامان', 'عامين'], '%d أعوام', '%d عامًا', '%d عام']
    }, pluralize = function (u) {
        return function (number, withoutSuffix, string, isFuture) {
            var f = pluralForm(number),
                str = plurals[u][pluralForm(number)];
            if (f === 2) {
                str = str[withoutSuffix ? 0 : 1];
            }
            return str.replace(/%d/i, number);
        };
    }, months$1 = [
        'يناير',
        'فبراير',
        'مارس',
        'أبريل',
        'مايو',
        'يونيو',
        'يوليو',
        'أغسطس',
        'سبتمبر',
        'أكتوبر',
        'نوفمبر',
        'ديسمبر'
    ];

    hooks.defineLocale('ar-ly', {
        months: months$1,
        monthsShort: months$1,
        weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
        weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),
        weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'D/\u200FM/\u200FYYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        meridiemParse: /ص|م/,
        isPM: function (input) {
            return 'م' === input;
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 12) {
                return 'ص';
            } else {
                return 'م';
            }
        },
        calendar: {
            sameDay: '[اليوم عند الساعة] LT',
            nextDay: '[غدًا عند الساعة] LT',
            nextWeek: 'dddd [عند الساعة] LT',
            lastDay: '[أمس عند الساعة] LT',
            lastWeek: 'dddd [عند الساعة] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'بعد %s',
            past: 'منذ %s',
            s: pluralize('s'),
            ss: pluralize('s'),
            m: pluralize('m'),
            mm: pluralize('m'),
            h: pluralize('h'),
            hh: pluralize('h'),
            d: pluralize('d'),
            dd: pluralize('d'),
            M: pluralize('M'),
            MM: pluralize('M'),
            y: pluralize('y'),
            yy: pluralize('y')
        },
        preparse: function (string) {
            return string.replace(/،/g, ',');
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return symbolMap[match];
            }).replace(/,/g, '،');
        },
        week: {
            dow: 6, // Saturday is the first day of the week.
            doy: 12  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('ar-ma', {
        months: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'),
        monthsShort: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'),
        weekdays: 'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
        weekdaysShort: 'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'),
        weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[اليوم على الساعة] LT',
            nextDay: '[غدا على الساعة] LT',
            nextWeek: 'dddd [على الساعة] LT',
            lastDay: '[أمس على الساعة] LT',
            lastWeek: 'dddd [على الساعة] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'في %s',
            past: 'منذ %s',
            s: 'ثوان',
            ss: '%d ثانية',
            m: 'دقيقة',
            mm: '%d دقائق',
            h: 'ساعة',
            hh: '%d ساعات',
            d: 'يوم',
            dd: '%d أيام',
            M: 'شهر',
            MM: '%d أشهر',
            y: 'سنة',
            yy: '%d سنوات'
        },
        week: {
            dow: 6, // Saturday is the first day of the week.
            doy: 12  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var symbolMap$1 = {
        '1': '١',
        '2': '٢',
        '3': '٣',
        '4': '٤',
        '5': '٥',
        '6': '٦',
        '7': '٧',
        '8': '٨',
        '9': '٩',
        '0': '٠'
    }, numberMap = {
        '١': '1',
        '٢': '2',
        '٣': '3',
        '٤': '4',
        '٥': '5',
        '٦': '6',
        '٧': '7',
        '٨': '8',
        '٩': '9',
        '٠': '0'
    };

    hooks.defineLocale('ar-sa', {
        months: 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
        monthsShort: 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
        weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
        weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),
        weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        meridiemParse: /ص|م/,
        isPM: function (input) {
            return 'م' === input;
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 12) {
                return 'ص';
            } else {
                return 'م';
            }
        },
        calendar: {
            sameDay: '[اليوم على الساعة] LT',
            nextDay: '[غدا على الساعة] LT',
            nextWeek: 'dddd [على الساعة] LT',
            lastDay: '[أمس على الساعة] LT',
            lastWeek: 'dddd [على الساعة] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'في %s',
            past: 'منذ %s',
            s: 'ثوان',
            ss: '%d ثانية',
            m: 'دقيقة',
            mm: '%d دقائق',
            h: 'ساعة',
            hh: '%d ساعات',
            d: 'يوم',
            dd: '%d أيام',
            M: 'شهر',
            MM: '%d أشهر',
            y: 'سنة',
            yy: '%d سنوات'
        },
        preparse: function (string) {
            return string.replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) {
                return numberMap[match];
            }).replace(/،/g, ',');
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return symbolMap$1[match];
            }).replace(/,/g, '،');
        },
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 6  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('ar-tn', {
        months: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
        monthsShort: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
        weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
        weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),
        weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[اليوم على الساعة] LT',
            nextDay: '[غدا على الساعة] LT',
            nextWeek: 'dddd [على الساعة] LT',
            lastDay: '[أمس على الساعة] LT',
            lastWeek: 'dddd [على الساعة] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'في %s',
            past: 'منذ %s',
            s: 'ثوان',
            ss: '%d ثانية',
            m: 'دقيقة',
            mm: '%d دقائق',
            h: 'ساعة',
            hh: '%d ساعات',
            d: 'يوم',
            dd: '%d أيام',
            M: 'شهر',
            MM: '%d أشهر',
            y: 'سنة',
            yy: '%d سنوات'
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4 // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var symbolMap$2 = {
        '1': '١',
        '2': '٢',
        '3': '٣',
        '4': '٤',
        '5': '٥',
        '6': '٦',
        '7': '٧',
        '8': '٨',
        '9': '٩',
        '0': '٠'
    }, numberMap$1 = {
        '١': '1',
        '٢': '2',
        '٣': '3',
        '٤': '4',
        '٥': '5',
        '٦': '6',
        '٧': '7',
        '٨': '8',
        '٩': '9',
        '٠': '0'
    }, pluralForm$1 = function (n) {
        return n === 0 ? 0 : n === 1 ? 1 : n === 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5;
    }, plurals$1 = {
        s: ['أقل من ثانية', 'ثانية واحدة', ['ثانيتان', 'ثانيتين'], '%d ثوان', '%d ثانية', '%d ثانية'],
        m: ['أقل من دقيقة', 'دقيقة واحدة', ['دقيقتان', 'دقيقتين'], '%d دقائق', '%d دقيقة', '%d دقيقة'],
        h: ['أقل من ساعة', 'ساعة واحدة', ['ساعتان', 'ساعتين'], '%d ساعات', '%d ساعة', '%d ساعة'],
        d: ['أقل من يوم', 'يوم واحد', ['يومان', 'يومين'], '%d أيام', '%d يومًا', '%d يوم'],
        M: ['أقل من شهر', 'شهر واحد', ['شهران', 'شهرين'], '%d أشهر', '%d شهرا', '%d شهر'],
        y: ['أقل من عام', 'عام واحد', ['عامان', 'عامين'], '%d أعوام', '%d عامًا', '%d عام']
    }, pluralize$1 = function (u) {
        return function (number, withoutSuffix, string, isFuture) {
            var f = pluralForm$1(number),
                str = plurals$1[u][pluralForm$1(number)];
            if (f === 2) {
                str = str[withoutSuffix ? 0 : 1];
            }
            return str.replace(/%d/i, number);
        };
    }, months$2 = [
        'يناير',
        'فبراير',
        'مارس',
        'أبريل',
        'مايو',
        'يونيو',
        'يوليو',
        'أغسطس',
        'سبتمبر',
        'أكتوبر',
        'نوفمبر',
        'ديسمبر'
    ];

    hooks.defineLocale('ar', {
        months: months$2,
        monthsShort: months$2,
        weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
        weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),
        weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'D/\u200FM/\u200FYYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        meridiemParse: /ص|م/,
        isPM: function (input) {
            return 'م' === input;
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 12) {
                return 'ص';
            } else {
                return 'م';
            }
        },
        calendar: {
            sameDay: '[اليوم عند الساعة] LT',
            nextDay: '[غدًا عند الساعة] LT',
            nextWeek: 'dddd [عند الساعة] LT',
            lastDay: '[أمس عند الساعة] LT',
            lastWeek: 'dddd [عند الساعة] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'بعد %s',
            past: 'منذ %s',
            s: pluralize$1('s'),
            ss: pluralize$1('s'),
            m: pluralize$1('m'),
            mm: pluralize$1('m'),
            h: pluralize$1('h'),
            hh: pluralize$1('h'),
            d: pluralize$1('d'),
            dd: pluralize$1('d'),
            M: pluralize$1('M'),
            MM: pluralize$1('M'),
            y: pluralize$1('y'),
            yy: pluralize$1('y')
        },
        preparse: function (string) {
            return string.replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) {
                return numberMap$1[match];
            }).replace(/،/g, ',');
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return symbolMap$2[match];
            }).replace(/,/g, '،');
        },
        week: {
            dow: 6, // Saturday is the first day of the week.
            doy: 12  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var suffixes = {
        1: '-inci',
        5: '-inci',
        8: '-inci',
        70: '-inci',
        80: '-inci',
        2: '-nci',
        7: '-nci',
        20: '-nci',
        50: '-nci',
        3: '-üncü',
        4: '-üncü',
        100: '-üncü',
        6: '-ncı',
        9: '-uncu',
        10: '-uncu',
        30: '-uncu',
        60: '-ıncı',
        90: '-ıncı'
    };

    hooks.defineLocale('az', {
        months: 'yanvar_fevral_mart_aprel_may_iyun_iyul_avqust_sentyabr_oktyabr_noyabr_dekabr'.split('_'),
        monthsShort: 'yan_fev_mar_apr_may_iyn_iyl_avq_sen_okt_noy_dek'.split('_'),
        weekdays: 'Bazar_Bazar ertəsi_Çərşənbə axşamı_Çərşənbə_Cümə axşamı_Cümə_Şənbə'.split('_'),
        weekdaysShort: 'Baz_BzE_ÇAx_Çər_CAx_Cüm_Şən'.split('_'),
        weekdaysMin: 'Bz_BE_ÇA_Çə_CA_Cü_Şə'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[bugün saat] LT',
            nextDay: '[sabah saat] LT',
            nextWeek: '[gələn həftə] dddd [saat] LT',
            lastDay: '[dünən] LT',
            lastWeek: '[keçən həftə] dddd [saat] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s sonra',
            past: '%s əvvəl',
            s: 'birneçə saniyə',
            ss: '%d saniyə',
            m: 'bir dəqiqə',
            mm: '%d dəqiqə',
            h: 'bir saat',
            hh: '%d saat',
            d: 'bir gün',
            dd: '%d gün',
            M: 'bir ay',
            MM: '%d ay',
            y: 'bir il',
            yy: '%d il'
        },
        meridiemParse: /gecə|səhər|gündüz|axşam/,
        isPM: function (input) {
            return /^(gündüz|axşam)$/.test(input);
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'gecə';
            } else if (hour < 12) {
                return 'səhər';
            } else if (hour < 17) {
                return 'gündüz';
            } else {
                return 'axşam';
            }
        },
        dayOfMonthOrdinalParse: /\d{1,2}-(ıncı|inci|nci|üncü|ncı|uncu)/,
        ordinal: function (number) {
            if (number === 0) {  // special case for zero
                return number + '-ıncı';
            }
            var a = number % 10,
                b = number % 100 - a,
                c = number >= 100 ? 100 : null;
            return number + (suffixes[a] || suffixes[b] || suffixes[c]);
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    function plural(word, num) {
        var forms = word.split('_');
        return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]);
    }
    function relativeTimeWithPlural(number, withoutSuffix, key) {
        var format = {
            'ss': withoutSuffix ? 'секунда_секунды_секунд' : 'секунду_секунды_секунд',
            'mm': withoutSuffix ? 'хвіліна_хвіліны_хвілін' : 'хвіліну_хвіліны_хвілін',
            'hh': withoutSuffix ? 'гадзіна_гадзіны_гадзін' : 'гадзіну_гадзіны_гадзін',
            'dd': 'дзень_дні_дзён',
            'MM': 'месяц_месяцы_месяцаў',
            'yy': 'год_гады_гадоў'
        };
        if (key === 'm') {
            return withoutSuffix ? 'хвіліна' : 'хвіліну';
        }
        else if (key === 'h') {
            return withoutSuffix ? 'гадзіна' : 'гадзіну';
        }
        else {
            return number + ' ' + plural(format[key], +number);
        }
    }

    hooks.defineLocale('be', {
        months: {
            format: 'студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня'.split('_'),
            standalone: 'студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань'.split('_')
        },
        monthsShort: 'студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж'.split('_'),
        weekdays: {
            format: 'нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу'.split('_'),
            standalone: 'нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота'.split('_'),
            isFormat: /\[ ?[Ууў] ?(?:мінулую|наступную)? ?\] ?dddd/
        },
        weekdaysShort: 'нд_пн_ат_ср_чц_пт_сб'.split('_'),
        weekdaysMin: 'нд_пн_ат_ср_чц_пт_сб'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY г.',
            LLL: 'D MMMM YYYY г., HH:mm',
            LLLL: 'dddd, D MMMM YYYY г., HH:mm'
        },
        calendar: {
            sameDay: '[Сёння ў] LT',
            nextDay: '[Заўтра ў] LT',
            lastDay: '[Учора ў] LT',
            nextWeek: function () {
                return '[У] dddd [ў] LT';
            },
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                    case 3:
                    case 5:
                    case 6:
                        return '[У мінулую] dddd [ў] LT';
                    case 1:
                    case 2:
                    case 4:
                        return '[У мінулы] dddd [ў] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'праз %s',
            past: '%s таму',
            s: 'некалькі секунд',
            m: relativeTimeWithPlural,
            mm: relativeTimeWithPlural,
            h: relativeTimeWithPlural,
            hh: relativeTimeWithPlural,
            d: 'дзень',
            dd: relativeTimeWithPlural,
            M: 'месяц',
            MM: relativeTimeWithPlural,
            y: 'год',
            yy: relativeTimeWithPlural
        },
        meridiemParse: /ночы|раніцы|дня|вечара/,
        isPM: function (input) {
            return /^(дня|вечара)$/.test(input);
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'ночы';
            } else if (hour < 12) {
                return 'раніцы';
            } else if (hour < 17) {
                return 'дня';
            } else {
                return 'вечара';
            }
        },
        dayOfMonthOrdinalParse: /\d{1,2}-(і|ы|га)/,
        ordinal: function (number, period) {
            switch (period) {
                case 'M':
                case 'd':
                case 'DDD':
                case 'w':
                case 'W':
                    return (number % 10 === 2 || number % 10 === 3) && (number % 100 !== 12 && number % 100 !== 13) ? number + '-і' : number + '-ы';
                case 'D':
                    return number + '-га';
                default:
                    return number;
            }
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('bg', {
        months: 'януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември'.split('_'),
        monthsShort: 'янр_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек'.split('_'),
        weekdays: 'неделя_понеделник_вторник_сряда_четвъртък_петък_събота'.split('_'),
        weekdaysShort: 'нед_пон_вто_сря_чет_пет_съб'.split('_'),
        weekdaysMin: 'нд_пн_вт_ср_чт_пт_сб'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'D.MM.YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY H:mm',
            LLLL: 'dddd, D MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[Днес в] LT',
            nextDay: '[Утре в] LT',
            nextWeek: 'dddd [в] LT',
            lastDay: '[Вчера в] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                    case 3:
                    case 6:
                        return '[В изминалата] dddd [в] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[В изминалия] dddd [в] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'след %s',
            past: 'преди %s',
            s: 'няколко секунди',
            ss: '%d секунди',
            m: 'минута',
            mm: '%d минути',
            h: 'час',
            hh: '%d часа',
            d: 'ден',
            dd: '%d дни',
            M: 'месец',
            MM: '%d месеца',
            y: 'година',
            yy: '%d години'
        },
        dayOfMonthOrdinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/,
        ordinal: function (number) {
            var lastDigit = number % 10,
                last2Digits = number % 100;
            if (number === 0) {
                return number + '-ев';
            } else if (last2Digits === 0) {
                return number + '-ен';
            } else if (last2Digits > 10 && last2Digits < 20) {
                return number + '-ти';
            } else if (lastDigit === 1) {
                return number + '-ви';
            } else if (lastDigit === 2) {
                return number + '-ри';
            } else if (lastDigit === 7 || lastDigit === 8) {
                return number + '-ми';
            } else {
                return number + '-ти';
            }
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('bm', {
        months: 'Zanwuyekalo_Fewuruyekalo_Marisikalo_Awirilikalo_Mɛkalo_Zuwɛnkalo_Zuluyekalo_Utikalo_Sɛtanburukalo_ɔkutɔburukalo_Nowanburukalo_Desanburukalo'.split('_'),
        monthsShort: 'Zan_Few_Mar_Awi_Mɛ_Zuw_Zul_Uti_Sɛt_ɔku_Now_Des'.split('_'),
        weekdays: 'Kari_Ntɛnɛn_Tarata_Araba_Alamisa_Juma_Sibiri'.split('_'),
        weekdaysShort: 'Kar_Ntɛ_Tar_Ara_Ala_Jum_Sib'.split('_'),
        weekdaysMin: 'Ka_Nt_Ta_Ar_Al_Ju_Si'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'MMMM [tile] D [san] YYYY',
            LLL: 'MMMM [tile] D [san] YYYY [lɛrɛ] HH:mm',
            LLLL: 'dddd MMMM [tile] D [san] YYYY [lɛrɛ] HH:mm'
        },
        calendar: {
            sameDay: '[Bi lɛrɛ] LT',
            nextDay: '[Sini lɛrɛ] LT',
            nextWeek: 'dddd [don lɛrɛ] LT',
            lastDay: '[Kunu lɛrɛ] LT',
            lastWeek: 'dddd [tɛmɛnen lɛrɛ] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s kɔnɔ',
            past: 'a bɛ %s bɔ',
            s: 'sanga dama dama',
            ss: 'sekondi %d',
            m: 'miniti kelen',
            mm: 'miniti %d',
            h: 'lɛrɛ kelen',
            hh: 'lɛrɛ %d',
            d: 'tile kelen',
            dd: 'tile %d',
            M: 'kalo kelen',
            MM: 'kalo %d',
            y: 'san kelen',
            yy: 'san %d'
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var symbolMap$3 = {
        '1': '১',
        '2': '২',
        '3': '৩',
        '4': '৪',
        '5': '৫',
        '6': '৬',
        '7': '৭',
        '8': '৮',
        '9': '৯',
        '0': '০'
    },
        numberMap$2 = {
            '১': '1',
            '২': '2',
            '৩': '3',
            '৪': '4',
            '৫': '5',
            '৬': '6',
            '৭': '7',
            '৮': '8',
            '৯': '9',
            '০': '0'
        };

    hooks.defineLocale('bn', {
        months: 'জানুয়ারী_ফেব্রুয়ারি_মার্চ_এপ্রিল_মে_জুন_জুলাই_আগস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর'.split('_'),
        monthsShort: 'জানু_ফেব_মার্চ_এপ্র_মে_জুন_জুল_আগ_সেপ্ট_অক্টো_নভে_ডিসে'.split('_'),
        weekdays: 'রবিবার_সোমবার_মঙ্গলবার_বুধবার_বৃহস্পতিবার_শুক্রবার_শনিবার'.split('_'),
        weekdaysShort: 'রবি_সোম_মঙ্গল_বুধ_বৃহস্পতি_শুক্র_শনি'.split('_'),
        weekdaysMin: 'রবি_সোম_মঙ্গ_বুধ_বৃহঃ_শুক্র_শনি'.split('_'),
        longDateFormat: {
            LT: 'A h:mm সময়',
            LTS: 'A h:mm:ss সময়',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY, A h:mm সময়',
            LLLL: 'dddd, D MMMM YYYY, A h:mm সময়'
        },
        calendar: {
            sameDay: '[আজ] LT',
            nextDay: '[আগামীকাল] LT',
            nextWeek: 'dddd, LT',
            lastDay: '[গতকাল] LT',
            lastWeek: '[গত] dddd, LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s পরে',
            past: '%s আগে',
            s: 'কয়েক সেকেন্ড',
            ss: '%d সেকেন্ড',
            m: 'এক মিনিট',
            mm: '%d মিনিট',
            h: 'এক ঘন্টা',
            hh: '%d ঘন্টা',
            d: 'এক দিন',
            dd: '%d দিন',
            M: 'এক মাস',
            MM: '%d মাস',
            y: 'এক বছর',
            yy: '%d বছর'
        },
        preparse: function (string) {
            return string.replace(/[১২৩৪৫৬৭৮৯০]/g, function (match) {
                return numberMap$2[match];
            });
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return symbolMap$3[match];
            });
        },
        meridiemParse: /রাত|সকাল|দুপুর|বিকাল|রাত/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if ((meridiem === 'রাত' && hour >= 4) ||
                (meridiem === 'দুপুর' && hour < 5) ||
                meridiem === 'বিকাল') {
                return hour + 12;
            } else {
                return hour;
            }
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'রাত';
            } else if (hour < 10) {
                return 'সকাল';
            } else if (hour < 17) {
                return 'দুপুর';
            } else if (hour < 20) {
                return 'বিকাল';
            } else {
                return 'রাত';
            }
        },
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 6  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var symbolMap$4 = {
        '1': '༡',
        '2': '༢',
        '3': '༣',
        '4': '༤',
        '5': '༥',
        '6': '༦',
        '7': '༧',
        '8': '༨',
        '9': '༩',
        '0': '༠'
    },
        numberMap$3 = {
            '༡': '1',
            '༢': '2',
            '༣': '3',
            '༤': '4',
            '༥': '5',
            '༦': '6',
            '༧': '7',
            '༨': '8',
            '༩': '9',
            '༠': '0'
        };

    hooks.defineLocale('bo', {
        months: 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split('_'),
        monthsShort: 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split('_'),
        weekdays: 'གཟའ་ཉི་མ་_གཟའ་ཟླ་བ་_གཟའ་མིག་དམར་_གཟའ་ལྷག་པ་_གཟའ་ཕུར་བུ_གཟའ་པ་སངས་_གཟའ་སྤེན་པ་'.split('_'),
        weekdaysShort: 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split('_'),
        weekdaysMin: 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split('_'),
        longDateFormat: {
            LT: 'A h:mm',
            LTS: 'A h:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY, A h:mm',
            LLLL: 'dddd, D MMMM YYYY, A h:mm'
        },
        calendar: {
            sameDay: '[དི་རིང] LT',
            nextDay: '[སང་ཉིན] LT',
            nextWeek: '[བདུན་ཕྲག་རྗེས་མ], LT',
            lastDay: '[ཁ་སང] LT',
            lastWeek: '[བདུན་ཕྲག་མཐའ་མ] dddd, LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s ལ་',
            past: '%s སྔན་ལ',
            s: 'ལམ་སང',
            ss: '%d སྐར་ཆ།',
            m: 'སྐར་མ་གཅིག',
            mm: '%d སྐར་མ',
            h: 'ཆུ་ཚོད་གཅིག',
            hh: '%d ཆུ་ཚོད',
            d: 'ཉིན་གཅིག',
            dd: '%d ཉིན་',
            M: 'ཟླ་བ་གཅིག',
            MM: '%d ཟླ་བ',
            y: 'ལོ་གཅིག',
            yy: '%d ལོ'
        },
        preparse: function (string) {
            return string.replace(/[༡༢༣༤༥༦༧༨༩༠]/g, function (match) {
                return numberMap$3[match];
            });
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return symbolMap$4[match];
            });
        },
        meridiemParse: /མཚན་མོ|ཞོགས་ཀས|ཉིན་གུང|དགོང་དག|མཚན་མོ/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if ((meridiem === 'མཚན་མོ' && hour >= 4) ||
                (meridiem === 'ཉིན་གུང' && hour < 5) ||
                meridiem === 'དགོང་དག') {
                return hour + 12;
            } else {
                return hour;
            }
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'མཚན་མོ';
            } else if (hour < 10) {
                return 'ཞོགས་ཀས';
            } else if (hour < 17) {
                return 'ཉིན་གུང';
            } else if (hour < 20) {
                return 'དགོང་དག';
            } else {
                return 'མཚན་མོ';
            }
        },
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 6  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    function relativeTimeWithMutation(number, withoutSuffix, key) {
        var format = {
            'mm': 'munutenn',
            'MM': 'miz',
            'dd': 'devezh'
        };
        return number + ' ' + mutation(format[key], number);
    }
    function specialMutationForYears(number) {
        switch (lastNumber(number)) {
            case 1:
            case 3:
            case 4:
            case 5:
            case 9:
                return number + ' bloaz';
            default:
                return number + ' vloaz';
        }
    }
    function lastNumber(number) {
        if (number > 9) {
            return lastNumber(number % 10);
        }
        return number;
    }
    function mutation(text, number) {
        if (number === 2) {
            return softMutation(text);
        }
        return text;
    }
    function softMutation(text) {
        var mutationTable = {
            'm': 'v',
            'b': 'v',
            'd': 'z'
        };
        if (mutationTable[text.charAt(0)] === undefined) {
            return text;
        }
        return mutationTable[text.charAt(0)] + text.substring(1);
    }

    hooks.defineLocale('br', {
        months: 'Genver_C\'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu'.split('_'),
        monthsShort: 'Gen_C\'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker'.split('_'),
        weekdays: 'Sul_Lun_Meurzh_Merc\'her_Yaou_Gwener_Sadorn'.split('_'),
        weekdaysShort: 'Sul_Lun_Meu_Mer_Yao_Gwe_Sad'.split('_'),
        weekdaysMin: 'Su_Lu_Me_Mer_Ya_Gw_Sa'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'h[e]mm A',
            LTS: 'h[e]mm:ss A',
            L: 'DD/MM/YYYY',
            LL: 'D [a viz] MMMM YYYY',
            LLL: 'D [a viz] MMMM YYYY h[e]mm A',
            LLLL: 'dddd, D [a viz] MMMM YYYY h[e]mm A'
        },
        calendar: {
            sameDay: '[Hiziv da] LT',
            nextDay: '[Warc\'hoazh da] LT',
            nextWeek: 'dddd [da] LT',
            lastDay: '[Dec\'h da] LT',
            lastWeek: 'dddd [paset da] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'a-benn %s',
            past: '%s \'zo',
            s: 'un nebeud segondennoù',
            ss: '%d eilenn',
            m: 'ur vunutenn',
            mm: relativeTimeWithMutation,
            h: 'un eur',
            hh: '%d eur',
            d: 'un devezh',
            dd: relativeTimeWithMutation,
            M: 'ur miz',
            MM: relativeTimeWithMutation,
            y: 'ur bloaz',
            yy: specialMutationForYears
        },
        dayOfMonthOrdinalParse: /\d{1,2}(añ|vet)/,
        ordinal: function (number) {
            var output = (number === 1) ? 'añ' : 'vet';
            return number + output;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    function translate(number, withoutSuffix, key) {
        var result = number + ' ';
        switch (key) {
            case 'ss':
                if (number === 1) {
                    result += 'sekunda';
                } else if (number === 2 || number === 3 || number === 4) {
                    result += 'sekunde';
                } else {
                    result += 'sekundi';
                }
                return result;
            case 'm':
                return withoutSuffix ? 'jedna minuta' : 'jedne minute';
            case 'mm':
                if (number === 1) {
                    result += 'minuta';
                } else if (number === 2 || number === 3 || number === 4) {
                    result += 'minute';
                } else {
                    result += 'minuta';
                }
                return result;
            case 'h':
                return withoutSuffix ? 'jedan sat' : 'jednog sata';
            case 'hh':
                if (number === 1) {
                    result += 'sat';
                } else if (number === 2 || number === 3 || number === 4) {
                    result += 'sata';
                } else {
                    result += 'sati';
                }
                return result;
            case 'dd':
                if (number === 1) {
                    result += 'dan';
                } else {
                    result += 'dana';
                }
                return result;
            case 'MM':
                if (number === 1) {
                    result += 'mjesec';
                } else if (number === 2 || number === 3 || number === 4) {
                    result += 'mjeseca';
                } else {
                    result += 'mjeseci';
                }
                return result;
            case 'yy':
                if (number === 1) {
                    result += 'godina';
                } else if (number === 2 || number === 3 || number === 4) {
                    result += 'godine';
                } else {
                    result += 'godina';
                }
                return result;
        }
    }

    hooks.defineLocale('bs', {
        months: 'januar_februar_mart_april_maj_juni_juli_august_septembar_oktobar_novembar_decembar'.split('_'),
        monthsShort: 'jan._feb._mar._apr._maj._jun._jul._aug._sep._okt._nov._dec.'.split('_'),
        monthsParseExact: true,
        weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'),
        weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'),
        weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm',
            LLLL: 'dddd, D. MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[danas u] LT',
            nextDay: '[sutra u] LT',
            nextWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[u] [nedjelju] [u] LT';
                    case 3:
                        return '[u] [srijedu] [u] LT';
                    case 6:
                        return '[u] [subotu] [u] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[u] dddd [u] LT';
                }
            },
            lastDay: '[jučer u] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                    case 3:
                        return '[prošlu] dddd [u] LT';
                    case 6:
                        return '[prošle] [subote] [u] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[prošli] dddd [u] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'za %s',
            past: 'prije %s',
            s: 'par sekundi',
            ss: translate,
            m: translate,
            mm: translate,
            h: translate,
            hh: translate,
            d: 'dan',
            dd: translate,
            M: 'mjesec',
            MM: translate,
            y: 'godinu',
            yy: translate
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('ca', {
        months: {
            standalone: 'gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre'.split('_'),
            format: 'de gener_de febrer_de març_d\'abril_de maig_de juny_de juliol_d\'agost_de setembre_d\'octubre_de novembre_de desembre'.split('_'),
            isFormat: /D[oD]?(\s)+MMMM/
        },
        monthsShort: 'gen._febr._març_abr._maig_juny_jul._ag._set._oct._nov._des.'.split('_'),
        monthsParseExact: true,
        weekdays: 'diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte'.split('_'),
        weekdaysShort: 'dg._dl._dt._dc._dj._dv._ds.'.split('_'),
        weekdaysMin: 'dg_dl_dt_dc_dj_dv_ds'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM [de] YYYY',
            ll: 'D MMM YYYY',
            LLL: 'D MMMM [de] YYYY [a les] H:mm',
            lll: 'D MMM YYYY, H:mm',
            LLLL: 'dddd D MMMM [de] YYYY [a les] H:mm',
            llll: 'ddd D MMM YYYY, H:mm'
        },
        calendar: {
            sameDay: function () {
                return '[avui a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
            },
            nextDay: function () {
                return '[demà a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
            },
            nextWeek: function () {
                return 'dddd [a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
            },
            lastDay: function () {
                return '[ahir a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
            },
            lastWeek: function () {
                return '[el] dddd [passat a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT';
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'd\'aquí %s',
            past: 'fa %s',
            s: 'uns segons',
            ss: '%d segons',
            m: 'un minut',
            mm: '%d minuts',
            h: 'una hora',
            hh: '%d hores',
            d: 'un dia',
            dd: '%d dies',
            M: 'un mes',
            MM: '%d mesos',
            y: 'un any',
            yy: '%d anys'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(r|n|t|è|a)/,
        ordinal: function (number, period) {
            var output = (number === 1) ? 'r' :
                (number === 2) ? 'n' :
                    (number === 3) ? 'r' :
                        (number === 4) ? 't' : 'è';
            if (period === 'w' || period === 'W') {
                output = 'a';
            }
            return number + output;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var months$3 = 'leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec'.split('_'),
        monthsShort = 'led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro'.split('_');
    function plural$1(n) {
        return (n > 1) && (n < 5) && (~~(n / 10) !== 1);
    }
    function translate$1(number, withoutSuffix, key, isFuture) {
        var result = number + ' ';
        switch (key) {
            case 's':  // a few seconds / in a few seconds / a few seconds ago
                return (withoutSuffix || isFuture) ? 'pár sekund' : 'pár sekundami';
            case 'ss': // 9 seconds / in 9 seconds / 9 seconds ago
                if (withoutSuffix || isFuture) {
                    return result + (plural$1(number) ? 'sekundy' : 'sekund');
                } else {
                    return result + 'sekundami';
                }
                break;
            case 'm':  // a minute / in a minute / a minute ago
                return withoutSuffix ? 'minuta' : (isFuture ? 'minutu' : 'minutou');
            case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago
                if (withoutSuffix || isFuture) {
                    return result + (plural$1(number) ? 'minuty' : 'minut');
                } else {
                    return result + 'minutami';
                }
                break;
            case 'h':  // an hour / in an hour / an hour ago
                return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou');
            case 'hh': // 9 hours / in 9 hours / 9 hours ago
                if (withoutSuffix || isFuture) {
                    return result + (plural$1(number) ? 'hodiny' : 'hodin');
                } else {
                    return result + 'hodinami';
                }
                break;
            case 'd':  // a day / in a day / a day ago
                return (withoutSuffix || isFuture) ? 'den' : 'dnem';
            case 'dd': // 9 days / in 9 days / 9 days ago
                if (withoutSuffix || isFuture) {
                    return result + (plural$1(number) ? 'dny' : 'dní');
                } else {
                    return result + 'dny';
                }
                break;
            case 'M':  // a month / in a month / a month ago
                return (withoutSuffix || isFuture) ? 'měsíc' : 'měsícem';
            case 'MM': // 9 months / in 9 months / 9 months ago
                if (withoutSuffix || isFuture) {
                    return result + (plural$1(number) ? 'měsíce' : 'měsíců');
                } else {
                    return result + 'měsíci';
                }
                break;
            case 'y':  // a year / in a year / a year ago
                return (withoutSuffix || isFuture) ? 'rok' : 'rokem';
            case 'yy': // 9 years / in 9 years / 9 years ago
                if (withoutSuffix || isFuture) {
                    return result + (plural$1(number) ? 'roky' : 'let');
                } else {
                    return result + 'lety';
                }
                break;
        }
    }

    hooks.defineLocale('cs', {
        months: months$3,
        monthsShort: monthsShort,
        monthsParse: (function (months, monthsShort) {
            var i, _monthsParse = [];
            for (i = 0; i < 12; i++) {
                // use custom parser to solve problem with July (červenec)
                _monthsParse[i] = new RegExp('^' + months[i] + '$|^' + monthsShort[i] + '$', 'i');
            }
            return _monthsParse;
        }(months$3, monthsShort)),
        shortMonthsParse: (function (monthsShort) {
            var i, _shortMonthsParse = [];
            for (i = 0; i < 12; i++) {
                _shortMonthsParse[i] = new RegExp('^' + monthsShort[i] + '$', 'i');
            }
            return _shortMonthsParse;
        }(monthsShort)),
        longMonthsParse: (function (months) {
            var i, _longMonthsParse = [];
            for (i = 0; i < 12; i++) {
                _longMonthsParse[i] = new RegExp('^' + months[i] + '$', 'i');
            }
            return _longMonthsParse;
        }(months$3)),
        weekdays: 'neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota'.split('_'),
        weekdaysShort: 'ne_po_út_st_čt_pá_so'.split('_'),
        weekdaysMin: 'ne_po_út_st_čt_pá_so'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm',
            LLLL: 'dddd D. MMMM YYYY H:mm',
            l: 'D. M. YYYY'
        },
        calendar: {
            sameDay: '[dnes v] LT',
            nextDay: '[zítra v] LT',
            nextWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[v neděli v] LT';
                    case 1:
                    case 2:
                        return '[v] dddd [v] LT';
                    case 3:
                        return '[ve středu v] LT';
                    case 4:
                        return '[ve čtvrtek v] LT';
                    case 5:
                        return '[v pátek v] LT';
                    case 6:
                        return '[v sobotu v] LT';
                }
            },
            lastDay: '[včera v] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[minulou neděli v] LT';
                    case 1:
                    case 2:
                        return '[minulé] dddd [v] LT';
                    case 3:
                        return '[minulou středu v] LT';
                    case 4:
                    case 5:
                        return '[minulý] dddd [v] LT';
                    case 6:
                        return '[minulou sobotu v] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'za %s',
            past: 'před %s',
            s: translate$1,
            ss: translate$1,
            m: translate$1,
            mm: translate$1,
            h: translate$1,
            hh: translate$1,
            d: translate$1,
            dd: translate$1,
            M: translate$1,
            MM: translate$1,
            y: translate$1,
            yy: translate$1
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('cv', {
        months: 'кӑрлач_нарӑс_пуш_ака_май_ҫӗртме_утӑ_ҫурла_авӑн_юпа_чӳк_раштав'.split('_'),
        monthsShort: 'кӑр_нар_пуш_ака_май_ҫӗр_утӑ_ҫур_авн_юпа_чӳк_раш'.split('_'),
        weekdays: 'вырсарникун_тунтикун_ытларикун_юнкун_кӗҫнерникун_эрнекун_шӑматкун'.split('_'),
        weekdaysShort: 'выр_тун_ытл_юн_кӗҫ_эрн_шӑм'.split('_'),
        weekdaysMin: 'вр_тн_ыт_юн_кҫ_эр_шм'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD-MM-YYYY',
            LL: 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ]',
            LLL: 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm',
            LLLL: 'dddd, YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm'
        },
        calendar: {
            sameDay: '[Паян] LT [сехетре]',
            nextDay: '[Ыран] LT [сехетре]',
            lastDay: '[Ӗнер] LT [сехетре]',
            nextWeek: '[Ҫитес] dddd LT [сехетре]',
            lastWeek: '[Иртнӗ] dddd LT [сехетре]',
            sameElse: 'L'
        },
        relativeTime: {
            future: function (output) {
                var affix = /сехет$/i.exec(output) ? 'рен' : /ҫул$/i.exec(output) ? 'тан' : 'ран';
                return output + affix;
            },
            past: '%s каялла',
            s: 'пӗр-ик ҫеккунт',
            ss: '%d ҫеккунт',
            m: 'пӗр минут',
            mm: '%d минут',
            h: 'пӗр сехет',
            hh: '%d сехет',
            d: 'пӗр кун',
            dd: '%d кун',
            M: 'пӗр уйӑх',
            MM: '%d уйӑх',
            y: 'пӗр ҫул',
            yy: '%d ҫул'
        },
        dayOfMonthOrdinalParse: /\d{1,2}-мӗш/,
        ordinal: '%d-мӗш',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('cy', {
        months: 'Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr'.split('_'),
        monthsShort: 'Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag'.split('_'),
        weekdays: 'Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn'.split('_'),
        weekdaysShort: 'Sul_Llun_Maw_Mer_Iau_Gwe_Sad'.split('_'),
        weekdaysMin: 'Su_Ll_Ma_Me_Ia_Gw_Sa'.split('_'),
        weekdaysParseExact: true,
        // time formats are the same as en-gb
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Heddiw am] LT',
            nextDay: '[Yfory am] LT',
            nextWeek: 'dddd [am] LT',
            lastDay: '[Ddoe am] LT',
            lastWeek: 'dddd [diwethaf am] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'mewn %s',
            past: '%s yn ôl',
            s: 'ychydig eiliadau',
            ss: '%d eiliad',
            m: 'munud',
            mm: '%d munud',
            h: 'awr',
            hh: '%d awr',
            d: 'diwrnod',
            dd: '%d diwrnod',
            M: 'mis',
            MM: '%d mis',
            y: 'blwyddyn',
            yy: '%d flynedd'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(fed|ain|af|il|ydd|ed|eg)/,
        // traditional ordinal numbers above 31 are not commonly used in colloquial Welsh
        ordinal: function (number) {
            var b = number,
                output = '',
                lookup = [
                    '', 'af', 'il', 'ydd', 'ydd', 'ed', 'ed', 'ed', 'fed', 'fed', 'fed', // 1af to 10fed
                    'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'fed' // 11eg to 20fed
                ];
            if (b > 20) {
                if (b === 40 || b === 50 || b === 60 || b === 80 || b === 100) {
                    output = 'fed'; // not 30ain, 70ain or 90ain
                } else {
                    output = 'ain';
                }
            } else if (b > 0) {
                output = lookup[b];
            }
            return number + output;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('da', {
        months: 'januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december'.split('_'),
        monthsShort: 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'),
        weekdays: 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'),
        weekdaysShort: 'søn_man_tir_ons_tor_fre_lør'.split('_'),
        weekdaysMin: 'sø_ma_ti_on_to_fr_lø'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY HH:mm',
            LLLL: 'dddd [d.] D. MMMM YYYY [kl.] HH:mm'
        },
        calendar: {
            sameDay: '[i dag kl.] LT',
            nextDay: '[i morgen kl.] LT',
            nextWeek: 'på dddd [kl.] LT',
            lastDay: '[i går kl.] LT',
            lastWeek: '[i] dddd[s kl.] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'om %s',
            past: '%s siden',
            s: 'få sekunder',
            ss: '%d sekunder',
            m: 'et minut',
            mm: '%d minutter',
            h: 'en time',
            hh: '%d timer',
            d: 'en dag',
            dd: '%d dage',
            M: 'en måned',
            MM: '%d måneder',
            y: 'et år',
            yy: '%d år'
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    function processRelativeTime(number, withoutSuffix, key, isFuture) {
        var format = {
            'm': ['eine Minute', 'einer Minute'],
            'h': ['eine Stunde', 'einer Stunde'],
            'd': ['ein Tag', 'einem Tag'],
            'dd': [number + ' Tage', number + ' Tagen'],
            'M': ['ein Monat', 'einem Monat'],
            'MM': [number + ' Monate', number + ' Monaten'],
            'y': ['ein Jahr', 'einem Jahr'],
            'yy': [number + ' Jahre', number + ' Jahren']
        };
        return withoutSuffix ? format[key][0] : format[key][1];
    }

    hooks.defineLocale('de-at', {
        months: 'Jänner_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),
        monthsShort: 'Jän._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'),
        monthsParseExact: true,
        weekdays: 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'),
        weekdaysShort: 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'),
        weekdaysMin: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY HH:mm',
            LLLL: 'dddd, D. MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[heute um] LT [Uhr]',
            sameElse: 'L',
            nextDay: '[morgen um] LT [Uhr]',
            nextWeek: 'dddd [um] LT [Uhr]',
            lastDay: '[gestern um] LT [Uhr]',
            lastWeek: '[letzten] dddd [um] LT [Uhr]'
        },
        relativeTime: {
            future: 'in %s',
            past: 'vor %s',
            s: 'ein paar Sekunden',
            ss: '%d Sekunden',
            m: processRelativeTime,
            mm: '%d Minuten',
            h: processRelativeTime,
            hh: '%d Stunden',
            d: processRelativeTime,
            dd: processRelativeTime,
            M: processRelativeTime,
            MM: processRelativeTime,
            y: processRelativeTime,
            yy: processRelativeTime
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    function processRelativeTime$1(number, withoutSuffix, key, isFuture) {
        var format = {
            'm': ['eine Minute', 'einer Minute'],
            'h': ['eine Stunde', 'einer Stunde'],
            'd': ['ein Tag', 'einem Tag'],
            'dd': [number + ' Tage', number + ' Tagen'],
            'M': ['ein Monat', 'einem Monat'],
            'MM': [number + ' Monate', number + ' Monaten'],
            'y': ['ein Jahr', 'einem Jahr'],
            'yy': [number + ' Jahre', number + ' Jahren']
        };
        return withoutSuffix ? format[key][0] : format[key][1];
    }

    hooks.defineLocale('de-ch', {
        months: 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),
        monthsShort: 'Jan._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'),
        monthsParseExact: true,
        weekdays: 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'),
        weekdaysShort: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),
        weekdaysMin: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY HH:mm',
            LLLL: 'dddd, D. MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[heute um] LT [Uhr]',
            sameElse: 'L',
            nextDay: '[morgen um] LT [Uhr]',
            nextWeek: 'dddd [um] LT [Uhr]',
            lastDay: '[gestern um] LT [Uhr]',
            lastWeek: '[letzten] dddd [um] LT [Uhr]'
        },
        relativeTime: {
            future: 'in %s',
            past: 'vor %s',
            s: 'ein paar Sekunden',
            ss: '%d Sekunden',
            m: processRelativeTime$1,
            mm: '%d Minuten',
            h: processRelativeTime$1,
            hh: '%d Stunden',
            d: processRelativeTime$1,
            dd: processRelativeTime$1,
            M: processRelativeTime$1,
            MM: processRelativeTime$1,
            y: processRelativeTime$1,
            yy: processRelativeTime$1
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    function processRelativeTime$2(number, withoutSuffix, key, isFuture) {
        var format = {
            'm': ['eine Minute', 'einer Minute'],
            'h': ['eine Stunde', 'einer Stunde'],
            'd': ['ein Tag', 'einem Tag'],
            'dd': [number + ' Tage', number + ' Tagen'],
            'M': ['ein Monat', 'einem Monat'],
            'MM': [number + ' Monate', number + ' Monaten'],
            'y': ['ein Jahr', 'einem Jahr'],
            'yy': [number + ' Jahre', number + ' Jahren']
        };
        return withoutSuffix ? format[key][0] : format[key][1];
    }

    hooks.defineLocale('de', {
        months: 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),
        monthsShort: 'Jan._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'),
        monthsParseExact: true,
        weekdays: 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'),
        weekdaysShort: 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'),
        weekdaysMin: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY HH:mm',
            LLLL: 'dddd, D. MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[heute um] LT [Uhr]',
            sameElse: 'L',
            nextDay: '[morgen um] LT [Uhr]',
            nextWeek: 'dddd [um] LT [Uhr]',
            lastDay: '[gestern um] LT [Uhr]',
            lastWeek: '[letzten] dddd [um] LT [Uhr]'
        },
        relativeTime: {
            future: 'in %s',
            past: 'vor %s',
            s: 'ein paar Sekunden',
            ss: '%d Sekunden',
            m: processRelativeTime$2,
            mm: '%d Minuten',
            h: processRelativeTime$2,
            hh: '%d Stunden',
            d: processRelativeTime$2,
            dd: processRelativeTime$2,
            M: processRelativeTime$2,
            MM: processRelativeTime$2,
            y: processRelativeTime$2,
            yy: processRelativeTime$2
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var months$4 = [
        'ޖެނުއަރީ',
        'ފެބްރުއަރީ',
        'މާރިޗު',
        'އޭޕްރީލު',
        'މޭ',
        'ޖޫން',
        'ޖުލައި',
        'އޯގަސްޓު',
        'ސެޕްޓެމްބަރު',
        'އޮކްޓޯބަރު',
        'ނޮވެމްބަރު',
        'ޑިސެމްބަރު'
    ], weekdays = [
        'އާދިއްތަ',
        'ހޯމަ',
        'އަންގާރަ',
        'ބުދަ',
        'ބުރާސްފަތި',
        'ހުކުރު',
        'ހޮނިހިރު'
    ];

    hooks.defineLocale('dv', {
        months: months$4,
        monthsShort: months$4,
        weekdays: weekdays,
        weekdaysShort: weekdays,
        weekdaysMin: 'އާދި_ހޯމަ_އަން_ބުދަ_ބުރާ_ހުކު_ހޮނި'.split('_'),
        longDateFormat: {

            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'D/M/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        meridiemParse: /މކ|މފ/,
        isPM: function (input) {
            return 'މފ' === input;
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 12) {
                return 'މކ';
            } else {
                return 'މފ';
            }
        },
        calendar: {
            sameDay: '[މިއަދު] LT',
            nextDay: '[މާދަމާ] LT',
            nextWeek: 'dddd LT',
            lastDay: '[އިއްޔެ] LT',
            lastWeek: '[ފާއިތުވި] dddd LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'ތެރޭގައި %s',
            past: 'ކުރިން %s',
            s: 'ސިކުންތުކޮޅެއް',
            ss: 'd% ސިކުންތު',
            m: 'މިނިޓެއް',
            mm: 'މިނިޓު %d',
            h: 'ގަޑިއިރެއް',
            hh: 'ގަޑިއިރު %d',
            d: 'ދުވަހެއް',
            dd: 'ދުވަސް %d',
            M: 'މަހެއް',
            MM: 'މަސް %d',
            y: 'އަހަރެއް',
            yy: 'އަހަރު %d'
        },
        preparse: function (string) {
            return string.replace(/،/g, ',');
        },
        postformat: function (string) {
            return string.replace(/,/g, '،');
        },
        week: {
            dow: 7,  // Sunday is the first day of the week.
            doy: 12  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('el', {
        monthsNominativeEl: 'Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος'.split('_'),
        monthsGenitiveEl: 'Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου'.split('_'),
        months: function (momentToFormat, format) {
            if (!momentToFormat) {
                return this._monthsNominativeEl;
            } else if (typeof format === 'string' && /D/.test(format.substring(0, format.indexOf('MMMM')))) { // if there is a day number before 'MMMM'
                return this._monthsGenitiveEl[momentToFormat.month()];
            } else {
                return this._monthsNominativeEl[momentToFormat.month()];
            }
        },
        monthsShort: 'Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ'.split('_'),
        weekdays: 'Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο'.split('_'),
        weekdaysShort: 'Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ'.split('_'),
        weekdaysMin: 'Κυ_Δε_Τρ_Τε_Πε_Πα_Σα'.split('_'),
        meridiem: function (hours, minutes, isLower) {
            if (hours > 11) {
                return isLower ? 'μμ' : 'ΜΜ';
            } else {
                return isLower ? 'πμ' : 'ΠΜ';
            }
        },
        isPM: function (input) {
            return ((input + '').toLowerCase()[0] === 'μ');
        },
        meridiemParse: /[ΠΜ]\.?Μ?\.?/i,
        longDateFormat: {
            LT: 'h:mm A',
            LTS: 'h:mm:ss A',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY h:mm A',
            LLLL: 'dddd, D MMMM YYYY h:mm A'
        },
        calendarEl: {
            sameDay: '[Σήμερα {}] LT',
            nextDay: '[Αύριο {}] LT',
            nextWeek: 'dddd [{}] LT',
            lastDay: '[Χθες {}] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 6:
                        return '[το προηγούμενο] dddd [{}] LT';
                    default:
                        return '[την προηγούμενη] dddd [{}] LT';
                }
            },
            sameElse: 'L'
        },
        calendar: function (key, mom) {
            var output = this._calendarEl[key],
                hours = mom && mom.hours();
            if (isFunction(output)) {
                output = output.apply(mom);
            }
            return output.replace('{}', (hours % 12 === 1 ? 'στη' : 'στις'));
        },
        relativeTime: {
            future: 'σε %s',
            past: '%s πριν',
            s: 'λίγα δευτερόλεπτα',
            ss: '%d δευτερόλεπτα',
            m: 'ένα λεπτό',
            mm: '%d λεπτά',
            h: 'μία ώρα',
            hh: '%d ώρες',
            d: 'μία μέρα',
            dd: '%d μέρες',
            M: 'ένας μήνας',
            MM: '%d μήνες',
            y: 'ένας χρόνος',
            yy: '%d χρόνια'
        },
        dayOfMonthOrdinalParse: /\d{1,2}η/,
        ordinal: '%dη',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('en-au', {
        months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
        monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
        weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
        weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
        weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
        longDateFormat: {
            LT: 'h:mm A',
            LTS: 'h:mm:ss A',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY h:mm A',
            LLLL: 'dddd, D MMMM YYYY h:mm A'
        },
        calendar: {
            sameDay: '[Today at] LT',
            nextDay: '[Tomorrow at] LT',
            nextWeek: 'dddd [at] LT',
            lastDay: '[Yesterday at] LT',
            lastWeek: '[Last] dddd [at] LT',
            sameElse: 'L'
        },
        relativeTime: {
            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',
            M: 'a month',
            MM: '%d months',
            y: 'a year',
            yy: '%d years'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/,
        ordinal: function (number) {
            var b = number % 10,
                output = (~~(number % 100 / 10) === 1) ? 'th' :
                    (b === 1) ? 'st' :
                        (b === 2) ? 'nd' :
                            (b === 3) ? 'rd' : 'th';
            return number + output;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('en-ca', {
        months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
        monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
        weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
        weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
        weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
        longDateFormat: {
            LT: 'h:mm A',
            LTS: 'h:mm:ss A',
            L: 'YYYY-MM-DD',
            LL: 'MMMM D, YYYY',
            LLL: 'MMMM D, YYYY h:mm A',
            LLLL: 'dddd, MMMM D, YYYY h:mm A'
        },
        calendar: {
            sameDay: '[Today at] LT',
            nextDay: '[Tomorrow at] LT',
            nextWeek: 'dddd [at] LT',
            lastDay: '[Yesterday at] LT',
            lastWeek: '[Last] dddd [at] LT',
            sameElse: 'L'
        },
        relativeTime: {
            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',
            M: 'a month',
            MM: '%d months',
            y: 'a year',
            yy: '%d years'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/,
        ordinal: function (number) {
            var b = number % 10,
                output = (~~(number % 100 / 10) === 1) ? 'th' :
                    (b === 1) ? 'st' :
                        (b === 2) ? 'nd' :
                            (b === 3) ? 'rd' : 'th';
            return number + output;
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('en-gb', {
        months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
        monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
        weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
        weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
        weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Today at] LT',
            nextDay: '[Tomorrow at] LT',
            nextWeek: 'dddd [at] LT',
            lastDay: '[Yesterday at] LT',
            lastWeek: '[Last] dddd [at] LT',
            sameElse: 'L'
        },
        relativeTime: {
            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',
            M: 'a month',
            MM: '%d months',
            y: 'a year',
            yy: '%d years'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/,
        ordinal: function (number) {
            var b = number % 10,
                output = (~~(number % 100 / 10) === 1) ? 'th' :
                    (b === 1) ? 'st' :
                        (b === 2) ? 'nd' :
                            (b === 3) ? 'rd' : 'th';
            return number + output;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('en-ie', {
        months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
        monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
        weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
        weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
        weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD-MM-YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Today at] LT',
            nextDay: '[Tomorrow at] LT',
            nextWeek: 'dddd [at] LT',
            lastDay: '[Yesterday at] LT',
            lastWeek: '[Last] dddd [at] LT',
            sameElse: 'L'
        },
        relativeTime: {
            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',
            M: 'a month',
            MM: '%d months',
            y: 'a year',
            yy: '%d years'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/,
        ordinal: function (number) {
            var b = number % 10,
                output = (~~(number % 100 / 10) === 1) ? 'th' :
                    (b === 1) ? 'st' :
                        (b === 2) ? 'nd' :
                            (b === 3) ? 'rd' : 'th';
            return number + output;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('en-il', {
        months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
        monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
        weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
        weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
        weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Today at] LT',
            nextDay: '[Tomorrow at] LT',
            nextWeek: 'dddd [at] LT',
            lastDay: '[Yesterday at] LT',
            lastWeek: '[Last] dddd [at] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'in %s',
            past: '%s ago',
            s: 'a few seconds',
            m: 'a minute',
            mm: '%d minutes',
            h: 'an hour',
            hh: '%d hours',
            d: 'a day',
            dd: '%d days',
            M: 'a month',
            MM: '%d months',
            y: 'a year',
            yy: '%d years'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/,
        ordinal: function (number) {
            var b = number % 10,
                output = (~~(number % 100 / 10) === 1) ? 'th' :
                    (b === 1) ? 'st' :
                        (b === 2) ? 'nd' :
                            (b === 3) ? 'rd' : 'th';
            return number + output;
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('en-nz', {
        months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
        monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
        weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
        weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
        weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
        longDateFormat: {
            LT: 'h:mm A',
            LTS: 'h:mm:ss A',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY h:mm A',
            LLLL: 'dddd, D MMMM YYYY h:mm A'
        },
        calendar: {
            sameDay: '[Today at] LT',
            nextDay: '[Tomorrow at] LT',
            nextWeek: 'dddd [at] LT',
            lastDay: '[Yesterday at] LT',
            lastWeek: '[Last] dddd [at] LT',
            sameElse: 'L'
        },
        relativeTime: {
            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',
            M: 'a month',
            MM: '%d months',
            y: 'a year',
            yy: '%d years'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/,
        ordinal: function (number) {
            var b = number % 10,
                output = (~~(number % 100 / 10) === 1) ? 'th' :
                    (b === 1) ? 'st' :
                        (b === 2) ? 'nd' :
                            (b === 3) ? 'rd' : 'th';
            return number + output;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('eo', {
        months: 'januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro'.split('_'),
        monthsShort: 'jan_feb_mar_apr_maj_jun_jul_aŭg_sep_okt_nov_dec'.split('_'),
        weekdays: 'dimanĉo_lundo_mardo_merkredo_ĵaŭdo_vendredo_sabato'.split('_'),
        weekdaysShort: 'dim_lun_mard_merk_ĵaŭ_ven_sab'.split('_'),
        weekdaysMin: 'di_lu_ma_me_ĵa_ve_sa'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'YYYY-MM-DD',
            LL: 'D[-a de] MMMM, YYYY',
            LLL: 'D[-a de] MMMM, YYYY HH:mm',
            LLLL: 'dddd, [la] D[-a de] MMMM, YYYY HH:mm'
        },
        meridiemParse: /[ap]\.t\.m/i,
        isPM: function (input) {
            return input.charAt(0).toLowerCase() === 'p';
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours > 11) {
                return isLower ? 'p.t.m.' : 'P.T.M.';
            } else {
                return isLower ? 'a.t.m.' : 'A.T.M.';
            }
        },
        calendar: {
            sameDay: '[Hodiaŭ je] LT',
            nextDay: '[Morgaŭ je] LT',
            nextWeek: 'dddd [je] LT',
            lastDay: '[Hieraŭ je] LT',
            lastWeek: '[pasinta] dddd [je] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'post %s',
            past: 'antaŭ %s',
            s: 'sekundoj',
            ss: '%d sekundoj',
            m: 'minuto',
            mm: '%d minutoj',
            h: 'horo',
            hh: '%d horoj',
            d: 'tago',//ne 'diurno', ĉar estas uzita por proksimumo
            dd: '%d tagoj',
            M: 'monato',
            MM: '%d monatoj',
            y: 'jaro',
            yy: '%d jaroj'
        },
        dayOfMonthOrdinalParse: /\d{1,2}a/,
        ordinal: '%da',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'),
        monthsShort$1 = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_');

    var monthsParse = [/^ene/i, /^feb/i, /^mar/i, /^abr/i, /^may/i, /^jun/i, /^jul/i, /^ago/i, /^sep/i, /^oct/i, /^nov/i, /^dic/i];
    var monthsRegex$1 = /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i;

    hooks.defineLocale('es-do', {
        months: 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'),
        monthsShort: function (m, format) {
            if (!m) {
                return monthsShortDot;
            } else if (/-MMM-/.test(format)) {
                return monthsShort$1[m.month()];
            } else {
                return monthsShortDot[m.month()];
            }
        },
        monthsRegex: monthsRegex$1,
        monthsShortRegex: monthsRegex$1,
        monthsStrictRegex: /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i,
        monthsShortStrictRegex: /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i,
        monthsParse: monthsParse,
        longMonthsParse: monthsParse,
        shortMonthsParse: monthsParse,
        weekdays: 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),
        weekdaysShort: 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),
        weekdaysMin: 'do_lu_ma_mi_ju_vi_sá'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'h:mm A',
            LTS: 'h:mm:ss A',
            L: 'DD/MM/YYYY',
            LL: 'D [de] MMMM [de] YYYY',
            LLL: 'D [de] MMMM [de] YYYY h:mm A',
            LLLL: 'dddd, D [de] MMMM [de] YYYY h:mm A'
        },
        calendar: {
            sameDay: function () {
                return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            nextDay: function () {
                return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            nextWeek: function () {
                return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            lastDay: function () {
                return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            lastWeek: function () {
                return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'en %s',
            past: 'hace %s',
            s: 'unos segundos',
            ss: '%d segundos',
            m: 'un minuto',
            mm: '%d minutos',
            h: 'una hora',
            hh: '%d horas',
            d: 'un día',
            dd: '%d días',
            M: 'un mes',
            MM: '%d meses',
            y: 'un año',
            yy: '%d años'
        },
        dayOfMonthOrdinalParse: /\d{1,2}º/,
        ordinal: '%dº',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var monthsShortDot$1 = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'),
        monthsShort$2 = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_');

    hooks.defineLocale('es-us', {
        months: 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'),
        monthsShort: function (m, format) {
            if (!m) {
                return monthsShortDot$1;
            } else if (/-MMM-/.test(format)) {
                return monthsShort$2[m.month()];
            } else {
                return monthsShortDot$1[m.month()];
            }
        },
        monthsParseExact: true,
        weekdays: 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),
        weekdaysShort: 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),
        weekdaysMin: 'do_lu_ma_mi_ju_vi_sá'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'h:mm A',
            LTS: 'h:mm:ss A',
            L: 'MM/DD/YYYY',
            LL: 'MMMM [de] D [de] YYYY',
            LLL: 'MMMM [de] D [de] YYYY h:mm A',
            LLLL: 'dddd, MMMM [de] D [de] YYYY h:mm A'
        },
        calendar: {
            sameDay: function () {
                return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            nextDay: function () {
                return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            nextWeek: function () {
                return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            lastDay: function () {
                return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            lastWeek: function () {
                return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'en %s',
            past: 'hace %s',
            s: 'unos segundos',
            ss: '%d segundos',
            m: 'un minuto',
            mm: '%d minutos',
            h: 'una hora',
            hh: '%d horas',
            d: 'un día',
            dd: '%d días',
            M: 'un mes',
            MM: '%d meses',
            y: 'un año',
            yy: '%d años'
        },
        dayOfMonthOrdinalParse: /\d{1,2}º/,
        ordinal: '%dº',
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 6  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var monthsShortDot$2 = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'),
        monthsShort$3 = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_');

    var monthsParse$1 = [/^ene/i, /^feb/i, /^mar/i, /^abr/i, /^may/i, /^jun/i, /^jul/i, /^ago/i, /^sep/i, /^oct/i, /^nov/i, /^dic/i];
    var monthsRegex$2 = /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i;

    hooks.defineLocale('es', {
        months: 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'),
        monthsShort: function (m, format) {
            if (!m) {
                return monthsShortDot$2;
            } else if (/-MMM-/.test(format)) {
                return monthsShort$3[m.month()];
            } else {
                return monthsShortDot$2[m.month()];
            }
        },
        monthsRegex: monthsRegex$2,
        monthsShortRegex: monthsRegex$2,
        monthsStrictRegex: /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i,
        monthsShortStrictRegex: /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i,
        monthsParse: monthsParse$1,
        longMonthsParse: monthsParse$1,
        shortMonthsParse: monthsParse$1,
        weekdays: 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),
        weekdaysShort: 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),
        weekdaysMin: 'do_lu_ma_mi_ju_vi_sá'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D [de] MMMM [de] YYYY',
            LLL: 'D [de] MMMM [de] YYYY H:mm',
            LLLL: 'dddd, D [de] MMMM [de] YYYY H:mm'
        },
        calendar: {
            sameDay: function () {
                return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            nextDay: function () {
                return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            nextWeek: function () {
                return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            lastDay: function () {
                return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            lastWeek: function () {
                return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'en %s',
            past: 'hace %s',
            s: 'unos segundos',
            ss: '%d segundos',
            m: 'un minuto',
            mm: '%d minutos',
            h: 'una hora',
            hh: '%d horas',
            d: 'un día',
            dd: '%d días',
            M: 'un mes',
            MM: '%d meses',
            y: 'un año',
            yy: '%d años'
        },
        dayOfMonthOrdinalParse: /\d{1,2}º/,
        ordinal: '%dº',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    function processRelativeTime$3(number, withoutSuffix, key, isFuture) {
        var format = {
            's': ['mõne sekundi', 'mõni sekund', 'paar sekundit'],
            'ss': [number + 'sekundi', number + 'sekundit'],
            'm': ['ühe minuti', 'üks minut'],
            'mm': [number + ' minuti', number + ' minutit'],
            'h': ['ühe tunni', 'tund aega', 'üks tund'],
            'hh': [number + ' tunni', number + ' tundi'],
            'd': ['ühe päeva', 'üks päev'],
            'M': ['kuu aja', 'kuu aega', 'üks kuu'],
            'MM': [number + ' kuu', number + ' kuud'],
            'y': ['ühe aasta', 'aasta', 'üks aasta'],
            'yy': [number + ' aasta', number + ' aastat']
        };
        if (withoutSuffix) {
            return format[key][2] ? format[key][2] : format[key][1];
        }
        return isFuture ? format[key][0] : format[key][1];
    }

    hooks.defineLocale('et', {
        months: 'jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember'.split('_'),
        monthsShort: 'jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets'.split('_'),
        weekdays: 'pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev'.split('_'),
        weekdaysShort: 'P_E_T_K_N_R_L'.split('_'),
        weekdaysMin: 'P_E_T_K_N_R_L'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm',
            LLLL: 'dddd, D. MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[Täna,] LT',
            nextDay: '[Homme,] LT',
            nextWeek: '[Järgmine] dddd LT',
            lastDay: '[Eile,] LT',
            lastWeek: '[Eelmine] dddd LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s pärast',
            past: '%s tagasi',
            s: processRelativeTime$3,
            ss: processRelativeTime$3,
            m: processRelativeTime$3,
            mm: processRelativeTime$3,
            h: processRelativeTime$3,
            hh: processRelativeTime$3,
            d: processRelativeTime$3,
            dd: '%d päeva',
            M: processRelativeTime$3,
            MM: processRelativeTime$3,
            y: processRelativeTime$3,
            yy: processRelativeTime$3
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('eu', {
        months: 'urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua'.split('_'),
        monthsShort: 'urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.'.split('_'),
        monthsParseExact: true,
        weekdays: 'igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata'.split('_'),
        weekdaysShort: 'ig._al._ar._az._og._ol._lr.'.split('_'),
        weekdaysMin: 'ig_al_ar_az_og_ol_lr'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'YYYY-MM-DD',
            LL: 'YYYY[ko] MMMM[ren] D[a]',
            LLL: 'YYYY[ko] MMMM[ren] D[a] HH:mm',
            LLLL: 'dddd, YYYY[ko] MMMM[ren] D[a] HH:mm',
            l: 'YYYY-M-D',
            ll: 'YYYY[ko] MMM D[a]',
            lll: 'YYYY[ko] MMM D[a] HH:mm',
            llll: 'ddd, YYYY[ko] MMM D[a] HH:mm'
        },
        calendar: {
            sameDay: '[gaur] LT[etan]',
            nextDay: '[bihar] LT[etan]',
            nextWeek: 'dddd LT[etan]',
            lastDay: '[atzo] LT[etan]',
            lastWeek: '[aurreko] dddd LT[etan]',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s barru',
            past: 'duela %s',
            s: 'segundo batzuk',
            ss: '%d segundo',
            m: 'minutu bat',
            mm: '%d minutu',
            h: 'ordu bat',
            hh: '%d ordu',
            d: 'egun bat',
            dd: '%d egun',
            M: 'hilabete bat',
            MM: '%d hilabete',
            y: 'urte bat',
            yy: '%d urte'
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var symbolMap$5 = {
        '1': '۱',
        '2': '۲',
        '3': '۳',
        '4': '۴',
        '5': '۵',
        '6': '۶',
        '7': '۷',
        '8': '۸',
        '9': '۹',
        '0': '۰'
    }, numberMap$4 = {
        '۱': '1',
        '۲': '2',
        '۳': '3',
        '۴': '4',
        '۵': '5',
        '۶': '6',
        '۷': '7',
        '۸': '8',
        '۹': '9',
        '۰': '0'
    };

    hooks.defineLocale('fa', {
        months: 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'),
        monthsShort: 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'),
        weekdays: 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'),
        weekdaysShort: 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'),
        weekdaysMin: 'ی_د_س_چ_پ_ج_ش'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        meridiemParse: /قبل از ظهر|بعد از ظهر/,
        isPM: function (input) {
            return /بعد از ظهر/.test(input);
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 12) {
                return 'قبل از ظهر';
            } else {
                return 'بعد از ظهر';
            }
        },
        calendar: {
            sameDay: '[امروز ساعت] LT',
            nextDay: '[فردا ساعت] LT',
            nextWeek: 'dddd [ساعت] LT',
            lastDay: '[دیروز ساعت] LT',
            lastWeek: 'dddd [پیش] [ساعت] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'در %s',
            past: '%s پیش',
            s: 'چند ثانیه',
            ss: 'ثانیه d%',
            m: 'یک دقیقه',
            mm: '%d دقیقه',
            h: 'یک ساعت',
            hh: '%d ساعت',
            d: 'یک روز',
            dd: '%d روز',
            M: 'یک ماه',
            MM: '%d ماه',
            y: 'یک سال',
            yy: '%d سال'
        },
        preparse: function (string) {
            return string.replace(/[۰-۹]/g, function (match) {
                return numberMap$4[match];
            }).replace(/،/g, ',');
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return symbolMap$5[match];
            }).replace(/,/g, '،');
        },
        dayOfMonthOrdinalParse: /\d{1,2}م/,
        ordinal: '%dم',
        week: {
            dow: 6, // Saturday is the first day of the week.
            doy: 12 // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var numbersPast = 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split(' '),
        numbersFuture = [
            'nolla', 'yhden', 'kahden', 'kolmen', 'neljän', 'viiden', 'kuuden',
            numbersPast[7], numbersPast[8], numbersPast[9]
        ];
    function translate$2(number, withoutSuffix, key, isFuture) {
        var result = '';
        switch (key) {
            case 's':
                return isFuture ? 'muutaman sekunnin' : 'muutama sekunti';
            case 'ss':
                return isFuture ? 'sekunnin' : 'sekuntia';
            case 'm':
                return isFuture ? 'minuutin' : 'minuutti';
            case 'mm':
                result = isFuture ? 'minuutin' : 'minuuttia';
                break;
            case 'h':
                return isFuture ? 'tunnin' : 'tunti';
            case 'hh':
                result = isFuture ? 'tunnin' : 'tuntia';
                break;
            case 'd':
                return isFuture ? 'päivän' : 'päivä';
            case 'dd':
                result = isFuture ? 'päivän' : 'päivää';
                break;
            case 'M':
                return isFuture ? 'kuukauden' : 'kuukausi';
            case 'MM':
                result = isFuture ? 'kuukauden' : 'kuukautta';
                break;
            case 'y':
                return isFuture ? 'vuoden' : 'vuosi';
            case 'yy':
                result = isFuture ? 'vuoden' : 'vuotta';
                break;
        }
        result = verbalNumber(number, isFuture) + ' ' + result;
        return result;
    }
    function verbalNumber(number, isFuture) {
        return number < 10 ? (isFuture ? numbersFuture[number] : numbersPast[number]) : number;
    }

    hooks.defineLocale('fi', {
        months: 'tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu'.split('_'),
        monthsShort: 'tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu'.split('_'),
        weekdays: 'sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai'.split('_'),
        weekdaysShort: 'su_ma_ti_ke_to_pe_la'.split('_'),
        weekdaysMin: 'su_ma_ti_ke_to_pe_la'.split('_'),
        longDateFormat: {
            LT: 'HH.mm',
            LTS: 'HH.mm.ss',
            L: 'DD.MM.YYYY',
            LL: 'Do MMMM[ta] YYYY',
            LLL: 'Do MMMM[ta] YYYY, [klo] HH.mm',
            LLLL: 'dddd, Do MMMM[ta] YYYY, [klo] HH.mm',
            l: 'D.M.YYYY',
            ll: 'Do MMM YYYY',
            lll: 'Do MMM YYYY, [klo] HH.mm',
            llll: 'ddd, Do MMM YYYY, [klo] HH.mm'
        },
        calendar: {
            sameDay: '[tänään] [klo] LT',
            nextDay: '[huomenna] [klo] LT',
            nextWeek: 'dddd [klo] LT',
            lastDay: '[eilen] [klo] LT',
            lastWeek: '[viime] dddd[na] [klo] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s päästä',
            past: '%s sitten',
            s: translate$2,
            ss: translate$2,
            m: translate$2,
            mm: translate$2,
            h: translate$2,
            hh: translate$2,
            d: translate$2,
            dd: translate$2,
            M: translate$2,
            MM: translate$2,
            y: translate$2,
            yy: translate$2
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('fo', {
        months: 'januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember'.split('_'),
        monthsShort: 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'),
        weekdays: 'sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur'.split('_'),
        weekdaysShort: 'sun_mán_týs_mik_hós_frí_ley'.split('_'),
        weekdaysMin: 'su_má_tý_mi_hó_fr_le'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D. MMMM, YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Í dag kl.] LT',
            nextDay: '[Í morgin kl.] LT',
            nextWeek: 'dddd [kl.] LT',
            lastDay: '[Í gjár kl.] LT',
            lastWeek: '[síðstu] dddd [kl] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'um %s',
            past: '%s síðani',
            s: 'fá sekund',
            ss: '%d sekundir',
            m: 'ein minutt',
            mm: '%d minuttir',
            h: 'ein tími',
            hh: '%d tímar',
            d: 'ein dagur',
            dd: '%d dagar',
            M: 'ein mánaði',
            MM: '%d mánaðir',
            y: 'eitt ár',
            yy: '%d ár'
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('fr-ca', {
        months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),
        monthsShort: 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'),
        monthsParseExact: true,
        weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),
        weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),
        weekdaysMin: 'di_lu_ma_me_je_ve_sa'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'YYYY-MM-DD',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Aujourd’hui à] LT',
            nextDay: '[Demain à] LT',
            nextWeek: 'dddd [à] LT',
            lastDay: '[Hier à] LT',
            lastWeek: 'dddd [dernier à] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'dans %s',
            past: 'il y a %s',
            s: 'quelques secondes',
            ss: '%d secondes',
            m: 'une minute',
            mm: '%d minutes',
            h: 'une heure',
            hh: '%d heures',
            d: 'un jour',
            dd: '%d jours',
            M: 'un mois',
            MM: '%d mois',
            y: 'un an',
            yy: '%d ans'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(er|e)/,
        ordinal: function (number, period) {
            switch (period) {
                // Words with masculine grammatical gender: mois, trimestre, jour
                default:
                case 'M':
                case 'Q':
                case 'D':
                case 'DDD':
                case 'd':
                    return number + (number === 1 ? 'er' : 'e');

                // Words with feminine grammatical gender: semaine
                case 'w':
                case 'W':
                    return number + (number === 1 ? 're' : 'e');
            }
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('fr-ch', {
        months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),
        monthsShort: 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'),
        monthsParseExact: true,
        weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),
        weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),
        weekdaysMin: 'di_lu_ma_me_je_ve_sa'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Aujourd’hui à] LT',
            nextDay: '[Demain à] LT',
            nextWeek: 'dddd [à] LT',
            lastDay: '[Hier à] LT',
            lastWeek: 'dddd [dernier à] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'dans %s',
            past: 'il y a %s',
            s: 'quelques secondes',
            ss: '%d secondes',
            m: 'une minute',
            mm: '%d minutes',
            h: 'une heure',
            hh: '%d heures',
            d: 'un jour',
            dd: '%d jours',
            M: 'un mois',
            MM: '%d mois',
            y: 'un an',
            yy: '%d ans'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(er|e)/,
        ordinal: function (number, period) {
            switch (period) {
                // Words with masculine grammatical gender: mois, trimestre, jour
                default:
                case 'M':
                case 'Q':
                case 'D':
                case 'DDD':
                case 'd':
                    return number + (number === 1 ? 'er' : 'e');

                // Words with feminine grammatical gender: semaine
                case 'w':
                case 'W':
                    return number + (number === 1 ? 're' : 'e');
            }
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('fr', {
        months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),
        monthsShort: 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'),
        monthsParseExact: true,
        weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),
        weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),
        weekdaysMin: 'di_lu_ma_me_je_ve_sa'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Aujourd’hui à] LT',
            nextDay: '[Demain à] LT',
            nextWeek: 'dddd [à] LT',
            lastDay: '[Hier à] LT',
            lastWeek: 'dddd [dernier à] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'dans %s',
            past: 'il y a %s',
            s: 'quelques secondes',
            ss: '%d secondes',
            m: 'une minute',
            mm: '%d minutes',
            h: 'une heure',
            hh: '%d heures',
            d: 'un jour',
            dd: '%d jours',
            M: 'un mois',
            MM: '%d mois',
            y: 'un an',
            yy: '%d ans'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(er|)/,
        ordinal: function (number, period) {
            switch (period) {
                // TODO: Return 'e' when day of month > 1. Move this case inside
                // block for masculine words below.
                // See https://github.com/moment/moment/issues/3375
                case 'D':
                    return number + (number === 1 ? 'er' : '');

                // Words with masculine grammatical gender: mois, trimestre, jour
                default:
                case 'M':
                case 'Q':
                case 'DDD':
                case 'd':
                    return number + (number === 1 ? 'er' : 'e');

                // Words with feminine grammatical gender: semaine
                case 'w':
                case 'W':
                    return number + (number === 1 ? 're' : 'e');
            }
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var monthsShortWithDots = 'jan._feb._mrt._apr._mai_jun._jul._aug._sep._okt._nov._des.'.split('_'),
        monthsShortWithoutDots = 'jan_feb_mrt_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_');

    hooks.defineLocale('fy', {
        months: 'jannewaris_febrewaris_maart_april_maaie_juny_july_augustus_septimber_oktober_novimber_desimber'.split('_'),
        monthsShort: function (m, format) {
            if (!m) {
                return monthsShortWithDots;
            } else if (/-MMM-/.test(format)) {
                return monthsShortWithoutDots[m.month()];
            } else {
                return monthsShortWithDots[m.month()];
            }
        },
        monthsParseExact: true,
        weekdays: 'snein_moandei_tiisdei_woansdei_tongersdei_freed_sneon'.split('_'),
        weekdaysShort: 'si._mo._ti._wo._to._fr._so.'.split('_'),
        weekdaysMin: 'Si_Mo_Ti_Wo_To_Fr_So'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD-MM-YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[hjoed om] LT',
            nextDay: '[moarn om] LT',
            nextWeek: 'dddd [om] LT',
            lastDay: '[juster om] LT',
            lastWeek: '[ôfrûne] dddd [om] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'oer %s',
            past: '%s lyn',
            s: 'in pear sekonden',
            ss: '%d sekonden',
            m: 'ien minút',
            mm: '%d minuten',
            h: 'ien oere',
            hh: '%d oeren',
            d: 'ien dei',
            dd: '%d dagen',
            M: 'ien moanne',
            MM: '%d moannen',
            y: 'ien jier',
            yy: '%d jierren'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/,
        ordinal: function (number) {
            return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de');
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var months$5 = [
        'Am Faoilleach', 'An Gearran', 'Am Màrt', 'An Giblean', 'An Cèitean', 'An t-Ògmhios', 'An t-Iuchar', 'An Lùnastal', 'An t-Sultain', 'An Dàmhair', 'An t-Samhain', 'An Dùbhlachd'
    ];

    var monthsShort$4 = ['Faoi', 'Gear', 'Màrt', 'Gibl', 'Cèit', 'Ògmh', 'Iuch', 'Lùn', 'Sult', 'Dàmh', 'Samh', 'Dùbh'];

    var weekdays$1 = ['Didòmhnaich', 'Diluain', 'Dimàirt', 'Diciadain', 'Diardaoin', 'Dihaoine', 'Disathairne'];

    var weekdaysShort = ['Did', 'Dil', 'Dim', 'Dic', 'Dia', 'Dih', 'Dis'];

    var weekdaysMin = ['Dò', 'Lu', 'Mà', 'Ci', 'Ar', 'Ha', 'Sa'];

    hooks.defineLocale('gd', {
        months: months$5,
        monthsShort: monthsShort$4,
        monthsParseExact: true,
        weekdays: weekdays$1,
        weekdaysShort: weekdaysShort,
        weekdaysMin: weekdaysMin,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[An-diugh aig] LT',
            nextDay: '[A-màireach aig] LT',
            nextWeek: 'dddd [aig] LT',
            lastDay: '[An-dè aig] LT',
            lastWeek: 'dddd [seo chaidh] [aig] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'ann an %s',
            past: 'bho chionn %s',
            s: 'beagan diogan',
            ss: '%d diogan',
            m: 'mionaid',
            mm: '%d mionaidean',
            h: 'uair',
            hh: '%d uairean',
            d: 'latha',
            dd: '%d latha',
            M: 'mìos',
            MM: '%d mìosan',
            y: 'bliadhna',
            yy: '%d bliadhna'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(d|na|mh)/,
        ordinal: function (number) {
            var output = number === 1 ? 'd' : number % 10 === 2 ? 'na' : 'mh';
            return number + output;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('gl', {
        months: 'xaneiro_febreiro_marzo_abril_maio_xuño_xullo_agosto_setembro_outubro_novembro_decembro'.split('_'),
        monthsShort: 'xan._feb._mar._abr._mai._xuñ._xul._ago._set._out._nov._dec.'.split('_'),
        monthsParseExact: true,
        weekdays: 'domingo_luns_martes_mércores_xoves_venres_sábado'.split('_'),
        weekdaysShort: 'dom._lun._mar._mér._xov._ven._sáb.'.split('_'),
        weekdaysMin: 'do_lu_ma_mé_xo_ve_sá'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D [de] MMMM [de] YYYY',
            LLL: 'D [de] MMMM [de] YYYY H:mm',
            LLLL: 'dddd, D [de] MMMM [de] YYYY H:mm'
        },
        calendar: {
            sameDay: function () {
                return '[hoxe ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT';
            },
            nextDay: function () {
                return '[mañá ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT';
            },
            nextWeek: function () {
                return 'dddd [' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT';
            },
            lastDay: function () {
                return '[onte ' + ((this.hours() !== 1) ? 'á' : 'a') + '] LT';
            },
            lastWeek: function () {
                return '[o] dddd [pasado ' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT';
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: function (str) {
                if (str.indexOf('un') === 0) {
                    return 'n' + str;
                }
                return 'en ' + str;
            },
            past: 'hai %s',
            s: 'uns segundos',
            ss: '%d segundos',
            m: 'un minuto',
            mm: '%d minutos',
            h: 'unha hora',
            hh: '%d horas',
            d: 'un día',
            dd: '%d días',
            M: 'un mes',
            MM: '%d meses',
            y: 'un ano',
            yy: '%d anos'
        },
        dayOfMonthOrdinalParse: /\d{1,2}º/,
        ordinal: '%dº',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    function processRelativeTime$4(number, withoutSuffix, key, isFuture) {
        var format = {
            's': ['thodde secondanim', 'thodde second'],
            'ss': [number + ' secondanim', number + ' second'],
            'm': ['eka mintan', 'ek minute'],
            'mm': [number + ' mintanim', number + ' mintam'],
            'h': ['eka horan', 'ek hor'],
            'hh': [number + ' horanim', number + ' horam'],
            'd': ['eka disan', 'ek dis'],
            'dd': [number + ' disanim', number + ' dis'],
            'M': ['eka mhoinean', 'ek mhoino'],
            'MM': [number + ' mhoineanim', number + ' mhoine'],
            'y': ['eka vorsan', 'ek voros'],
            'yy': [number + ' vorsanim', number + ' vorsam']
        };
        return withoutSuffix ? format[key][0] : format[key][1];
    }

    hooks.defineLocale('gom-latn', {
        months: 'Janer_Febrer_Mars_Abril_Mai_Jun_Julai_Agost_Setembr_Otubr_Novembr_Dezembr'.split('_'),
        monthsShort: 'Jan._Feb._Mars_Abr._Mai_Jun_Jul._Ago._Set._Otu._Nov._Dez.'.split('_'),
        monthsParseExact: true,
        weekdays: 'Aitar_Somar_Mongllar_Budvar_Brestar_Sukrar_Son\'var'.split('_'),
        weekdaysShort: 'Ait._Som._Mon._Bud._Bre._Suk._Son.'.split('_'),
        weekdaysMin: 'Ai_Sm_Mo_Bu_Br_Su_Sn'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'A h:mm [vazta]',
            LTS: 'A h:mm:ss [vazta]',
            L: 'DD-MM-YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY A h:mm [vazta]',
            LLLL: 'dddd, MMMM[achea] Do, YYYY, A h:mm [vazta]',
            llll: 'ddd, D MMM YYYY, A h:mm [vazta]'
        },
        calendar: {
            sameDay: '[Aiz] LT',
            nextDay: '[Faleam] LT',
            nextWeek: '[Ieta to] dddd[,] LT',
            lastDay: '[Kal] LT',
            lastWeek: '[Fatlo] dddd[,] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s',
            past: '%s adim',
            s: processRelativeTime$4,
            ss: processRelativeTime$4,
            m: processRelativeTime$4,
            mm: processRelativeTime$4,
            h: processRelativeTime$4,
            hh: processRelativeTime$4,
            d: processRelativeTime$4,
            dd: processRelativeTime$4,
            M: processRelativeTime$4,
            MM: processRelativeTime$4,
            y: processRelativeTime$4,
            yy: processRelativeTime$4
        },
        dayOfMonthOrdinalParse: /\d{1,2}(er)/,
        ordinal: function (number, period) {
            switch (period) {
                // the ordinal 'er' only applies to day of the month
                case 'D':
                    return number + 'er';
                default:
                case 'M':
                case 'Q':
                case 'DDD':
                case 'd':
                case 'w':
                case 'W':
                    return number;
            }
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        },
        meridiemParse: /rati|sokalli|donparam|sanje/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'rati') {
                return hour < 4 ? hour : hour + 12;
            } else if (meridiem === 'sokalli') {
                return hour;
            } else if (meridiem === 'donparam') {
                return hour > 12 ? hour : hour + 12;
            } else if (meridiem === 'sanje') {
                return hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'rati';
            } else if (hour < 12) {
                return 'sokalli';
            } else if (hour < 16) {
                return 'donparam';
            } else if (hour < 20) {
                return 'sanje';
            } else {
                return 'rati';
            }
        }
    });

    //! moment.js locale configuration

    var symbolMap$6 = {
        '1': '૧',
        '2': '૨',
        '3': '૩',
        '4': '૪',
        '5': '૫',
        '6': '૬',
        '7': '૭',
        '8': '૮',
        '9': '૯',
        '0': '૦'
    },
        numberMap$5 = {
            '૧': '1',
            '૨': '2',
            '૩': '3',
            '૪': '4',
            '૫': '5',
            '૬': '6',
            '૭': '7',
            '૮': '8',
            '૯': '9',
            '૦': '0'
        };

    hooks.defineLocale('gu', {
        months: 'જાન્યુઆરી_ફેબ્રુઆરી_માર્ચ_એપ્રિલ_મે_જૂન_જુલાઈ_ઑગસ્ટ_સપ્ટેમ્બર_ઑક્ટ્બર_નવેમ્બર_ડિસેમ્બર'.split('_'),
        monthsShort: 'જાન્યુ._ફેબ્રુ._માર્ચ_એપ્રિ._મે_જૂન_જુલા._ઑગ._સપ્ટે._ઑક્ટ્._નવે._ડિસે.'.split('_'),
        monthsParseExact: true,
        weekdays: 'રવિવાર_સોમવાર_મંગળવાર_બુધ્વાર_ગુરુવાર_શુક્રવાર_શનિવાર'.split('_'),
        weekdaysShort: 'રવિ_સોમ_મંગળ_બુધ્_ગુરુ_શુક્ર_શનિ'.split('_'),
        weekdaysMin: 'ર_સો_મં_બુ_ગુ_શુ_શ'.split('_'),
        longDateFormat: {
            LT: 'A h:mm વાગ્યે',
            LTS: 'A h:mm:ss વાગ્યે',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY, A h:mm વાગ્યે',
            LLLL: 'dddd, D MMMM YYYY, A h:mm વાગ્યે'
        },
        calendar: {
            sameDay: '[આજ] LT',
            nextDay: '[કાલે] LT',
            nextWeek: 'dddd, LT',
            lastDay: '[ગઇકાલે] LT',
            lastWeek: '[પાછલા] dddd, LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s મા',
            past: '%s પેહલા',
            s: 'અમુક પળો',
            ss: '%d સેકંડ',
            m: 'એક મિનિટ',
            mm: '%d મિનિટ',
            h: 'એક કલાક',
            hh: '%d કલાક',
            d: 'એક દિવસ',
            dd: '%d દિવસ',
            M: 'એક મહિનો',
            MM: '%d મહિનો',
            y: 'એક વર્ષ',
            yy: '%d વર્ષ'
        },
        preparse: function (string) {
            return string.replace(/[૧૨૩૪૫૬૭૮૯૦]/g, function (match) {
                return numberMap$5[match];
            });
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return symbolMap$6[match];
            });
        },
        // Gujarati notation for meridiems are quite fuzzy in practice. While there exists
        // a rigid notion of a 'Pahar' it is not used as rigidly in modern Gujarati.
        meridiemParse: /રાત|બપોર|સવાર|સાંજ/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'રાત') {
                return hour < 4 ? hour : hour + 12;
            } else if (meridiem === 'સવાર') {
                return hour;
            } else if (meridiem === 'બપોર') {
                return hour >= 10 ? hour : hour + 12;
            } else if (meridiem === 'સાંજ') {
                return hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'રાત';
            } else if (hour < 10) {
                return 'સવાર';
            } else if (hour < 17) {
                return 'બપોર';
            } else if (hour < 20) {
                return 'સાંજ';
            } else {
                return 'રાત';
            }
        },
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 6 // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('he', {
        months: 'ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר'.split('_'),
        monthsShort: 'ינו׳_פבר׳_מרץ_אפר׳_מאי_יוני_יולי_אוג׳_ספט׳_אוק׳_נוב׳_דצמ׳'.split('_'),
        weekdays: 'ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת'.split('_'),
        weekdaysShort: 'א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳'.split('_'),
        weekdaysMin: 'א_ב_ג_ד_ה_ו_ש'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D [ב]MMMM YYYY',
            LLL: 'D [ב]MMMM YYYY HH:mm',
            LLLL: 'dddd, D [ב]MMMM YYYY HH:mm',
            l: 'D/M/YYYY',
            ll: 'D MMM YYYY',
            lll: 'D MMM YYYY HH:mm',
            llll: 'ddd, D MMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[היום ב־]LT',
            nextDay: '[מחר ב־]LT',
            nextWeek: 'dddd [בשעה] LT',
            lastDay: '[אתמול ב־]LT',
            lastWeek: '[ביום] dddd [האחרון בשעה] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'בעוד %s',
            past: 'לפני %s',
            s: 'מספר שניות',
            ss: '%d שניות',
            m: 'דקה',
            mm: '%d דקות',
            h: 'שעה',
            hh: function (number) {
                if (number === 2) {
                    return 'שעתיים';
                }
                return number + ' שעות';
            },
            d: 'יום',
            dd: function (number) {
                if (number === 2) {
                    return 'יומיים';
                }
                return number + ' ימים';
            },
            M: 'חודש',
            MM: function (number) {
                if (number === 2) {
                    return 'חודשיים';
                }
                return number + ' חודשים';
            },
            y: 'שנה',
            yy: function (number) {
                if (number === 2) {
                    return 'שנתיים';
                } else if (number % 10 === 0 && number !== 10) {
                    return number + ' שנה';
                }
                return number + ' שנים';
            }
        },
        meridiemParse: /אחה"צ|לפנה"צ|אחרי הצהריים|לפני הצהריים|לפנות בוקר|בבוקר|בערב/i,
        isPM: function (input) {
            return /^(אחה"צ|אחרי הצהריים|בערב)$/.test(input);
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 5) {
                return 'לפנות בוקר';
            } else if (hour < 10) {
                return 'בבוקר';
            } else if (hour < 12) {
                return isLower ? 'לפנה"צ' : 'לפני הצהריים';
            } else if (hour < 18) {
                return isLower ? 'אחה"צ' : 'אחרי הצהריים';
            } else {
                return 'בערב';
            }
        }
    });

    //! moment.js locale configuration

    var symbolMap$7 = {
        '1': '१',
        '2': '२',
        '3': '३',
        '4': '४',
        '5': '५',
        '6': '६',
        '7': '७',
        '8': '८',
        '9': '९',
        '0': '०'
    },
        numberMap$6 = {
            '१': '1',
            '२': '2',
            '३': '3',
            '४': '4',
            '५': '5',
            '६': '6',
            '७': '7',
            '८': '8',
            '९': '9',
            '०': '0'
        };

    hooks.defineLocale('hi', {
        months: 'जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर'.split('_'),
        monthsShort: 'जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.'.split('_'),
        monthsParseExact: true,
        weekdays: 'रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'),
        weekdaysShort: 'रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि'.split('_'),
        weekdaysMin: 'र_सो_मं_बु_गु_शु_श'.split('_'),
        longDateFormat: {
            LT: 'A h:mm बजे',
            LTS: 'A h:mm:ss बजे',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY, A h:mm बजे',
            LLLL: 'dddd, D MMMM YYYY, A h:mm बजे'
        },
        calendar: {
            sameDay: '[आज] LT',
            nextDay: '[कल] LT',
            nextWeek: 'dddd, LT',
            lastDay: '[कल] LT',
            lastWeek: '[पिछले] dddd, LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s में',
            past: '%s पहले',
            s: 'कुछ ही क्षण',
            ss: '%d सेकंड',
            m: 'एक मिनट',
            mm: '%d मिनट',
            h: 'एक घंटा',
            hh: '%d घंटे',
            d: 'एक दिन',
            dd: '%d दिन',
            M: 'एक महीने',
            MM: '%d महीने',
            y: 'एक वर्ष',
            yy: '%d वर्ष'
        },
        preparse: function (string) {
            return string.replace(/[१२३४५६७८९०]/g, function (match) {
                return numberMap$6[match];
            });
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return symbolMap$7[match];
            });
        },
        // Hindi notation for meridiems are quite fuzzy in practice. While there exists
        // a rigid notion of a 'Pahar' it is not used as rigidly in modern Hindi.
        meridiemParse: /रात|सुबह|दोपहर|शाम/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'रात') {
                return hour < 4 ? hour : hour + 12;
            } else if (meridiem === 'सुबह') {
                return hour;
            } else if (meridiem === 'दोपहर') {
                return hour >= 10 ? hour : hour + 12;
            } else if (meridiem === 'शाम') {
                return hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'रात';
            } else if (hour < 10) {
                return 'सुबह';
            } else if (hour < 17) {
                return 'दोपहर';
            } else if (hour < 20) {
                return 'शाम';
            } else {
                return 'रात';
            }
        },
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 6  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    function translate$3(number, withoutSuffix, key) {
        var result = number + ' ';
        switch (key) {
            case 'ss':
                if (number === 1) {
                    result += 'sekunda';
                } else if (number === 2 || number === 3 || number === 4) {
                    result += 'sekunde';
                } else {
                    result += 'sekundi';
                }
                return result;
            case 'm':
                return withoutSuffix ? 'jedna minuta' : 'jedne minute';
            case 'mm':
                if (number === 1) {
                    result += 'minuta';
                } else if (number === 2 || number === 3 || number === 4) {
                    result += 'minute';
                } else {
                    result += 'minuta';
                }
                return result;
            case 'h':
                return withoutSuffix ? 'jedan sat' : 'jednog sata';
            case 'hh':
                if (number === 1) {
                    result += 'sat';
                } else if (number === 2 || number === 3 || number === 4) {
                    result += 'sata';
                } else {
                    result += 'sati';
                }
                return result;
            case 'dd':
                if (number === 1) {
                    result += 'dan';
                } else {
                    result += 'dana';
                }
                return result;
            case 'MM':
                if (number === 1) {
                    result += 'mjesec';
                } else if (number === 2 || number === 3 || number === 4) {
                    result += 'mjeseca';
                } else {
                    result += 'mjeseci';
                }
                return result;
            case 'yy':
                if (number === 1) {
                    result += 'godina';
                } else if (number === 2 || number === 3 || number === 4) {
                    result += 'godine';
                } else {
                    result += 'godina';
                }
                return result;
        }
    }

    hooks.defineLocale('hr', {
        months: {
            format: 'siječnja_veljače_ožujka_travnja_svibnja_lipnja_srpnja_kolovoza_rujna_listopada_studenoga_prosinca'.split('_'),
            standalone: 'siječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac'.split('_')
        },
        monthsShort: 'sij._velj._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.'.split('_'),
        monthsParseExact: true,
        weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'),
        weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'),
        weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm',
            LLLL: 'dddd, D. MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[danas u] LT',
            nextDay: '[sutra u] LT',
            nextWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[u] [nedjelju] [u] LT';
                    case 3:
                        return '[u] [srijedu] [u] LT';
                    case 6:
                        return '[u] [subotu] [u] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[u] dddd [u] LT';
                }
            },
            lastDay: '[jučer u] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                    case 3:
                        return '[prošlu] dddd [u] LT';
                    case 6:
                        return '[prošle] [subote] [u] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[prošli] dddd [u] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'za %s',
            past: 'prije %s',
            s: 'par sekundi',
            ss: translate$3,
            m: translate$3,
            mm: translate$3,
            h: translate$3,
            hh: translate$3,
            d: 'dan',
            dd: translate$3,
            M: 'mjesec',
            MM: translate$3,
            y: 'godinu',
            yy: translate$3
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var weekEndings = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' ');
    function translate$4(number, withoutSuffix, key, isFuture) {
        var num = number;
        switch (key) {
            case 's':
                return (isFuture || withoutSuffix) ? 'néhány másodperc' : 'néhány másodperce';
            case 'ss':
                return num + (isFuture || withoutSuffix) ? ' másodperc' : ' másodperce';
            case 'm':
                return 'egy' + (isFuture || withoutSuffix ? ' perc' : ' perce');
            case 'mm':
                return num + (isFuture || withoutSuffix ? ' perc' : ' perce');
            case 'h':
                return 'egy' + (isFuture || withoutSuffix ? ' óra' : ' órája');
            case 'hh':
                return num + (isFuture || withoutSuffix ? ' óra' : ' órája');
            case 'd':
                return 'egy' + (isFuture || withoutSuffix ? ' nap' : ' napja');
            case 'dd':
                return num + (isFuture || withoutSuffix ? ' nap' : ' napja');
            case 'M':
                return 'egy' + (isFuture || withoutSuffix ? ' hónap' : ' hónapja');
            case 'MM':
                return num + (isFuture || withoutSuffix ? ' hónap' : ' hónapja');
            case 'y':
                return 'egy' + (isFuture || withoutSuffix ? ' év' : ' éve');
            case 'yy':
                return num + (isFuture || withoutSuffix ? ' év' : ' éve');
        }
        return '';
    }
    function week(isFuture) {
        return (isFuture ? '' : '[múlt] ') + '[' + weekEndings[this.day()] + '] LT[-kor]';
    }

    hooks.defineLocale('hu', {
        months: 'január_február_március_április_május_június_július_augusztus_szeptember_október_november_december'.split('_'),
        monthsShort: 'jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec'.split('_'),
        weekdays: 'vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat'.split('_'),
        weekdaysShort: 'vas_hét_kedd_sze_csüt_pén_szo'.split('_'),
        weekdaysMin: 'v_h_k_sze_cs_p_szo'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'YYYY.MM.DD.',
            LL: 'YYYY. MMMM D.',
            LLL: 'YYYY. MMMM D. H:mm',
            LLLL: 'YYYY. MMMM D., dddd H:mm'
        },
        meridiemParse: /de|du/i,
        isPM: function (input) {
            return input.charAt(1).toLowerCase() === 'u';
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours < 12) {
                return isLower === true ? 'de' : 'DE';
            } else {
                return isLower === true ? 'du' : 'DU';
            }
        },
        calendar: {
            sameDay: '[ma] LT[-kor]',
            nextDay: '[holnap] LT[-kor]',
            nextWeek: function () {
                return week.call(this, true);
            },
            lastDay: '[tegnap] LT[-kor]',
            lastWeek: function () {
                return week.call(this, false);
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s múlva',
            past: '%s',
            s: translate$4,
            ss: translate$4,
            m: translate$4,
            mm: translate$4,
            h: translate$4,
            hh: translate$4,
            d: translate$4,
            dd: translate$4,
            M: translate$4,
            MM: translate$4,
            y: translate$4,
            yy: translate$4
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('hy-am', {
        months: {
            format: 'հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի'.split('_'),
            standalone: 'հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր'.split('_')
        },
        monthsShort: 'հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ'.split('_'),
        weekdays: 'կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ'.split('_'),
        weekdaysShort: 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'),
        weekdaysMin: 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY թ.',
            LLL: 'D MMMM YYYY թ., HH:mm',
            LLLL: 'dddd, D MMMM YYYY թ., HH:mm'
        },
        calendar: {
            sameDay: '[այսօր] LT',
            nextDay: '[վաղը] LT',
            lastDay: '[երեկ] LT',
            nextWeek: function () {
                return 'dddd [օրը ժամը] LT';
            },
            lastWeek: function () {
                return '[անցած] dddd [օրը ժամը] LT';
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s հետո',
            past: '%s առաջ',
            s: 'մի քանի վայրկյան',
            ss: '%d վայրկյան',
            m: 'րոպե',
            mm: '%d րոպե',
            h: 'ժամ',
            hh: '%d ժամ',
            d: 'օր',
            dd: '%d օր',
            M: 'ամիս',
            MM: '%d ամիս',
            y: 'տարի',
            yy: '%d տարի'
        },
        meridiemParse: /գիշերվա|առավոտվա|ցերեկվա|երեկոյան/,
        isPM: function (input) {
            return /^(ցերեկվա|երեկոյան)$/.test(input);
        },
        meridiem: function (hour) {
            if (hour < 4) {
                return 'գիշերվա';
            } else if (hour < 12) {
                return 'առավոտվա';
            } else if (hour < 17) {
                return 'ցերեկվա';
            } else {
                return 'երեկոյան';
            }
        },
        dayOfMonthOrdinalParse: /\d{1,2}|\d{1,2}-(ին|րդ)/,
        ordinal: function (number, period) {
            switch (period) {
                case 'DDD':
                case 'w':
                case 'W':
                case 'DDDo':
                    if (number === 1) {
                        return number + '-ին';
                    }
                    return number + '-րդ';
                default:
                    return number;
            }
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('id', {
        months: 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember'.split('_'),
        monthsShort: 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Agt_Sep_Okt_Nov_Des'.split('_'),
        weekdays: 'Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu'.split('_'),
        weekdaysShort: 'Min_Sen_Sel_Rab_Kam_Jum_Sab'.split('_'),
        weekdaysMin: 'Mg_Sn_Sl_Rb_Km_Jm_Sb'.split('_'),
        longDateFormat: {
            LT: 'HH.mm',
            LTS: 'HH.mm.ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY [pukul] HH.mm',
            LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm'
        },
        meridiemParse: /pagi|siang|sore|malam/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'pagi') {
                return hour;
            } else if (meridiem === 'siang') {
                return hour >= 11 ? hour : hour + 12;
            } else if (meridiem === 'sore' || meridiem === 'malam') {
                return hour + 12;
            }
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours < 11) {
                return 'pagi';
            } else if (hours < 15) {
                return 'siang';
            } else if (hours < 19) {
                return 'sore';
            } else {
                return 'malam';
            }
        },
        calendar: {
            sameDay: '[Hari ini pukul] LT',
            nextDay: '[Besok pukul] LT',
            nextWeek: 'dddd [pukul] LT',
            lastDay: '[Kemarin pukul] LT',
            lastWeek: 'dddd [lalu pukul] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'dalam %s',
            past: '%s yang lalu',
            s: 'beberapa detik',
            ss: '%d detik',
            m: 'semenit',
            mm: '%d menit',
            h: 'sejam',
            hh: '%d jam',
            d: 'sehari',
            dd: '%d hari',
            M: 'sebulan',
            MM: '%d bulan',
            y: 'setahun',
            yy: '%d tahun'
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    function plural$2(n) {
        if (n % 100 === 11) {
            return true;
        } else if (n % 10 === 1) {
            return false;
        }
        return true;
    }
    function translate$5(number, withoutSuffix, key, isFuture) {
        var result = number + ' ';
        switch (key) {
            case 's':
                return withoutSuffix || isFuture ? 'nokkrar sekúndur' : 'nokkrum sekúndum';
            case 'ss':
                if (plural$2(number)) {
                    return result + (withoutSuffix || isFuture ? 'sekúndur' : 'sekúndum');
                }
                return result + 'sekúnda';
            case 'm':
                return withoutSuffix ? 'mínúta' : 'mínútu';
            case 'mm':
                if (plural$2(number)) {
                    return result + (withoutSuffix || isFuture ? 'mínútur' : 'mínútum');
                } else if (withoutSuffix) {
                    return result + 'mínúta';
                }
                return result + 'mínútu';
            case 'hh':
                if (plural$2(number)) {
                    return result + (withoutSuffix || isFuture ? 'klukkustundir' : 'klukkustundum');
                }
                return result + 'klukkustund';
            case 'd':
                if (withoutSuffix) {
                    return 'dagur';
                }
                return isFuture ? 'dag' : 'degi';
            case 'dd':
                if (plural$2(number)) {
                    if (withoutSuffix) {
                        return result + 'dagar';
                    }
                    return result + (isFuture ? 'daga' : 'dögum');
                } else if (withoutSuffix) {
                    return result + 'dagur';
                }
                return result + (isFuture ? 'dag' : 'degi');
            case 'M':
                if (withoutSuffix) {
                    return 'mánuður';
                }
                return isFuture ? 'mánuð' : 'mánuði';
            case 'MM':
                if (plural$2(number)) {
                    if (withoutSuffix) {
                        return result + 'mánuðir';
                    }
                    return result + (isFuture ? 'mánuði' : 'mánuðum');
                } else if (withoutSuffix) {
                    return result + 'mánuður';
                }
                return result + (isFuture ? 'mánuð' : 'mánuði');
            case 'y':
                return withoutSuffix || isFuture ? 'ár' : 'ári';
            case 'yy':
                if (plural$2(number)) {
                    return result + (withoutSuffix || isFuture ? 'ár' : 'árum');
                }
                return result + (withoutSuffix || isFuture ? 'ár' : 'ári');
        }
    }

    hooks.defineLocale('is', {
        months: 'janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember'.split('_'),
        monthsShort: 'jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des'.split('_'),
        weekdays: 'sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur'.split('_'),
        weekdaysShort: 'sun_mán_þri_mið_fim_fös_lau'.split('_'),
        weekdaysMin: 'Su_Má_Þr_Mi_Fi_Fö_La'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY [kl.] H:mm',
            LLLL: 'dddd, D. MMMM YYYY [kl.] H:mm'
        },
        calendar: {
            sameDay: '[í dag kl.] LT',
            nextDay: '[á morgun kl.] LT',
            nextWeek: 'dddd [kl.] LT',
            lastDay: '[í gær kl.] LT',
            lastWeek: '[síðasta] dddd [kl.] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'eftir %s',
            past: 'fyrir %s síðan',
            s: translate$5,
            ss: translate$5,
            m: translate$5,
            mm: translate$5,
            h: 'klukkustund',
            hh: translate$5,
            d: translate$5,
            dd: translate$5,
            M: translate$5,
            MM: translate$5,
            y: translate$5,
            yy: translate$5
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('it', {
        months: 'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split('_'),
        monthsShort: 'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'),
        weekdays: 'domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato'.split('_'),
        weekdaysShort: 'dom_lun_mar_mer_gio_ven_sab'.split('_'),
        weekdaysMin: 'do_lu_ma_me_gi_ve_sa'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Oggi alle] LT',
            nextDay: '[Domani alle] LT',
            nextWeek: 'dddd [alle] LT',
            lastDay: '[Ieri alle] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[la scorsa] dddd [alle] LT';
                    default:
                        return '[lo scorso] dddd [alle] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: function (s) {
                return ((/^[0-9].+$/).test(s) ? 'tra' : 'in') + ' ' + s;
            },
            past: '%s fa',
            s: 'alcuni secondi',
            ss: '%d secondi',
            m: 'un minuto',
            mm: '%d minuti',
            h: 'un\'ora',
            hh: '%d ore',
            d: 'un giorno',
            dd: '%d giorni',
            M: 'un mese',
            MM: '%d mesi',
            y: 'un anno',
            yy: '%d anni'
        },
        dayOfMonthOrdinalParse: /\d{1,2}º/,
        ordinal: '%dº',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('ja', {
        months: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
        monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
        weekdays: '日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日'.split('_'),
        weekdaysShort: '日_月_火_水_木_金_土'.split('_'),
        weekdaysMin: '日_月_火_水_木_金_土'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'YYYY/MM/DD',
            LL: 'YYYY年M月D日',
            LLL: 'YYYY年M月D日 HH:mm',
            LLLL: 'YYYY年M月D日 dddd HH:mm',
            l: 'YYYY/MM/DD',
            ll: 'YYYY年M月D日',
            lll: 'YYYY年M月D日 HH:mm',
            llll: 'YYYY年M月D日(ddd) HH:mm'
        },
        meridiemParse: /午前|午後/i,
        isPM: function (input) {
            return input === '午後';
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 12) {
                return '午前';
            } else {
                return '午後';
            }
        },
        calendar: {
            sameDay: '[今日] LT',
            nextDay: '[明日] LT',
            nextWeek: function (now) {
                if (now.week() < this.week()) {
                    return '[来週]dddd LT';
                } else {
                    return 'dddd LT';
                }
            },
            lastDay: '[昨日] LT',
            lastWeek: function (now) {
                if (this.week() < now.week()) {
                    return '[先週]dddd LT';
                } else {
                    return 'dddd LT';
                }
            },
            sameElse: 'L'
        },
        dayOfMonthOrdinalParse: /\d{1,2}日/,
        ordinal: function (number, period) {
            switch (period) {
                case 'd':
                case 'D':
                case 'DDD':
                    return number + '日';
                default:
                    return number;
            }
        },
        relativeTime: {
            future: '%s後',
            past: '%s前',
            s: '数秒',
            ss: '%d秒',
            m: '1分',
            mm: '%d分',
            h: '1時間',
            hh: '%d時間',
            d: '1日',
            dd: '%d日',
            M: '1ヶ月',
            MM: '%dヶ月',
            y: '1年',
            yy: '%d年'
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('jv', {
        months: 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_Nopember_Desember'.split('_'),
        monthsShort: 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nop_Des'.split('_'),
        weekdays: 'Minggu_Senen_Seloso_Rebu_Kemis_Jemuwah_Septu'.split('_'),
        weekdaysShort: 'Min_Sen_Sel_Reb_Kem_Jem_Sep'.split('_'),
        weekdaysMin: 'Mg_Sn_Sl_Rb_Km_Jm_Sp'.split('_'),
        longDateFormat: {
            LT: 'HH.mm',
            LTS: 'HH.mm.ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY [pukul] HH.mm',
            LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm'
        },
        meridiemParse: /enjing|siyang|sonten|ndalu/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'enjing') {
                return hour;
            } else if (meridiem === 'siyang') {
                return hour >= 11 ? hour : hour + 12;
            } else if (meridiem === 'sonten' || meridiem === 'ndalu') {
                return hour + 12;
            }
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours < 11) {
                return 'enjing';
            } else if (hours < 15) {
                return 'siyang';
            } else if (hours < 19) {
                return 'sonten';
            } else {
                return 'ndalu';
            }
        },
        calendar: {
            sameDay: '[Dinten puniko pukul] LT',
            nextDay: '[Mbenjang pukul] LT',
            nextWeek: 'dddd [pukul] LT',
            lastDay: '[Kala wingi pukul] LT',
            lastWeek: 'dddd [kepengker pukul] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'wonten ing %s',
            past: '%s ingkang kepengker',
            s: 'sawetawis detik',
            ss: '%d detik',
            m: 'setunggal menit',
            mm: '%d menit',
            h: 'setunggal jam',
            hh: '%d jam',
            d: 'sedinten',
            dd: '%d dinten',
            M: 'sewulan',
            MM: '%d wulan',
            y: 'setaun',
            yy: '%d taun'
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('ka', {
        months: {
            standalone: 'იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი'.split('_'),
            format: 'იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს'.split('_')
        },
        monthsShort: 'იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ'.split('_'),
        weekdays: {
            standalone: 'კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი'.split('_'),
            format: 'კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს'.split('_'),
            isFormat: /(წინა|შემდეგ)/
        },
        weekdaysShort: 'კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ'.split('_'),
        weekdaysMin: 'კვ_ორ_სა_ოთ_ხუ_პა_შა'.split('_'),
        longDateFormat: {
            LT: 'h:mm A',
            LTS: 'h:mm:ss A',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY h:mm A',
            LLLL: 'dddd, D MMMM YYYY h:mm A'
        },
        calendar: {
            sameDay: '[დღეს] LT[-ზე]',
            nextDay: '[ხვალ] LT[-ზე]',
            lastDay: '[გუშინ] LT[-ზე]',
            nextWeek: '[შემდეგ] dddd LT[-ზე]',
            lastWeek: '[წინა] dddd LT-ზე',
            sameElse: 'L'
        },
        relativeTime: {
            future: function (s) {
                return (/(წამი|წუთი|საათი|წელი)/).test(s) ?
                    s.replace(/ი$/, 'ში') :
                    s + 'ში';
            },
            past: function (s) {
                if ((/(წამი|წუთი|საათი|დღე|თვე)/).test(s)) {
                    return s.replace(/(ი|ე)$/, 'ის წინ');
                }
                if ((/წელი/).test(s)) {
                    return s.replace(/წელი$/, 'წლის წინ');
                }
            },
            s: 'რამდენიმე წამი',
            ss: '%d წამი',
            m: 'წუთი',
            mm: '%d წუთი',
            h: 'საათი',
            hh: '%d საათი',
            d: 'დღე',
            dd: '%d დღე',
            M: 'თვე',
            MM: '%d თვე',
            y: 'წელი',
            yy: '%d წელი'
        },
        dayOfMonthOrdinalParse: /0|1-ლი|მე-\d{1,2}|\d{1,2}-ე/,
        ordinal: function (number) {
            if (number === 0) {
                return number;
            }
            if (number === 1) {
                return number + '-ლი';
            }
            if ((number < 20) || (number <= 100 && (number % 20 === 0)) || (number % 100 === 0)) {
                return 'მე-' + number;
            }
            return number + '-ე';
        },
        week: {
            dow: 1,
            doy: 7
        }
    });

    //! moment.js locale configuration

    var suffixes$1 = {
        0: '-ші',
        1: '-ші',
        2: '-ші',
        3: '-ші',
        4: '-ші',
        5: '-ші',
        6: '-шы',
        7: '-ші',
        8: '-ші',
        9: '-шы',
        10: '-шы',
        20: '-шы',
        30: '-шы',
        40: '-шы',
        50: '-ші',
        60: '-шы',
        70: '-ші',
        80: '-ші',
        90: '-шы',
        100: '-ші'
    };

    hooks.defineLocale('kk', {
        months: 'қаңтар_ақпан_наурыз_сәуір_мамыр_маусым_шілде_тамыз_қыркүйек_қазан_қараша_желтоқсан'.split('_'),
        monthsShort: 'қаң_ақп_нау_сәу_мам_мау_шіл_там_қыр_қаз_қар_жел'.split('_'),
        weekdays: 'жексенбі_дүйсенбі_сейсенбі_сәрсенбі_бейсенбі_жұма_сенбі'.split('_'),
        weekdaysShort: 'жек_дүй_сей_сәр_бей_жұм_сен'.split('_'),
        weekdaysMin: 'жк_дй_сй_ср_бй_жм_сн'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Бүгін сағат] LT',
            nextDay: '[Ертең сағат] LT',
            nextWeek: 'dddd [сағат] LT',
            lastDay: '[Кеше сағат] LT',
            lastWeek: '[Өткен аптаның] dddd [сағат] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s ішінде',
            past: '%s бұрын',
            s: 'бірнеше секунд',
            ss: '%d секунд',
            m: 'бір минут',
            mm: '%d минут',
            h: 'бір сағат',
            hh: '%d сағат',
            d: 'бір күн',
            dd: '%d күн',
            M: 'бір ай',
            MM: '%d ай',
            y: 'бір жыл',
            yy: '%d жыл'
        },
        dayOfMonthOrdinalParse: /\d{1,2}-(ші|шы)/,
        ordinal: function (number) {
            var a = number % 10,
                b = number >= 100 ? 100 : null;
            return number + (suffixes$1[number] || suffixes$1[a] || suffixes$1[b]);
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var symbolMap$8 = {
        '1': '១',
        '2': '២',
        '3': '៣',
        '4': '៤',
        '5': '៥',
        '6': '៦',
        '7': '៧',
        '8': '៨',
        '9': '៩',
        '0': '០'
    }, numberMap$7 = {
        '១': '1',
        '២': '2',
        '៣': '3',
        '៤': '4',
        '៥': '5',
        '៦': '6',
        '៧': '7',
        '៨': '8',
        '៩': '9',
        '០': '0'
    };

    hooks.defineLocale('km', {
        months: 'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split(
            '_'
        ),
        monthsShort: 'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split(
            '_'
        ),
        weekdays: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'),
        weekdaysShort: 'អា_ច_អ_ព_ព្រ_សុ_ស'.split('_'),
        weekdaysMin: 'អា_ច_អ_ព_ព្រ_សុ_ស'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        meridiemParse: /ព្រឹក|ល្ងាច/,
        isPM: function (input) {
            return input === 'ល្ងាច';
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 12) {
                return 'ព្រឹក';
            } else {
                return 'ល្ងាច';
            }
        },
        calendar: {
            sameDay: '[ថ្ងៃនេះ ម៉ោង] LT',
            nextDay: '[ស្អែក ម៉ោង] LT',
            nextWeek: 'dddd [ម៉ោង] LT',
            lastDay: '[ម្សិលមិញ ម៉ោង] LT',
            lastWeek: 'dddd [សប្តាហ៍មុន] [ម៉ោង] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%sទៀត',
            past: '%sមុន',
            s: 'ប៉ុន្មានវិនាទី',
            ss: '%d វិនាទី',
            m: 'មួយនាទី',
            mm: '%d នាទី',
            h: 'មួយម៉ោង',
            hh: '%d ម៉ោង',
            d: 'មួយថ្ងៃ',
            dd: '%d ថ្ងៃ',
            M: 'មួយខែ',
            MM: '%d ខែ',
            y: 'មួយឆ្នាំ',
            yy: '%d ឆ្នាំ'
        },
        dayOfMonthOrdinalParse: /ទី\d{1,2}/,
        ordinal: 'ទី%d',
        preparse: function (string) {
            return string.replace(/[១២៣៤៥៦៧៨៩០]/g, function (match) {
                return numberMap$7[match];
            });
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return symbolMap$8[match];
            });
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4 // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var symbolMap$9 = {
        '1': '೧',
        '2': '೨',
        '3': '೩',
        '4': '೪',
        '5': '೫',
        '6': '೬',
        '7': '೭',
        '8': '೮',
        '9': '೯',
        '0': '೦'
    },
        numberMap$8 = {
            '೧': '1',
            '೨': '2',
            '೩': '3',
            '೪': '4',
            '೫': '5',
            '೬': '6',
            '೭': '7',
            '೮': '8',
            '೯': '9',
            '೦': '0'
        };

    hooks.defineLocale('kn', {
        months: 'ಜನವರಿ_ಫೆಬ್ರವರಿ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂಬರ್_ಅಕ್ಟೋಬರ್_ನವೆಂಬರ್_ಡಿಸೆಂಬರ್'.split('_'),
        monthsShort: 'ಜನ_ಫೆಬ್ರ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂ_ಅಕ್ಟೋ_ನವೆಂ_ಡಿಸೆಂ'.split('_'),
        monthsParseExact: true,
        weekdays: 'ಭಾನುವಾರ_ಸೋಮವಾರ_ಮಂಗಳವಾರ_ಬುಧವಾರ_ಗುರುವಾರ_ಶುಕ್ರವಾರ_ಶನಿವಾರ'.split('_'),
        weekdaysShort: 'ಭಾನು_ಸೋಮ_ಮಂಗಳ_ಬುಧ_ಗುರು_ಶುಕ್ರ_ಶನಿ'.split('_'),
        weekdaysMin: 'ಭಾ_ಸೋ_ಮಂ_ಬು_ಗು_ಶು_ಶ'.split('_'),
        longDateFormat: {
            LT: 'A h:mm',
            LTS: 'A h:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY, A h:mm',
            LLLL: 'dddd, D MMMM YYYY, A h:mm'
        },
        calendar: {
            sameDay: '[ಇಂದು] LT',
            nextDay: '[ನಾಳೆ] LT',
            nextWeek: 'dddd, LT',
            lastDay: '[ನಿನ್ನೆ] LT',
            lastWeek: '[ಕೊನೆಯ] dddd, LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s ನಂತರ',
            past: '%s ಹಿಂದೆ',
            s: 'ಕೆಲವು ಕ್ಷಣಗಳು',
            ss: '%d ಸೆಕೆಂಡುಗಳು',
            m: 'ಒಂದು ನಿಮಿಷ',
            mm: '%d ನಿಮಿಷ',
            h: 'ಒಂದು ಗಂಟೆ',
            hh: '%d ಗಂಟೆ',
            d: 'ಒಂದು ದಿನ',
            dd: '%d ದಿನ',
            M: 'ಒಂದು ತಿಂಗಳು',
            MM: '%d ತಿಂಗಳು',
            y: 'ಒಂದು ವರ್ಷ',
            yy: '%d ವರ್ಷ'
        },
        preparse: function (string) {
            return string.replace(/[೧೨೩೪೫೬೭೮೯೦]/g, function (match) {
                return numberMap$8[match];
            });
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return symbolMap$9[match];
            });
        },
        meridiemParse: /ರಾತ್ರಿ|ಬೆಳಿಗ್ಗೆ|ಮಧ್ಯಾಹ್ನ|ಸಂಜೆ/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'ರಾತ್ರಿ') {
                return hour < 4 ? hour : hour + 12;
            } else if (meridiem === 'ಬೆಳಿಗ್ಗೆ') {
                return hour;
            } else if (meridiem === 'ಮಧ್ಯಾಹ್ನ') {
                return hour >= 10 ? hour : hour + 12;
            } else if (meridiem === 'ಸಂಜೆ') {
                return hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'ರಾತ್ರಿ';
            } else if (hour < 10) {
                return 'ಬೆಳಿಗ್ಗೆ';
            } else if (hour < 17) {
                return 'ಮಧ್ಯಾಹ್ನ';
            } else if (hour < 20) {
                return 'ಸಂಜೆ';
            } else {
                return 'ರಾತ್ರಿ';
            }
        },
        dayOfMonthOrdinalParse: /\d{1,2}(ನೇ)/,
        ordinal: function (number) {
            return number + 'ನೇ';
        },
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 6  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('ko', {
        months: '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'),
        monthsShort: '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'),
        weekdays: '일요일_월요일_화요일_수요일_목요일_금요일_토요일'.split('_'),
        weekdaysShort: '일_월_화_수_목_금_토'.split('_'),
        weekdaysMin: '일_월_화_수_목_금_토'.split('_'),
        longDateFormat: {
            LT: 'A h:mm',
            LTS: 'A h:mm:ss',
            L: 'YYYY.MM.DD.',
            LL: 'YYYY년 MMMM D일',
            LLL: 'YYYY년 MMMM D일 A h:mm',
            LLLL: 'YYYY년 MMMM D일 dddd A h:mm',
            l: 'YYYY.MM.DD.',
            ll: 'YYYY년 MMMM D일',
            lll: 'YYYY년 MMMM D일 A h:mm',
            llll: 'YYYY년 MMMM D일 dddd A h:mm'
        },
        calendar: {
            sameDay: '오늘 LT',
            nextDay: '내일 LT',
            nextWeek: 'dddd LT',
            lastDay: '어제 LT',
            lastWeek: '지난주 dddd LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s 후',
            past: '%s 전',
            s: '몇 초',
            ss: '%d초',
            m: '1분',
            mm: '%d분',
            h: '한 시간',
            hh: '%d시간',
            d: '하루',
            dd: '%d일',
            M: '한 달',
            MM: '%d달',
            y: '일 년',
            yy: '%d년'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(일|월|주)/,
        ordinal: function (number, period) {
            switch (period) {
                case 'd':
                case 'D':
                case 'DDD':
                    return number + '일';
                case 'M':
                    return number + '월';
                case 'w':
                case 'W':
                    return number + '주';
                default:
                    return number;
            }
        },
        meridiemParse: /오전|오후/,
        isPM: function (token) {
            return token === '오후';
        },
        meridiem: function (hour, minute, isUpper) {
            return hour < 12 ? '오전' : '오후';
        }
    });

    //! moment.js locale configuration

    var suffixes$2 = {
        0: '-чү',
        1: '-чи',
        2: '-чи',
        3: '-чү',
        4: '-чү',
        5: '-чи',
        6: '-чы',
        7: '-чи',
        8: '-чи',
        9: '-чу',
        10: '-чу',
        20: '-чы',
        30: '-чу',
        40: '-чы',
        50: '-чү',
        60: '-чы',
        70: '-чи',
        80: '-чи',
        90: '-чу',
        100: '-чү'
    };

    hooks.defineLocale('ky', {
        months: 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'),
        monthsShort: 'янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_'),
        weekdays: 'Жекшемби_Дүйшөмбү_Шейшемби_Шаршемби_Бейшемби_Жума_Ишемби'.split('_'),
        weekdaysShort: 'Жек_Дүй_Шей_Шар_Бей_Жум_Ише'.split('_'),
        weekdaysMin: 'Жк_Дй_Шй_Шр_Бй_Жм_Иш'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Бүгүн саат] LT',
            nextDay: '[Эртең саат] LT',
            nextWeek: 'dddd [саат] LT',
            lastDay: '[Кече саат] LT',
            lastWeek: '[Өткен аптанын] dddd [күнү] [саат] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s ичинде',
            past: '%s мурун',
            s: 'бирнече секунд',
            ss: '%d секунд',
            m: 'бир мүнөт',
            mm: '%d мүнөт',
            h: 'бир саат',
            hh: '%d саат',
            d: 'бир күн',
            dd: '%d күн',
            M: 'бир ай',
            MM: '%d ай',
            y: 'бир жыл',
            yy: '%d жыл'
        },
        dayOfMonthOrdinalParse: /\d{1,2}-(чи|чы|чү|чу)/,
        ordinal: function (number) {
            var a = number % 10,
                b = number >= 100 ? 100 : null;
            return number + (suffixes$2[number] || suffixes$2[a] || suffixes$2[b]);
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    function processRelativeTime$5(number, withoutSuffix, key, isFuture) {
        var format = {
            'm': ['eng Minutt', 'enger Minutt'],
            'h': ['eng Stonn', 'enger Stonn'],
            'd': ['een Dag', 'engem Dag'],
            'M': ['ee Mount', 'engem Mount'],
            'y': ['ee Joer', 'engem Joer']
        };
        return withoutSuffix ? format[key][0] : format[key][1];
    }
    function processFutureTime(string) {
        var number = string.substr(0, string.indexOf(' '));
        if (eifelerRegelAppliesToNumber(number)) {
            return 'a ' + string;
        }
        return 'an ' + string;
    }
    function processPastTime(string) {
        var number = string.substr(0, string.indexOf(' '));
        if (eifelerRegelAppliesToNumber(number)) {
            return 'viru ' + string;
        }
        return 'virun ' + string;
    }
    /**
     * Returns true if the word before the given number loses the '-n' ending.
     * e.g. 'an 10 Deeg' but 'a 5 Deeg'
     *
     * @param number {integer}
     * @returns {boolean}
     */
    function eifelerRegelAppliesToNumber(number) {
        number = parseInt(number, 10);
        if (isNaN(number)) {
            return false;
        }
        if (number < 0) {
            // Negative Number --> always true
            return true;
        } else if (number < 10) {
            // Only 1 digit
            if (4 <= number && number <= 7) {
                return true;
            }
            return false;
        } else if (number < 100) {
            // 2 digits
            var lastDigit = number % 10, firstDigit = number / 10;
            if (lastDigit === 0) {
                return eifelerRegelAppliesToNumber(firstDigit);
            }
            return eifelerRegelAppliesToNumber(lastDigit);
        } else if (number < 10000) {
            // 3 or 4 digits --> recursively check first digit
            while (number >= 10) {
                number = number / 10;
            }
            return eifelerRegelAppliesToNumber(number);
        } else {
            // Anything larger than 4 digits: recursively check first n-3 digits
            number = number / 1000;
            return eifelerRegelAppliesToNumber(number);
        }
    }

    hooks.defineLocale('lb', {
        months: 'Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),
        monthsShort: 'Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'),
        monthsParseExact: true,
        weekdays: 'Sonndeg_Méindeg_Dënschdeg_Mëttwoch_Donneschdeg_Freideg_Samschdeg'.split('_'),
        weekdaysShort: 'So._Mé._Dë._Më._Do._Fr._Sa.'.split('_'),
        weekdaysMin: 'So_Mé_Dë_Më_Do_Fr_Sa'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'H:mm [Auer]',
            LTS: 'H:mm:ss [Auer]',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm [Auer]',
            LLLL: 'dddd, D. MMMM YYYY H:mm [Auer]'
        },
        calendar: {
            sameDay: '[Haut um] LT',
            sameElse: 'L',
            nextDay: '[Muer um] LT',
            nextWeek: 'dddd [um] LT',
            lastDay: '[Gëschter um] LT',
            lastWeek: function () {
                // Different date string for 'Dënschdeg' (Tuesday) and 'Donneschdeg' (Thursday) due to phonological rule
                switch (this.day()) {
                    case 2:
                    case 4:
                        return '[Leschten] dddd [um] LT';
                    default:
                        return '[Leschte] dddd [um] LT';
                }
            }
        },
        relativeTime: {
            future: processFutureTime,
            past: processPastTime,
            s: 'e puer Sekonnen',
            ss: '%d Sekonnen',
            m: processRelativeTime$5,
            mm: '%d Minutten',
            h: processRelativeTime$5,
            hh: '%d Stonnen',
            d: processRelativeTime$5,
            dd: '%d Deeg',
            M: processRelativeTime$5,
            MM: '%d Méint',
            y: processRelativeTime$5,
            yy: '%d Joer'
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('lo', {
        months: 'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split('_'),
        monthsShort: 'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split('_'),
        weekdays: 'ອາທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'),
        weekdaysShort: 'ທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'),
        weekdaysMin: 'ທ_ຈ_ອຄ_ພ_ພຫ_ສກ_ສ'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'ວັນdddd D MMMM YYYY HH:mm'
        },
        meridiemParse: /ຕອນເຊົ້າ|ຕອນແລງ/,
        isPM: function (input) {
            return input === 'ຕອນແລງ';
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 12) {
                return 'ຕອນເຊົ້າ';
            } else {
                return 'ຕອນແລງ';
            }
        },
        calendar: {
            sameDay: '[ມື້ນີ້ເວລາ] LT',
            nextDay: '[ມື້ອື່ນເວລາ] LT',
            nextWeek: '[ວັນ]dddd[ໜ້າເວລາ] LT',
            lastDay: '[ມື້ວານນີ້ເວລາ] LT',
            lastWeek: '[ວັນ]dddd[ແລ້ວນີ້ເວລາ] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'ອີກ %s',
            past: '%sຜ່ານມາ',
            s: 'ບໍ່ເທົ່າໃດວິນາທີ',
            ss: '%d ວິນາທີ',
            m: '1 ນາທີ',
            mm: '%d ນາທີ',
            h: '1 ຊົ່ວໂມງ',
            hh: '%d ຊົ່ວໂມງ',
            d: '1 ມື້',
            dd: '%d ມື້',
            M: '1 ເດືອນ',
            MM: '%d ເດືອນ',
            y: '1 ປີ',
            yy: '%d ປີ'
        },
        dayOfMonthOrdinalParse: /(ທີ່)\d{1,2}/,
        ordinal: function (number) {
            return 'ທີ່' + number;
        }
    });

    //! moment.js locale configuration

    var units = {
        'ss': 'sekundė_sekundžių_sekundes',
        'm': 'minutė_minutės_minutę',
        'mm': 'minutės_minučių_minutes',
        'h': 'valanda_valandos_valandą',
        'hh': 'valandos_valandų_valandas',
        'd': 'diena_dienos_dieną',
        'dd': 'dienos_dienų_dienas',
        'M': 'mėnuo_mėnesio_mėnesį',
        'MM': 'mėnesiai_mėnesių_mėnesius',
        'y': 'metai_metų_metus',
        'yy': 'metai_metų_metus'
    };
    function translateSeconds(number, withoutSuffix, key, isFuture) {
        if (withoutSuffix) {
            return 'kelios sekundės';
        } else {
            return isFuture ? 'kelių sekundžių' : 'kelias sekundes';
        }
    }
    function translateSingular(number, withoutSuffix, key, isFuture) {
        return withoutSuffix ? forms(key)[0] : (isFuture ? forms(key)[1] : forms(key)[2]);
    }
    function special(number) {
        return number % 10 === 0 || (number > 10 && number < 20);
    }
    function forms(key) {
        return units[key].split('_');
    }
    function translate$6(number, withoutSuffix, key, isFuture) {
        var result = number + ' ';
        if (number === 1) {
            return result + translateSingular(number, withoutSuffix, key[0], isFuture);
        } else if (withoutSuffix) {
            return result + (special(number) ? forms(key)[1] : forms(key)[0]);
        } else {
            if (isFuture) {
                return result + forms(key)[1];
            } else {
                return result + (special(number) ? forms(key)[1] : forms(key)[2]);
            }
        }
    }
    hooks.defineLocale('lt', {
        months: {
            format: 'sausio_vasario_kovo_balandžio_gegužės_birželio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio'.split('_'),
            standalone: 'sausis_vasaris_kovas_balandis_gegužė_birželis_liepa_rugpjūtis_rugsėjis_spalis_lapkritis_gruodis'.split('_'),
            isFormat: /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?|MMMM?(\[[^\[\]]*\]|\s)+D[oD]?/
        },
        monthsShort: 'sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd'.split('_'),
        weekdays: {
            format: 'sekmadienį_pirmadienį_antradienį_trečiadienį_ketvirtadienį_penktadienį_šeštadienį'.split('_'),
            standalone: 'sekmadienis_pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis'.split('_'),
            isFormat: /dddd HH:mm/
        },
        weekdaysShort: 'Sek_Pir_Ant_Tre_Ket_Pen_Šeš'.split('_'),
        weekdaysMin: 'S_P_A_T_K_Pn_Š'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'YYYY-MM-DD',
            LL: 'YYYY [m.] MMMM D [d.]',
            LLL: 'YYYY [m.] MMMM D [d.], HH:mm [val.]',
            LLLL: 'YYYY [m.] MMMM D [d.], dddd, HH:mm [val.]',
            l: 'YYYY-MM-DD',
            ll: 'YYYY [m.] MMMM D [d.]',
            lll: 'YYYY [m.] MMMM D [d.], HH:mm [val.]',
            llll: 'YYYY [m.] MMMM D [d.], ddd, HH:mm [val.]'
        },
        calendar: {
            sameDay: '[Šiandien] LT',
            nextDay: '[Rytoj] LT',
            nextWeek: 'dddd LT',
            lastDay: '[Vakar] LT',
            lastWeek: '[Praėjusį] dddd LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'po %s',
            past: 'prieš %s',
            s: translateSeconds,
            ss: translate$6,
            m: translateSingular,
            mm: translate$6,
            h: translateSingular,
            hh: translate$6,
            d: translateSingular,
            dd: translate$6,
            M: translateSingular,
            MM: translate$6,
            y: translateSingular,
            yy: translate$6
        },
        dayOfMonthOrdinalParse: /\d{1,2}-oji/,
        ordinal: function (number) {
            return number + '-oji';
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var units$1 = {
        'ss': 'sekundes_sekundēm_sekunde_sekundes'.split('_'),
        'm': 'minūtes_minūtēm_minūte_minūtes'.split('_'),
        'mm': 'minūtes_minūtēm_minūte_minūtes'.split('_'),
        'h': 'stundas_stundām_stunda_stundas'.split('_'),
        'hh': 'stundas_stundām_stunda_stundas'.split('_'),
        'd': 'dienas_dienām_diena_dienas'.split('_'),
        'dd': 'dienas_dienām_diena_dienas'.split('_'),
        'M': 'mēneša_mēnešiem_mēnesis_mēneši'.split('_'),
        'MM': 'mēneša_mēnešiem_mēnesis_mēneši'.split('_'),
        'y': 'gada_gadiem_gads_gadi'.split('_'),
        'yy': 'gada_gadiem_gads_gadi'.split('_')
    };
    /**
     * @param withoutSuffix boolean true = a length of time; false = before/after a period of time.
     */
    function format$1(forms, number, withoutSuffix) {
        if (withoutSuffix) {
            // E.g. "21 minūte", "3 minūtes".
            return number % 10 === 1 && number % 100 !== 11 ? forms[2] : forms[3];
        } else {
            // E.g. "21 minūtes" as in "pēc 21 minūtes".
            // E.g. "3 minūtēm" as in "pēc 3 minūtēm".
            return number % 10 === 1 && number % 100 !== 11 ? forms[0] : forms[1];
        }
    }
    function relativeTimeWithPlural$1(number, withoutSuffix, key) {
        return number + ' ' + format$1(units$1[key], number, withoutSuffix);
    }
    function relativeTimeWithSingular(number, withoutSuffix, key) {
        return format$1(units$1[key], number, withoutSuffix);
    }
    function relativeSeconds(number, withoutSuffix) {
        return withoutSuffix ? 'dažas sekundes' : 'dažām sekundēm';
    }

    hooks.defineLocale('lv', {
        months: 'janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris'.split('_'),
        monthsShort: 'jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec'.split('_'),
        weekdays: 'svētdiena_pirmdiena_otrdiena_trešdiena_ceturtdiena_piektdiena_sestdiena'.split('_'),
        weekdaysShort: 'Sv_P_O_T_C_Pk_S'.split('_'),
        weekdaysMin: 'Sv_P_O_T_C_Pk_S'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY.',
            LL: 'YYYY. [gada] D. MMMM',
            LLL: 'YYYY. [gada] D. MMMM, HH:mm',
            LLLL: 'YYYY. [gada] D. MMMM, dddd, HH:mm'
        },
        calendar: {
            sameDay: '[Šodien pulksten] LT',
            nextDay: '[Rīt pulksten] LT',
            nextWeek: 'dddd [pulksten] LT',
            lastDay: '[Vakar pulksten] LT',
            lastWeek: '[Pagājušā] dddd [pulksten] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'pēc %s',
            past: 'pirms %s',
            s: relativeSeconds,
            ss: relativeTimeWithPlural$1,
            m: relativeTimeWithSingular,
            mm: relativeTimeWithPlural$1,
            h: relativeTimeWithSingular,
            hh: relativeTimeWithPlural$1,
            d: relativeTimeWithSingular,
            dd: relativeTimeWithPlural$1,
            M: relativeTimeWithSingular,
            MM: relativeTimeWithPlural$1,
            y: relativeTimeWithSingular,
            yy: relativeTimeWithPlural$1
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var translator = {
        words: { //Different grammatical cases
            ss: ['sekund', 'sekunda', 'sekundi'],
            m: ['jedan minut', 'jednog minuta'],
            mm: ['minut', 'minuta', 'minuta'],
            h: ['jedan sat', 'jednog sata'],
            hh: ['sat', 'sata', 'sati'],
            dd: ['dan', 'dana', 'dana'],
            MM: ['mjesec', 'mjeseca', 'mjeseci'],
            yy: ['godina', 'godine', 'godina']
        },
        correctGrammaticalCase: function (number, wordKey) {
            return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]);
        },
        translate: function (number, withoutSuffix, key) {
            var wordKey = translator.words[key];
            if (key.length === 1) {
                return withoutSuffix ? wordKey[0] : wordKey[1];
            } else {
                return number + ' ' + translator.correctGrammaticalCase(number, wordKey);
            }
        }
    };

    hooks.defineLocale('me', {
        months: 'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split('_'),
        monthsShort: 'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split('_'),
        monthsParseExact: true,
        weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'),
        weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'),
        weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm',
            LLLL: 'dddd, D. MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[danas u] LT',
            nextDay: '[sjutra u] LT',

            nextWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[u] [nedjelju] [u] LT';
                    case 3:
                        return '[u] [srijedu] [u] LT';
                    case 6:
                        return '[u] [subotu] [u] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[u] dddd [u] LT';
                }
            },
            lastDay: '[juče u] LT',
            lastWeek: function () {
                var lastWeekDays = [
                    '[prošle] [nedjelje] [u] LT',
                    '[prošlog] [ponedjeljka] [u] LT',
                    '[prošlog] [utorka] [u] LT',
                    '[prošle] [srijede] [u] LT',
                    '[prošlog] [četvrtka] [u] LT',
                    '[prošlog] [petka] [u] LT',
                    '[prošle] [subote] [u] LT'
                ];
                return lastWeekDays[this.day()];
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'za %s',
            past: 'prije %s',
            s: 'nekoliko sekundi',
            ss: translator.translate,
            m: translator.translate,
            mm: translator.translate,
            h: translator.translate,
            hh: translator.translate,
            d: 'dan',
            dd: translator.translate,
            M: 'mjesec',
            MM: translator.translate,
            y: 'godinu',
            yy: translator.translate
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('mi', {
        months: 'Kohi-tāte_Hui-tanguru_Poutū-te-rangi_Paenga-whāwhā_Haratua_Pipiri_Hōngoingoi_Here-turi-kōkā_Mahuru_Whiringa-ā-nuku_Whiringa-ā-rangi_Hakihea'.split('_'),
        monthsShort: 'Kohi_Hui_Pou_Pae_Hara_Pipi_Hōngoi_Here_Mahu_Whi-nu_Whi-ra_Haki'.split('_'),
        monthsRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i,
        monthsStrictRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i,
        monthsShortRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i,
        monthsShortStrictRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,2}/i,
        weekdays: 'Rātapu_Mane_Tūrei_Wenerei_Tāite_Paraire_Hātarei'.split('_'),
        weekdaysShort: 'Ta_Ma_Tū_We_Tāi_Pa_Hā'.split('_'),
        weekdaysMin: 'Ta_Ma_Tū_We_Tāi_Pa_Hā'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY [i] HH:mm',
            LLLL: 'dddd, D MMMM YYYY [i] HH:mm'
        },
        calendar: {
            sameDay: '[i teie mahana, i] LT',
            nextDay: '[apopo i] LT',
            nextWeek: 'dddd [i] LT',
            lastDay: '[inanahi i] LT',
            lastWeek: 'dddd [whakamutunga i] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'i roto i %s',
            past: '%s i mua',
            s: 'te hēkona ruarua',
            ss: '%d hēkona',
            m: 'he meneti',
            mm: '%d meneti',
            h: 'te haora',
            hh: '%d haora',
            d: 'he ra',
            dd: '%d ra',
            M: 'he marama',
            MM: '%d marama',
            y: 'he tau',
            yy: '%d tau'
        },
        dayOfMonthOrdinalParse: /\d{1,2}º/,
        ordinal: '%dº',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('mk', {
        months: 'јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември'.split('_'),
        monthsShort: 'јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек'.split('_'),
        weekdays: 'недела_понеделник_вторник_среда_четврток_петок_сабота'.split('_'),
        weekdaysShort: 'нед_пон_вто_сре_чет_пет_саб'.split('_'),
        weekdaysMin: 'нe_пo_вт_ср_че_пе_сa'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'D.MM.YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY H:mm',
            LLLL: 'dddd, D MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[Денес во] LT',
            nextDay: '[Утре во] LT',
            nextWeek: '[Во] dddd [во] LT',
            lastDay: '[Вчера во] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                    case 3:
                    case 6:
                        return '[Изминатата] dddd [во] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[Изминатиот] dddd [во] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'после %s',
            past: 'пред %s',
            s: 'неколку секунди',
            ss: '%d секунди',
            m: 'минута',
            mm: '%d минути',
            h: 'час',
            hh: '%d часа',
            d: 'ден',
            dd: '%d дена',
            M: 'месец',
            MM: '%d месеци',
            y: 'година',
            yy: '%d години'
        },
        dayOfMonthOrdinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/,
        ordinal: function (number) {
            var lastDigit = number % 10,
                last2Digits = number % 100;
            if (number === 0) {
                return number + '-ев';
            } else if (last2Digits === 0) {
                return number + '-ен';
            } else if (last2Digits > 10 && last2Digits < 20) {
                return number + '-ти';
            } else if (lastDigit === 1) {
                return number + '-ви';
            } else if (lastDigit === 2) {
                return number + '-ри';
            } else if (lastDigit === 7 || lastDigit === 8) {
                return number + '-ми';
            } else {
                return number + '-ти';
            }
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('ml', {
        months: 'ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ'.split('_'),
        monthsShort: 'ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._ഓഗ._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.'.split('_'),
        monthsParseExact: true,
        weekdays: 'ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച'.split('_'),
        weekdaysShort: 'ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി'.split('_'),
        weekdaysMin: 'ഞാ_തി_ചൊ_ബു_വ്യാ_വെ_ശ'.split('_'),
        longDateFormat: {
            LT: 'A h:mm -നു',
            LTS: 'A h:mm:ss -നു',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY, A h:mm -നു',
            LLLL: 'dddd, D MMMM YYYY, A h:mm -നു'
        },
        calendar: {
            sameDay: '[ഇന്ന്] LT',
            nextDay: '[നാളെ] LT',
            nextWeek: 'dddd, LT',
            lastDay: '[ഇന്നലെ] LT',
            lastWeek: '[കഴിഞ്ഞ] dddd, LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s കഴിഞ്ഞ്',
            past: '%s മുൻപ്',
            s: 'അൽപ നിമിഷങ്ങൾ',
            ss: '%d സെക്കൻഡ്',
            m: 'ഒരു മിനിറ്റ്',
            mm: '%d മിനിറ്റ്',
            h: 'ഒരു മണിക്കൂർ',
            hh: '%d മണിക്കൂർ',
            d: 'ഒരു ദിവസം',
            dd: '%d ദിവസം',
            M: 'ഒരു മാസം',
            MM: '%d മാസം',
            y: 'ഒരു വർഷം',
            yy: '%d വർഷം'
        },
        meridiemParse: /രാത്രി|രാവിലെ|ഉച്ച കഴിഞ്ഞ്|വൈകുന്നേരം|രാത്രി/i,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if ((meridiem === 'രാത്രി' && hour >= 4) ||
                meridiem === 'ഉച്ച കഴിഞ്ഞ്' ||
                meridiem === 'വൈകുന്നേരം') {
                return hour + 12;
            } else {
                return hour;
            }
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'രാത്രി';
            } else if (hour < 12) {
                return 'രാവിലെ';
            } else if (hour < 17) {
                return 'ഉച്ച കഴിഞ്ഞ്';
            } else if (hour < 20) {
                return 'വൈകുന്നേരം';
            } else {
                return 'രാത്രി';
            }
        }
    });

    //! moment.js locale configuration

    function translate$7(number, withoutSuffix, key, isFuture) {
        switch (key) {
            case 's':
                return withoutSuffix ? 'хэдхэн секунд' : 'хэдхэн секундын';
            case 'ss':
                return number + (withoutSuffix ? ' секунд' : ' секундын');
            case 'm':
            case 'mm':
                return number + (withoutSuffix ? ' минут' : ' минутын');
            case 'h':
            case 'hh':
                return number + (withoutSuffix ? ' цаг' : ' цагийн');
            case 'd':
            case 'dd':
                return number + (withoutSuffix ? ' өдөр' : ' өдрийн');
            case 'M':
            case 'MM':
                return number + (withoutSuffix ? ' сар' : ' сарын');
            case 'y':
            case 'yy':
                return number + (withoutSuffix ? ' жил' : ' жилийн');
            default:
                return number;
        }
    }

    hooks.defineLocale('mn', {
        months: 'Нэгдүгээр сар_Хоёрдугаар сар_Гуравдугаар сар_Дөрөвдүгээр сар_Тавдугаар сар_Зургадугаар сар_Долдугаар сар_Наймдугаар сар_Есдүгээр сар_Аравдугаар сар_Арван нэгдүгээр сар_Арван хоёрдугаар сар'.split('_'),
        monthsShort: '1 сар_2 сар_3 сар_4 сар_5 сар_6 сар_7 сар_8 сар_9 сар_10 сар_11 сар_12 сар'.split('_'),
        monthsParseExact: true,
        weekdays: 'Ням_Даваа_Мягмар_Лхагва_Пүрэв_Баасан_Бямба'.split('_'),
        weekdaysShort: 'Ням_Дав_Мяг_Лха_Пүр_Баа_Бям'.split('_'),
        weekdaysMin: 'Ня_Да_Мя_Лх_Пү_Ба_Бя'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'YYYY-MM-DD',
            LL: 'YYYY оны MMMMын D',
            LLL: 'YYYY оны MMMMын D HH:mm',
            LLLL: 'dddd, YYYY оны MMMMын D HH:mm'
        },
        meridiemParse: /ҮӨ|ҮХ/i,
        isPM: function (input) {
            return input === 'ҮХ';
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 12) {
                return 'ҮӨ';
            } else {
                return 'ҮХ';
            }
        },
        calendar: {
            sameDay: '[Өнөөдөр] LT',
            nextDay: '[Маргааш] LT',
            nextWeek: '[Ирэх] dddd LT',
            lastDay: '[Өчигдөр] LT',
            lastWeek: '[Өнгөрсөн] dddd LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s дараа',
            past: '%s өмнө',
            s: translate$7,
            ss: translate$7,
            m: translate$7,
            mm: translate$7,
            h: translate$7,
            hh: translate$7,
            d: translate$7,
            dd: translate$7,
            M: translate$7,
            MM: translate$7,
            y: translate$7,
            yy: translate$7
        },
        dayOfMonthOrdinalParse: /\d{1,2} өдөр/,
        ordinal: function (number, period) {
            switch (period) {
                case 'd':
                case 'D':
                case 'DDD':
                    return number + ' өдөр';
                default:
                    return number;
            }
        }
    });

    //! moment.js locale configuration

    var symbolMap$a = {
        '1': '१',
        '2': '२',
        '3': '३',
        '4': '४',
        '5': '५',
        '6': '६',
        '7': '७',
        '8': '८',
        '9': '९',
        '0': '०'
    },
        numberMap$9 = {
            '१': '1',
            '२': '2',
            '३': '3',
            '४': '4',
            '५': '5',
            '६': '6',
            '७': '7',
            '८': '8',
            '९': '9',
            '०': '0'
        };

    function relativeTimeMr(number, withoutSuffix, string, isFuture) {
        var output = '';
        if (withoutSuffix) {
            switch (string) {
                case 's': output = 'काही सेकंद'; break;
                case 'ss': output = '%d सेकंद'; break;
                case 'm': output = 'एक मिनिट'; break;
                case 'mm': output = '%d मिनिटे'; break;
                case 'h': output = 'एक तास'; break;
                case 'hh': output = '%d तास'; break;
                case 'd': output = 'एक दिवस'; break;
                case 'dd': output = '%d दिवस'; break;
                case 'M': output = 'एक महिना'; break;
                case 'MM': output = '%d महिने'; break;
                case 'y': output = 'एक वर्ष'; break;
                case 'yy': output = '%d वर्षे'; break;
            }
        }
        else {
            switch (string) {
                case 's': output = 'काही सेकंदां'; break;
                case 'ss': output = '%d सेकंदां'; break;
                case 'm': output = 'एका मिनिटा'; break;
                case 'mm': output = '%d मिनिटां'; break;
                case 'h': output = 'एका तासा'; break;
                case 'hh': output = '%d तासां'; break;
                case 'd': output = 'एका दिवसा'; break;
                case 'dd': output = '%d दिवसां'; break;
                case 'M': output = 'एका महिन्या'; break;
                case 'MM': output = '%d महिन्यां'; break;
                case 'y': output = 'एका वर्षा'; break;
                case 'yy': output = '%d वर्षां'; break;
            }
        }
        return output.replace(/%d/i, number);
    }

    hooks.defineLocale('mr', {
        months: 'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split('_'),
        monthsShort: 'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split('_'),
        monthsParseExact: true,
        weekdays: 'रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'),
        weekdaysShort: 'रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि'.split('_'),
        weekdaysMin: 'र_सो_मं_बु_गु_शु_श'.split('_'),
        longDateFormat: {
            LT: 'A h:mm वाजता',
            LTS: 'A h:mm:ss वाजता',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY, A h:mm वाजता',
            LLLL: 'dddd, D MMMM YYYY, A h:mm वाजता'
        },
        calendar: {
            sameDay: '[आज] LT',
            nextDay: '[उद्या] LT',
            nextWeek: 'dddd, LT',
            lastDay: '[काल] LT',
            lastWeek: '[मागील] dddd, LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%sमध्ये',
            past: '%sपूर्वी',
            s: relativeTimeMr,
            ss: relativeTimeMr,
            m: relativeTimeMr,
            mm: relativeTimeMr,
            h: relativeTimeMr,
            hh: relativeTimeMr,
            d: relativeTimeMr,
            dd: relativeTimeMr,
            M: relativeTimeMr,
            MM: relativeTimeMr,
            y: relativeTimeMr,
            yy: relativeTimeMr
        },
        preparse: function (string) {
            return string.replace(/[१२३४५६७८९०]/g, function (match) {
                return numberMap$9[match];
            });
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return symbolMap$a[match];
            });
        },
        meridiemParse: /रात्री|सकाळी|दुपारी|सायंकाळी/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'रात्री') {
                return hour < 4 ? hour : hour + 12;
            } else if (meridiem === 'सकाळी') {
                return hour;
            } else if (meridiem === 'दुपारी') {
                return hour >= 10 ? hour : hour + 12;
            } else if (meridiem === 'सायंकाळी') {
                return hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'रात्री';
            } else if (hour < 10) {
                return 'सकाळी';
            } else if (hour < 17) {
                return 'दुपारी';
            } else if (hour < 20) {
                return 'सायंकाळी';
            } else {
                return 'रात्री';
            }
        },
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 6  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('ms-my', {
        months: 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'),
        monthsShort: 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'),
        weekdays: 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'),
        weekdaysShort: 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'),
        weekdaysMin: 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'),
        longDateFormat: {
            LT: 'HH.mm',
            LTS: 'HH.mm.ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY [pukul] HH.mm',
            LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm'
        },
        meridiemParse: /pagi|tengahari|petang|malam/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'pagi') {
                return hour;
            } else if (meridiem === 'tengahari') {
                return hour >= 11 ? hour : hour + 12;
            } else if (meridiem === 'petang' || meridiem === 'malam') {
                return hour + 12;
            }
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours < 11) {
                return 'pagi';
            } else if (hours < 15) {
                return 'tengahari';
            } else if (hours < 19) {
                return 'petang';
            } else {
                return 'malam';
            }
        },
        calendar: {
            sameDay: '[Hari ini pukul] LT',
            nextDay: '[Esok pukul] LT',
            nextWeek: 'dddd [pukul] LT',
            lastDay: '[Kelmarin pukul] LT',
            lastWeek: 'dddd [lepas pukul] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'dalam %s',
            past: '%s yang lepas',
            s: 'beberapa saat',
            ss: '%d saat',
            m: 'seminit',
            mm: '%d minit',
            h: 'sejam',
            hh: '%d jam',
            d: 'sehari',
            dd: '%d hari',
            M: 'sebulan',
            MM: '%d bulan',
            y: 'setahun',
            yy: '%d tahun'
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('ms', {
        months: 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'),
        monthsShort: 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'),
        weekdays: 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'),
        weekdaysShort: 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'),
        weekdaysMin: 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'),
        longDateFormat: {
            LT: 'HH.mm',
            LTS: 'HH.mm.ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY [pukul] HH.mm',
            LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm'
        },
        meridiemParse: /pagi|tengahari|petang|malam/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'pagi') {
                return hour;
            } else if (meridiem === 'tengahari') {
                return hour >= 11 ? hour : hour + 12;
            } else if (meridiem === 'petang' || meridiem === 'malam') {
                return hour + 12;
            }
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours < 11) {
                return 'pagi';
            } else if (hours < 15) {
                return 'tengahari';
            } else if (hours < 19) {
                return 'petang';
            } else {
                return 'malam';
            }
        },
        calendar: {
            sameDay: '[Hari ini pukul] LT',
            nextDay: '[Esok pukul] LT',
            nextWeek: 'dddd [pukul] LT',
            lastDay: '[Kelmarin pukul] LT',
            lastWeek: 'dddd [lepas pukul] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'dalam %s',
            past: '%s yang lepas',
            s: 'beberapa saat',
            ss: '%d saat',
            m: 'seminit',
            mm: '%d minit',
            h: 'sejam',
            hh: '%d jam',
            d: 'sehari',
            dd: '%d hari',
            M: 'sebulan',
            MM: '%d bulan',
            y: 'setahun',
            yy: '%d tahun'
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('mt', {
        months: 'Jannar_Frar_Marzu_April_Mejju_Ġunju_Lulju_Awwissu_Settembru_Ottubru_Novembru_Diċembru'.split('_'),
        monthsShort: 'Jan_Fra_Mar_Apr_Mej_Ġun_Lul_Aww_Set_Ott_Nov_Diċ'.split('_'),
        weekdays: 'Il-Ħadd_It-Tnejn_It-Tlieta_L-Erbgħa_Il-Ħamis_Il-Ġimgħa_Is-Sibt'.split('_'),
        weekdaysShort: 'Ħad_Tne_Tli_Erb_Ħam_Ġim_Sib'.split('_'),
        weekdaysMin: 'Ħa_Tn_Tl_Er_Ħa_Ġi_Si'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Illum fil-]LT',
            nextDay: '[Għada fil-]LT',
            nextWeek: 'dddd [fil-]LT',
            lastDay: '[Il-bieraħ fil-]LT',
            lastWeek: 'dddd [li għadda] [fil-]LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'f’ %s',
            past: '%s ilu',
            s: 'ftit sekondi',
            ss: '%d sekondi',
            m: 'minuta',
            mm: '%d minuti',
            h: 'siegħa',
            hh: '%d siegħat',
            d: 'ġurnata',
            dd: '%d ġranet',
            M: 'xahar',
            MM: '%d xhur',
            y: 'sena',
            yy: '%d sni'
        },
        dayOfMonthOrdinalParse: /\d{1,2}º/,
        ordinal: '%dº',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var symbolMap$b = {
        '1': '၁',
        '2': '၂',
        '3': '၃',
        '4': '၄',
        '5': '၅',
        '6': '၆',
        '7': '၇',
        '8': '၈',
        '9': '၉',
        '0': '၀'
    }, numberMap$a = {
        '၁': '1',
        '၂': '2',
        '၃': '3',
        '၄': '4',
        '၅': '5',
        '၆': '6',
        '၇': '7',
        '၈': '8',
        '၉': '9',
        '၀': '0'
    };

    hooks.defineLocale('my', {
        months: 'ဇန်နဝါရီ_ဖေဖော်ဝါရီ_မတ်_ဧပြီ_မေ_ဇွန်_ဇူလိုင်_သြဂုတ်_စက်တင်ဘာ_အောက်တိုဘာ_နိုဝင်ဘာ_ဒီဇင်ဘာ'.split('_'),
        monthsShort: 'ဇန်_ဖေ_မတ်_ပြီ_မေ_ဇွန်_လိုင်_သြ_စက်_အောက်_နို_ဒီ'.split('_'),
        weekdays: 'တနင်္ဂနွေ_တနင်္လာ_အင်္ဂါ_ဗုဒ္ဓဟူး_ကြာသပတေး_သောကြာ_စနေ'.split('_'),
        weekdaysShort: 'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'),
        weekdaysMin: 'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'),

        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[ယနေ.] LT [မှာ]',
            nextDay: '[မနက်ဖြန်] LT [မှာ]',
            nextWeek: 'dddd LT [မှာ]',
            lastDay: '[မနေ.က] LT [မှာ]',
            lastWeek: '[ပြီးခဲ့သော] dddd LT [မှာ]',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'လာမည့် %s မှာ',
            past: 'လွန်ခဲ့သော %s က',
            s: 'စက္ကန်.အနည်းငယ်',
            ss: '%d စက္ကန့်',
            m: 'တစ်မိနစ်',
            mm: '%d မိနစ်',
            h: 'တစ်နာရီ',
            hh: '%d နာရီ',
            d: 'တစ်ရက်',
            dd: '%d ရက်',
            M: 'တစ်လ',
            MM: '%d လ',
            y: 'တစ်နှစ်',
            yy: '%d နှစ်'
        },
        preparse: function (string) {
            return string.replace(/[၁၂၃၄၅၆၇၈၉၀]/g, function (match) {
                return numberMap$a[match];
            });
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return symbolMap$b[match];
            });
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4 // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('nb', {
        months: 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'),
        monthsShort: 'jan._feb._mars_april_mai_juni_juli_aug._sep._okt._nov._des.'.split('_'),
        monthsParseExact: true,
        weekdays: 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'),
        weekdaysShort: 'sø._ma._ti._on._to._fr._lø.'.split('_'),
        weekdaysMin: 'sø_ma_ti_on_to_fr_lø'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY [kl.] HH:mm',
            LLLL: 'dddd D. MMMM YYYY [kl.] HH:mm'
        },
        calendar: {
            sameDay: '[i dag kl.] LT',
            nextDay: '[i morgen kl.] LT',
            nextWeek: 'dddd [kl.] LT',
            lastDay: '[i går kl.] LT',
            lastWeek: '[forrige] dddd [kl.] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'om %s',
            past: '%s siden',
            s: 'noen sekunder',
            ss: '%d sekunder',
            m: 'ett minutt',
            mm: '%d minutter',
            h: 'en time',
            hh: '%d timer',
            d: 'en dag',
            dd: '%d dager',
            M: 'en måned',
            MM: '%d måneder',
            y: 'ett år',
            yy: '%d år'
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var symbolMap$c = {
        '1': '१',
        '2': '२',
        '3': '३',
        '4': '४',
        '5': '५',
        '6': '६',
        '7': '७',
        '8': '८',
        '9': '९',
        '0': '०'
    },
        numberMap$b = {
            '१': '1',
            '२': '2',
            '३': '3',
            '४': '4',
            '५': '5',
            '६': '6',
            '७': '7',
            '८': '8',
            '९': '9',
            '०': '0'
        };

    hooks.defineLocale('ne', {
        months: 'जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर'.split('_'),
        monthsShort: 'जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.'.split('_'),
        monthsParseExact: true,
        weekdays: 'आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार'.split('_'),
        weekdaysShort: 'आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.'.split('_'),
        weekdaysMin: 'आ._सो._मं._बु._बि._शु._श.'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'Aको h:mm बजे',
            LTS: 'Aको h:mm:ss बजे',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY, Aको h:mm बजे',
            LLLL: 'dddd, D MMMM YYYY, Aको h:mm बजे'
        },
        preparse: function (string) {
            return string.replace(/[१२३४५६७८९०]/g, function (match) {
                return numberMap$b[match];
            });
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return symbolMap$c[match];
            });
        },
        meridiemParse: /राति|बिहान|दिउँसो|साँझ/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'राति') {
                return hour < 4 ? hour : hour + 12;
            } else if (meridiem === 'बिहान') {
                return hour;
            } else if (meridiem === 'दिउँसो') {
                return hour >= 10 ? hour : hour + 12;
            } else if (meridiem === 'साँझ') {
                return hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 3) {
                return 'राति';
            } else if (hour < 12) {
                return 'बिहान';
            } else if (hour < 16) {
                return 'दिउँसो';
            } else if (hour < 20) {
                return 'साँझ';
            } else {
                return 'राति';
            }
        },
        calendar: {
            sameDay: '[आज] LT',
            nextDay: '[भोलि] LT',
            nextWeek: '[आउँदो] dddd[,] LT',
            lastDay: '[हिजो] LT',
            lastWeek: '[गएको] dddd[,] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%sमा',
            past: '%s अगाडि',
            s: 'केही क्षण',
            ss: '%d सेकेण्ड',
            m: 'एक मिनेट',
            mm: '%d मिनेट',
            h: 'एक घण्टा',
            hh: '%d घण्टा',
            d: 'एक दिन',
            dd: '%d दिन',
            M: 'एक महिना',
            MM: '%d महिना',
            y: 'एक बर्ष',
            yy: '%d बर्ष'
        },
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 6  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var monthsShortWithDots$1 = 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'),
        monthsShortWithoutDots$1 = 'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_');

    var monthsParse$2 = [/^jan/i, /^feb/i, /^maart|mrt.?$/i, /^apr/i, /^mei$/i, /^jun[i.]?$/i, /^jul[i.]?$/i, /^aug/i, /^sep/i, /^okt/i, /^nov/i, /^dec/i];
    var monthsRegex$3 = /^(januari|februari|maart|april|mei|april|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i;

    hooks.defineLocale('nl-be', {
        months: 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split('_'),
        monthsShort: function (m, format) {
            if (!m) {
                return monthsShortWithDots$1;
            } else if (/-MMM-/.test(format)) {
                return monthsShortWithoutDots$1[m.month()];
            } else {
                return monthsShortWithDots$1[m.month()];
            }
        },

        monthsRegex: monthsRegex$3,
        monthsShortRegex: monthsRegex$3,
        monthsStrictRegex: /^(januari|februari|maart|mei|ju[nl]i|april|augustus|september|oktober|november|december)/i,
        monthsShortStrictRegex: /^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i,

        monthsParse: monthsParse$2,
        longMonthsParse: monthsParse$2,
        shortMonthsParse: monthsParse$2,

        weekdays: 'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'),
        weekdaysShort: 'zo._ma._di._wo._do._vr._za.'.split('_'),
        weekdaysMin: 'zo_ma_di_wo_do_vr_za'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[vandaag om] LT',
            nextDay: '[morgen om] LT',
            nextWeek: 'dddd [om] LT',
            lastDay: '[gisteren om] LT',
            lastWeek: '[afgelopen] dddd [om] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'over %s',
            past: '%s geleden',
            s: 'een paar seconden',
            ss: '%d seconden',
            m: 'één minuut',
            mm: '%d minuten',
            h: 'één uur',
            hh: '%d uur',
            d: 'één dag',
            dd: '%d dagen',
            M: 'één maand',
            MM: '%d maanden',
            y: 'één jaar',
            yy: '%d jaar'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/,
        ordinal: function (number) {
            return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de');
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var monthsShortWithDots$2 = 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'),
        monthsShortWithoutDots$2 = 'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_');

    var monthsParse$3 = [/^jan/i, /^feb/i, /^maart|mrt.?$/i, /^apr/i, /^mei$/i, /^jun[i.]?$/i, /^jul[i.]?$/i, /^aug/i, /^sep/i, /^okt/i, /^nov/i, /^dec/i];
    var monthsRegex$4 = /^(januari|februari|maart|april|mei|april|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i;

    hooks.defineLocale('nl', {
        months: 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split('_'),
        monthsShort: function (m, format) {
            if (!m) {
                return monthsShortWithDots$2;
            } else if (/-MMM-/.test(format)) {
                return monthsShortWithoutDots$2[m.month()];
            } else {
                return monthsShortWithDots$2[m.month()];
            }
        },

        monthsRegex: monthsRegex$4,
        monthsShortRegex: monthsRegex$4,
        monthsStrictRegex: /^(januari|februari|maart|mei|ju[nl]i|april|augustus|september|oktober|november|december)/i,
        monthsShortStrictRegex: /^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i,

        monthsParse: monthsParse$3,
        longMonthsParse: monthsParse$3,
        shortMonthsParse: monthsParse$3,

        weekdays: 'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'),
        weekdaysShort: 'zo._ma._di._wo._do._vr._za.'.split('_'),
        weekdaysMin: 'zo_ma_di_wo_do_vr_za'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD-MM-YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[vandaag om] LT',
            nextDay: '[morgen om] LT',
            nextWeek: 'dddd [om] LT',
            lastDay: '[gisteren om] LT',
            lastWeek: '[afgelopen] dddd [om] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'over %s',
            past: '%s geleden',
            s: 'een paar seconden',
            ss: '%d seconden',
            m: 'één minuut',
            mm: '%d minuten',
            h: 'één uur',
            hh: '%d uur',
            d: 'één dag',
            dd: '%d dagen',
            M: 'één maand',
            MM: '%d maanden',
            y: 'één jaar',
            yy: '%d jaar'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/,
        ordinal: function (number) {
            return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de');
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('nn', {
        months: 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'),
        monthsShort: 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'),
        weekdays: 'sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag'.split('_'),
        weekdaysShort: 'sun_mån_tys_ons_tor_fre_lau'.split('_'),
        weekdaysMin: 'su_må_ty_on_to_fr_lø'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY [kl.] H:mm',
            LLLL: 'dddd D. MMMM YYYY [kl.] HH:mm'
        },
        calendar: {
            sameDay: '[I dag klokka] LT',
            nextDay: '[I morgon klokka] LT',
            nextWeek: 'dddd [klokka] LT',
            lastDay: '[I går klokka] LT',
            lastWeek: '[Føregåande] dddd [klokka] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'om %s',
            past: '%s sidan',
            s: 'nokre sekund',
            ss: '%d sekund',
            m: 'eit minutt',
            mm: '%d minutt',
            h: 'ein time',
            hh: '%d timar',
            d: 'ein dag',
            dd: '%d dagar',
            M: 'ein månad',
            MM: '%d månader',
            y: 'eit år',
            yy: '%d år'
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var symbolMap$d = {
        '1': '੧',
        '2': '੨',
        '3': '੩',
        '4': '੪',
        '5': '੫',
        '6': '੬',
        '7': '੭',
        '8': '੮',
        '9': '੯',
        '0': '੦'
    },
        numberMap$c = {
            '੧': '1',
            '੨': '2',
            '੩': '3',
            '੪': '4',
            '੫': '5',
            '੬': '6',
            '੭': '7',
            '੮': '8',
            '੯': '9',
            '੦': '0'
        };

    hooks.defineLocale('pa-in', {
        // There are months name as per Nanakshahi Calender but they are not used as rigidly in modern Punjabi.
        months: 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'),
        monthsShort: 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'),
        weekdays: 'ਐਤਵਾਰ_ਸੋਮਵਾਰ_ਮੰਗਲਵਾਰ_ਬੁਧਵਾਰ_ਵੀਰਵਾਰ_ਸ਼ੁੱਕਰਵਾਰ_ਸ਼ਨੀਚਰਵਾਰ'.split('_'),
        weekdaysShort: 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'),
        weekdaysMin: 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'),
        longDateFormat: {
            LT: 'A h:mm ਵਜੇ',
            LTS: 'A h:mm:ss ਵਜੇ',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY, A h:mm ਵਜੇ',
            LLLL: 'dddd, D MMMM YYYY, A h:mm ਵਜੇ'
        },
        calendar: {
            sameDay: '[ਅਜ] LT',
            nextDay: '[ਕਲ] LT',
            nextWeek: '[ਅਗਲਾ] dddd, LT',
            lastDay: '[ਕਲ] LT',
            lastWeek: '[ਪਿਛਲੇ] dddd, LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s ਵਿੱਚ',
            past: '%s ਪਿਛਲੇ',
            s: 'ਕੁਝ ਸਕਿੰਟ',
            ss: '%d ਸਕਿੰਟ',
            m: 'ਇਕ ਮਿੰਟ',
            mm: '%d ਮਿੰਟ',
            h: 'ਇੱਕ ਘੰਟਾ',
            hh: '%d ਘੰਟੇ',
            d: 'ਇੱਕ ਦਿਨ',
            dd: '%d ਦਿਨ',
            M: 'ਇੱਕ ਮਹੀਨਾ',
            MM: '%d ਮਹੀਨੇ',
            y: 'ਇੱਕ ਸਾਲ',
            yy: '%d ਸਾਲ'
        },
        preparse: function (string) {
            return string.replace(/[੧੨੩੪੫੬੭੮੯੦]/g, function (match) {
                return numberMap$c[match];
            });
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return symbolMap$d[match];
            });
        },
        // Punjabi notation for meridiems are quite fuzzy in practice. While there exists
        // a rigid notion of a 'Pahar' it is not used as rigidly in modern Punjabi.
        meridiemParse: /ਰਾਤ|ਸਵੇਰ|ਦੁਪਹਿਰ|ਸ਼ਾਮ/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'ਰਾਤ') {
                return hour < 4 ? hour : hour + 12;
            } else if (meridiem === 'ਸਵੇਰ') {
                return hour;
            } else if (meridiem === 'ਦੁਪਹਿਰ') {
                return hour >= 10 ? hour : hour + 12;
            } else if (meridiem === 'ਸ਼ਾਮ') {
                return hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'ਰਾਤ';
            } else if (hour < 10) {
                return 'ਸਵੇਰ';
            } else if (hour < 17) {
                return 'ਦੁਪਹਿਰ';
            } else if (hour < 20) {
                return 'ਸ਼ਾਮ';
            } else {
                return 'ਰਾਤ';
            }
        },
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 6  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var monthsNominative = 'styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień'.split('_'),
        monthsSubjective = 'stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia'.split('_');
    function plural$3(n) {
        return (n % 10 < 5) && (n % 10 > 1) && ((~~(n / 10) % 10) !== 1);
    }
    function translate$8(number, withoutSuffix, key) {
        var result = number + ' ';
        switch (key) {
            case 'ss':
                return result + (plural$3(number) ? 'sekundy' : 'sekund');
            case 'm':
                return withoutSuffix ? 'minuta' : 'minutę';
            case 'mm':
                return result + (plural$3(number) ? 'minuty' : 'minut');
            case 'h':
                return withoutSuffix ? 'godzina' : 'godzinę';
            case 'hh':
                return result + (plural$3(number) ? 'godziny' : 'godzin');
            case 'MM':
                return result + (plural$3(number) ? 'miesiące' : 'miesięcy');
            case 'yy':
                return result + (plural$3(number) ? 'lata' : 'lat');
        }
    }

    hooks.defineLocale('pl', {
        months: function (momentToFormat, format) {
            if (!momentToFormat) {
                return monthsNominative;
            } else if (format === '') {
                // Hack: if format empty we know this is used to generate
                // RegExp by moment. Give then back both valid forms of months
                // in RegExp ready format.
                return '(' + monthsSubjective[momentToFormat.month()] + '|' + monthsNominative[momentToFormat.month()] + ')';
            } else if (/D MMMM/.test(format)) {
                return monthsSubjective[momentToFormat.month()];
            } else {
                return monthsNominative[momentToFormat.month()];
            }
        },
        monthsShort: 'sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru'.split('_'),
        weekdays: 'niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota'.split('_'),
        weekdaysShort: 'ndz_pon_wt_śr_czw_pt_sob'.split('_'),
        weekdaysMin: 'Nd_Pn_Wt_Śr_Cz_Pt_So'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Dziś o] LT',
            nextDay: '[Jutro o] LT',
            nextWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[W niedzielę o] LT';

                    case 2:
                        return '[We wtorek o] LT';

                    case 3:
                        return '[W środę o] LT';

                    case 6:
                        return '[W sobotę o] LT';

                    default:
                        return '[W] dddd [o] LT';
                }
            },
            lastDay: '[Wczoraj o] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[W zeszłą niedzielę o] LT';
                    case 3:
                        return '[W zeszłą środę o] LT';
                    case 6:
                        return '[W zeszłą sobotę o] LT';
                    default:
                        return '[W zeszły] dddd [o] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'za %s',
            past: '%s temu',
            s: 'kilka sekund',
            ss: translate$8,
            m: translate$8,
            mm: translate$8,
            h: translate$8,
            hh: translate$8,
            d: '1 dzień',
            dd: '%d dni',
            M: 'miesiąc',
            MM: translate$8,
            y: 'rok',
            yy: translate$8
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('pt-br', {
        months: 'janeiro_fevereiro_março_abril_maio_junho_julho_agosto_setembro_outubro_novembro_dezembro'.split('_'),
        monthsShort: 'jan_fev_mar_abr_mai_jun_jul_ago_set_out_nov_dez'.split('_'),
        weekdays: 'Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado'.split('_'),
        weekdaysShort: 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'),
        weekdaysMin: 'Do_2ª_3ª_4ª_5ª_6ª_Sá'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D [de] MMMM [de] YYYY',
            LLL: 'D [de] MMMM [de] YYYY [às] HH:mm',
            LLLL: 'dddd, D [de] MMMM [de] YYYY [às] HH:mm'
        },
        calendar: {
            sameDay: '[Hoje às] LT',
            nextDay: '[Amanhã às] LT',
            nextWeek: 'dddd [às] LT',
            lastDay: '[Ontem às] LT',
            lastWeek: function () {
                return (this.day() === 0 || this.day() === 6) ?
                    '[Último] dddd [às] LT' : // Saturday + Sunday
                    '[Última] dddd [às] LT'; // Monday - Friday
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'em %s',
            past: 'há %s',
            s: 'poucos segundos',
            ss: '%d segundos',
            m: 'um minuto',
            mm: '%d minutos',
            h: 'uma hora',
            hh: '%d horas',
            d: 'um dia',
            dd: '%d dias',
            M: 'um mês',
            MM: '%d meses',
            y: 'um ano',
            yy: '%d anos'
        },
        dayOfMonthOrdinalParse: /\d{1,2}º/,
        ordinal: '%dº'
    });

    //! moment.js locale configuration

    hooks.defineLocale('pt', {
        months: 'janeiro_fevereiro_março_abril_maio_junho_julho_agosto_setembro_outubro_novembro_dezembro'.split('_'),
        monthsShort: 'jan_fev_mar_abr_mai_jun_jul_ago_set_out_nov_dez'.split('_'),
        weekdays: 'Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado'.split('_'),
        weekdaysShort: 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'),
        weekdaysMin: 'Do_2ª_3ª_4ª_5ª_6ª_Sá'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D [de] MMMM [de] YYYY',
            LLL: 'D [de] MMMM [de] YYYY HH:mm',
            LLLL: 'dddd, D [de] MMMM [de] YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Hoje às] LT',
            nextDay: '[Amanhã às] LT',
            nextWeek: 'dddd [às] LT',
            lastDay: '[Ontem às] LT',
            lastWeek: function () {
                return (this.day() === 0 || this.day() === 6) ?
                    '[Último] dddd [às] LT' : // Saturday + Sunday
                    '[Última] dddd [às] LT'; // Monday - Friday
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'em %s',
            past: 'há %s',
            s: 'segundos',
            ss: '%d segundos',
            m: 'um minuto',
            mm: '%d minutos',
            h: 'uma hora',
            hh: '%d horas',
            d: 'um dia',
            dd: '%d dias',
            M: 'um mês',
            MM: '%d meses',
            y: 'um ano',
            yy: '%d anos'
        },
        dayOfMonthOrdinalParse: /\d{1,2}º/,
        ordinal: '%dº',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    function relativeTimeWithPlural$2(number, withoutSuffix, key) {
        var format = {
            'ss': 'secunde',
            'mm': 'minute',
            'hh': 'ore',
            'dd': 'zile',
            'MM': 'luni',
            'yy': 'ani'
        },
            separator = ' ';
        if (number % 100 >= 20 || (number >= 100 && number % 100 === 0)) {
            separator = ' de ';
        }
        return number + separator + format[key];
    }

    hooks.defineLocale('ro', {
        months: 'ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie'.split('_'),
        monthsShort: 'ian._febr._mart._apr._mai_iun._iul._aug._sept._oct._nov._dec.'.split('_'),
        monthsParseExact: true,
        weekdays: 'duminică_luni_marți_miercuri_joi_vineri_sâmbătă'.split('_'),
        weekdaysShort: 'Dum_Lun_Mar_Mie_Joi_Vin_Sâm'.split('_'),
        weekdaysMin: 'Du_Lu_Ma_Mi_Jo_Vi_Sâ'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY H:mm',
            LLLL: 'dddd, D MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[azi la] LT',
            nextDay: '[mâine la] LT',
            nextWeek: 'dddd [la] LT',
            lastDay: '[ieri la] LT',
            lastWeek: '[fosta] dddd [la] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'peste %s',
            past: '%s în urmă',
            s: 'câteva secunde',
            ss: relativeTimeWithPlural$2,
            m: 'un minut',
            mm: relativeTimeWithPlural$2,
            h: 'o oră',
            hh: relativeTimeWithPlural$2,
            d: 'o zi',
            dd: relativeTimeWithPlural$2,
            M: 'o lună',
            MM: relativeTimeWithPlural$2,
            y: 'un an',
            yy: relativeTimeWithPlural$2
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    function plural$4(word, num) {
        var forms = word.split('_');
        return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]);
    }
    function relativeTimeWithPlural$3(number, withoutSuffix, key) {
        var format = {
            'ss': withoutSuffix ? 'секунда_секунды_секунд' : 'секунду_секунды_секунд',
            'mm': withoutSuffix ? 'минута_минуты_минут' : 'минуту_минуты_минут',
            'hh': 'час_часа_часов',
            'dd': 'день_дня_дней',
            'MM': 'месяц_месяца_месяцев',
            'yy': 'год_года_лет'
        };
        if (key === 'm') {
            return withoutSuffix ? 'минута' : 'минуту';
        }
        else {
            return number + ' ' + plural$4(format[key], +number);
        }
    }
    var monthsParse$4 = [/^янв/i, /^фев/i, /^мар/i, /^апр/i, /^ма[йя]/i, /^июн/i, /^июл/i, /^авг/i, /^сен/i, /^окт/i, /^ноя/i, /^дек/i];

    // http://new.gramota.ru/spravka/rules/139-prop : § 103
    // Сокращения месяцев: http://new.gramota.ru/spravka/buro/search-answer?s=242637
    // CLDR data:          http://www.unicode.org/cldr/charts/28/summary/ru.html#1753
    hooks.defineLocale('ru', {
        months: {
            format: 'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split('_'),
            standalone: 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_')
        },
        monthsShort: {
            // по CLDR именно "июл." и "июн.", но какой смысл менять букву на точку ?
            format: 'янв._февр._мар._апр._мая_июня_июля_авг._сент._окт._нояб._дек.'.split('_'),
            standalone: 'янв._февр._март_апр._май_июнь_июль_авг._сент._окт._нояб._дек.'.split('_')
        },
        weekdays: {
            standalone: 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'),
            format: 'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split('_'),
            isFormat: /\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/
        },
        weekdaysShort: 'вс_пн_вт_ср_чт_пт_сб'.split('_'),
        weekdaysMin: 'вс_пн_вт_ср_чт_пт_сб'.split('_'),
        monthsParse: monthsParse$4,
        longMonthsParse: monthsParse$4,
        shortMonthsParse: monthsParse$4,

        // полные названия с падежами, по три буквы, для некоторых, по 4 буквы, сокращения с точкой и без точки
        monthsRegex: /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i,

        // копия предыдущего
        monthsShortRegex: /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i,

        // полные названия с падежами
        monthsStrictRegex: /^(январ[яь]|феврал[яь]|марта?|апрел[яь]|ма[яй]|июн[яь]|июл[яь]|августа?|сентябр[яь]|октябр[яь]|ноябр[яь]|декабр[яь])/i,

        // Выражение, которое соотвествует только сокращённым формам
        monthsShortStrictRegex: /^(янв\.|февр?\.|мар[т.]|апр\.|ма[яй]|июн[ья.]|июл[ья.]|авг\.|сент?\.|окт\.|нояб?\.|дек\.)/i,
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY г.',
            LLL: 'D MMMM YYYY г., H:mm',
            LLLL: 'dddd, D MMMM YYYY г., H:mm'
        },
        calendar: {
            sameDay: '[Сегодня, в] LT',
            nextDay: '[Завтра, в] LT',
            lastDay: '[Вчера, в] LT',
            nextWeek: function (now) {
                if (now.week() !== this.week()) {
                    switch (this.day()) {
                        case 0:
                            return '[В следующее] dddd, [в] LT';
                        case 1:
                        case 2:
                        case 4:
                            return '[В следующий] dddd, [в] LT';
                        case 3:
                        case 5:
                        case 6:
                            return '[В следующую] dddd, [в] LT';
                    }
                } else {
                    if (this.day() === 2) {
                        return '[Во] dddd, [в] LT';
                    } else {
                        return '[В] dddd, [в] LT';
                    }
                }
            },
            lastWeek: function (now) {
                if (now.week() !== this.week()) {
                    switch (this.day()) {
                        case 0:
                            return '[В прошлое] dddd, [в] LT';
                        case 1:
                        case 2:
                        case 4:
                            return '[В прошлый] dddd, [в] LT';
                        case 3:
                        case 5:
                        case 6:
                            return '[В прошлую] dddd, [в] LT';
                    }
                } else {
                    if (this.day() === 2) {
                        return '[Во] dddd, [в] LT';
                    } else {
                        return '[В] dddd, [в] LT';
                    }
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'через %s',
            past: '%s назад',
            s: 'несколько секунд',
            ss: relativeTimeWithPlural$3,
            m: relativeTimeWithPlural$3,
            mm: relativeTimeWithPlural$3,
            h: 'час',
            hh: relativeTimeWithPlural$3,
            d: 'день',
            dd: relativeTimeWithPlural$3,
            M: 'месяц',
            MM: relativeTimeWithPlural$3,
            y: 'год',
            yy: relativeTimeWithPlural$3
        },
        meridiemParse: /ночи|утра|дня|вечера/i,
        isPM: function (input) {
            return /^(дня|вечера)$/.test(input);
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'ночи';
            } else if (hour < 12) {
                return 'утра';
            } else if (hour < 17) {
                return 'дня';
            } else {
                return 'вечера';
            }
        },
        dayOfMonthOrdinalParse: /\d{1,2}-(й|го|я)/,
        ordinal: function (number, period) {
            switch (period) {
                case 'M':
                case 'd':
                case 'DDD':
                    return number + '-й';
                case 'D':
                    return number + '-го';
                case 'w':
                case 'W':
                    return number + '-я';
                default:
                    return number;
            }
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var months$6 = [
        'جنوري',
        'فيبروري',
        'مارچ',
        'اپريل',
        'مئي',
        'جون',
        'جولاءِ',
        'آگسٽ',
        'سيپٽمبر',
        'آڪٽوبر',
        'نومبر',
        'ڊسمبر'
    ];
    var days$1 = [
        'آچر',
        'سومر',
        'اڱارو',
        'اربع',
        'خميس',
        'جمع',
        'ڇنڇر'
    ];

    hooks.defineLocale('sd', {
        months: months$6,
        monthsShort: months$6,
        weekdays: days$1,
        weekdaysShort: days$1,
        weekdaysMin: days$1,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd، D MMMM YYYY HH:mm'
        },
        meridiemParse: /صبح|شام/,
        isPM: function (input) {
            return 'شام' === input;
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 12) {
                return 'صبح';
            }
            return 'شام';
        },
        calendar: {
            sameDay: '[اڄ] LT',
            nextDay: '[سڀاڻي] LT',
            nextWeek: 'dddd [اڳين هفتي تي] LT',
            lastDay: '[ڪالهه] LT',
            lastWeek: '[گزريل هفتي] dddd [تي] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s پوء',
            past: '%s اڳ',
            s: 'چند سيڪنڊ',
            ss: '%d سيڪنڊ',
            m: 'هڪ منٽ',
            mm: '%d منٽ',
            h: 'هڪ ڪلاڪ',
            hh: '%d ڪلاڪ',
            d: 'هڪ ڏينهن',
            dd: '%d ڏينهن',
            M: 'هڪ مهينو',
            MM: '%d مهينا',
            y: 'هڪ سال',
            yy: '%d سال'
        },
        preparse: function (string) {
            return string.replace(/،/g, ',');
        },
        postformat: function (string) {
            return string.replace(/,/g, '،');
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('se', {
        months: 'ođđajagemánnu_guovvamánnu_njukčamánnu_cuoŋománnu_miessemánnu_geassemánnu_suoidnemánnu_borgemánnu_čakčamánnu_golggotmánnu_skábmamánnu_juovlamánnu'.split('_'),
        monthsShort: 'ođđj_guov_njuk_cuo_mies_geas_suoi_borg_čakč_golg_skáb_juov'.split('_'),
        weekdays: 'sotnabeaivi_vuossárga_maŋŋebárga_gaskavahkku_duorastat_bearjadat_lávvardat'.split('_'),
        weekdaysShort: 'sotn_vuos_maŋ_gask_duor_bear_láv'.split('_'),
        weekdaysMin: 's_v_m_g_d_b_L'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'MMMM D. [b.] YYYY',
            LLL: 'MMMM D. [b.] YYYY [ti.] HH:mm',
            LLLL: 'dddd, MMMM D. [b.] YYYY [ti.] HH:mm'
        },
        calendar: {
            sameDay: '[otne ti] LT',
            nextDay: '[ihttin ti] LT',
            nextWeek: 'dddd [ti] LT',
            lastDay: '[ikte ti] LT',
            lastWeek: '[ovddit] dddd [ti] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s geažes',
            past: 'maŋit %s',
            s: 'moadde sekunddat',
            ss: '%d sekunddat',
            m: 'okta minuhta',
            mm: '%d minuhtat',
            h: 'okta diimmu',
            hh: '%d diimmut',
            d: 'okta beaivi',
            dd: '%d beaivvit',
            M: 'okta mánnu',
            MM: '%d mánut',
            y: 'okta jahki',
            yy: '%d jagit'
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    /*jshint -W100*/
    hooks.defineLocale('si', {
        months: 'ජනවාරි_පෙබරවාරි_මාර්තු_අප්‍රේල්_මැයි_ජූනි_ජූලි_අගෝස්තු_සැප්තැම්බර්_ඔක්තෝබර්_නොවැම්බර්_දෙසැම්බර්'.split('_'),
        monthsShort: 'ජන_පෙබ_මාර්_අප්_මැයි_ජූනි_ජූලි_අගෝ_සැප්_ඔක්_නොවැ_දෙසැ'.split('_'),
        weekdays: 'ඉරිදා_සඳුදා_අඟහරුවාදා_බදාදා_බ්‍රහස්පතින්දා_සිකුරාදා_සෙනසුරාදා'.split('_'),
        weekdaysShort: 'ඉරි_සඳු_අඟ_බදා_බ්‍රහ_සිකු_සෙන'.split('_'),
        weekdaysMin: 'ඉ_ස_අ_බ_බ්‍ර_සි_සෙ'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'a h:mm',
            LTS: 'a h:mm:ss',
            L: 'YYYY/MM/DD',
            LL: 'YYYY MMMM D',
            LLL: 'YYYY MMMM D, a h:mm',
            LLLL: 'YYYY MMMM D [වැනි] dddd, a h:mm:ss'
        },
        calendar: {
            sameDay: '[අද] LT[ට]',
            nextDay: '[හෙට] LT[ට]',
            nextWeek: 'dddd LT[ට]',
            lastDay: '[ඊයේ] LT[ට]',
            lastWeek: '[පසුගිය] dddd LT[ට]',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%sකින්',
            past: '%sකට පෙර',
            s: 'තත්පර කිහිපය',
            ss: 'තත්පර %d',
            m: 'මිනිත්තුව',
            mm: 'මිනිත්තු %d',
            h: 'පැය',
            hh: 'පැය %d',
            d: 'දිනය',
            dd: 'දින %d',
            M: 'මාසය',
            MM: 'මාස %d',
            y: 'වසර',
            yy: 'වසර %d'
        },
        dayOfMonthOrdinalParse: /\d{1,2} වැනි/,
        ordinal: function (number) {
            return number + ' වැනි';
        },
        meridiemParse: /පෙර වරු|පස් වරු|පෙ.ව|ප.ව./,
        isPM: function (input) {
            return input === 'ප.ව.' || input === 'පස් වරු';
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours > 11) {
                return isLower ? 'ප.ව.' : 'පස් වරු';
            } else {
                return isLower ? 'පෙ.ව.' : 'පෙර වරු';
            }
        }
    });

    //! moment.js locale configuration

    var months$7 = 'január_február_marec_apríl_máj_jún_júl_august_september_október_november_december'.split('_'),
        monthsShort$5 = 'jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec'.split('_');
    function plural$5(n) {
        return (n > 1) && (n < 5);
    }
    function translate$9(number, withoutSuffix, key, isFuture) {
        var result = number + ' ';
        switch (key) {
            case 's':  // a few seconds / in a few seconds / a few seconds ago
                return (withoutSuffix || isFuture) ? 'pár sekúnd' : 'pár sekundami';
            case 'ss': // 9 seconds / in 9 seconds / 9 seconds ago
                if (withoutSuffix || isFuture) {
                    return result + (plural$5(number) ? 'sekundy' : 'sekúnd');
                } else {
                    return result + 'sekundami';
                }
                break;
            case 'm':  // a minute / in a minute / a minute ago
                return withoutSuffix ? 'minúta' : (isFuture ? 'minútu' : 'minútou');
            case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago
                if (withoutSuffix || isFuture) {
                    return result + (plural$5(number) ? 'minúty' : 'minút');
                } else {
                    return result + 'minútami';
                }
                break;
            case 'h':  // an hour / in an hour / an hour ago
                return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou');
            case 'hh': // 9 hours / in 9 hours / 9 hours ago
                if (withoutSuffix || isFuture) {
                    return result + (plural$5(number) ? 'hodiny' : 'hodín');
                } else {
                    return result + 'hodinami';
                }
                break;
            case 'd':  // a day / in a day / a day ago
                return (withoutSuffix || isFuture) ? 'deň' : 'dňom';
            case 'dd': // 9 days / in 9 days / 9 days ago
                if (withoutSuffix || isFuture) {
                    return result + (plural$5(number) ? 'dni' : 'dní');
                } else {
                    return result + 'dňami';
                }
                break;
            case 'M':  // a month / in a month / a month ago
                return (withoutSuffix || isFuture) ? 'mesiac' : 'mesiacom';
            case 'MM': // 9 months / in 9 months / 9 months ago
                if (withoutSuffix || isFuture) {
                    return result + (plural$5(number) ? 'mesiace' : 'mesiacov');
                } else {
                    return result + 'mesiacmi';
                }
                break;
            case 'y':  // a year / in a year / a year ago
                return (withoutSuffix || isFuture) ? 'rok' : 'rokom';
            case 'yy': // 9 years / in 9 years / 9 years ago
                if (withoutSuffix || isFuture) {
                    return result + (plural$5(number) ? 'roky' : 'rokov');
                } else {
                    return result + 'rokmi';
                }
                break;
        }
    }

    hooks.defineLocale('sk', {
        months: months$7,
        monthsShort: monthsShort$5,
        weekdays: 'nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota'.split('_'),
        weekdaysShort: 'ne_po_ut_st_št_pi_so'.split('_'),
        weekdaysMin: 'ne_po_ut_st_št_pi_so'.split('_'),
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm',
            LLLL: 'dddd D. MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[dnes o] LT',
            nextDay: '[zajtra o] LT',
            nextWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[v nedeľu o] LT';
                    case 1:
                    case 2:
                        return '[v] dddd [o] LT';
                    case 3:
                        return '[v stredu o] LT';
                    case 4:
                        return '[vo štvrtok o] LT';
                    case 5:
                        return '[v piatok o] LT';
                    case 6:
                        return '[v sobotu o] LT';
                }
            },
            lastDay: '[včera o] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[minulú nedeľu o] LT';
                    case 1:
                    case 2:
                        return '[minulý] dddd [o] LT';
                    case 3:
                        return '[minulú stredu o] LT';
                    case 4:
                    case 5:
                        return '[minulý] dddd [o] LT';
                    case 6:
                        return '[minulú sobotu o] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'za %s',
            past: 'pred %s',
            s: translate$9,
            ss: translate$9,
            m: translate$9,
            mm: translate$9,
            h: translate$9,
            hh: translate$9,
            d: translate$9,
            dd: translate$9,
            M: translate$9,
            MM: translate$9,
            y: translate$9,
            yy: translate$9
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    function processRelativeTime$6(number, withoutSuffix, key, isFuture) {
        var result = number + ' ';
        switch (key) {
            case 's':
                return withoutSuffix || isFuture ? 'nekaj sekund' : 'nekaj sekundami';
            case 'ss':
                if (number === 1) {
                    result += withoutSuffix ? 'sekundo' : 'sekundi';
                } else if (number === 2) {
                    result += withoutSuffix || isFuture ? 'sekundi' : 'sekundah';
                } else if (number < 5) {
                    result += withoutSuffix || isFuture ? 'sekunde' : 'sekundah';
                } else {
                    result += withoutSuffix || isFuture ? 'sekund' : 'sekund';
                }
                return result;
            case 'm':
                return withoutSuffix ? 'ena minuta' : 'eno minuto';
            case 'mm':
                if (number === 1) {
                    result += withoutSuffix ? 'minuta' : 'minuto';
                } else if (number === 2) {
                    result += withoutSuffix || isFuture ? 'minuti' : 'minutama';
                } else if (number < 5) {
                    result += withoutSuffix || isFuture ? 'minute' : 'minutami';
                } else {
                    result += withoutSuffix || isFuture ? 'minut' : 'minutami';
                }
                return result;
            case 'h':
                return withoutSuffix ? 'ena ura' : 'eno uro';
            case 'hh':
                if (number === 1) {
                    result += withoutSuffix ? 'ura' : 'uro';
                } else if (number === 2) {
                    result += withoutSuffix || isFuture ? 'uri' : 'urama';
                } else if (number < 5) {
                    result += withoutSuffix || isFuture ? 'ure' : 'urami';
                } else {
                    result += withoutSuffix || isFuture ? 'ur' : 'urami';
                }
                return result;
            case 'd':
                return withoutSuffix || isFuture ? 'en dan' : 'enim dnem';
            case 'dd':
                if (number === 1) {
                    result += withoutSuffix || isFuture ? 'dan' : 'dnem';
                } else if (number === 2) {
                    result += withoutSuffix || isFuture ? 'dni' : 'dnevoma';
                } else {
                    result += withoutSuffix || isFuture ? 'dni' : 'dnevi';
                }
                return result;
            case 'M':
                return withoutSuffix || isFuture ? 'en mesec' : 'enim mesecem';
            case 'MM':
                if (number === 1) {
                    result += withoutSuffix || isFuture ? 'mesec' : 'mesecem';
                } else if (number === 2) {
                    result += withoutSuffix || isFuture ? 'meseca' : 'mesecema';
                } else if (number < 5) {
                    result += withoutSuffix || isFuture ? 'mesece' : 'meseci';
                } else {
                    result += withoutSuffix || isFuture ? 'mesecev' : 'meseci';
                }
                return result;
            case 'y':
                return withoutSuffix || isFuture ? 'eno leto' : 'enim letom';
            case 'yy':
                if (number === 1) {
                    result += withoutSuffix || isFuture ? 'leto' : 'letom';
                } else if (number === 2) {
                    result += withoutSuffix || isFuture ? 'leti' : 'letoma';
                } else if (number < 5) {
                    result += withoutSuffix || isFuture ? 'leta' : 'leti';
                } else {
                    result += withoutSuffix || isFuture ? 'let' : 'leti';
                }
                return result;
        }
    }

    hooks.defineLocale('sl', {
        months: 'januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december'.split('_'),
        monthsShort: 'jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.'.split('_'),
        monthsParseExact: true,
        weekdays: 'nedelja_ponedeljek_torek_sreda_četrtek_petek_sobota'.split('_'),
        weekdaysShort: 'ned._pon._tor._sre._čet._pet._sob.'.split('_'),
        weekdaysMin: 'ne_po_to_sr_če_pe_so'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm',
            LLLL: 'dddd, D. MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[danes ob] LT',
            nextDay: '[jutri ob] LT',

            nextWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[v] [nedeljo] [ob] LT';
                    case 3:
                        return '[v] [sredo] [ob] LT';
                    case 6:
                        return '[v] [soboto] [ob] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[v] dddd [ob] LT';
                }
            },
            lastDay: '[včeraj ob] LT',
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[prejšnjo] [nedeljo] [ob] LT';
                    case 3:
                        return '[prejšnjo] [sredo] [ob] LT';
                    case 6:
                        return '[prejšnjo] [soboto] [ob] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[prejšnji] dddd [ob] LT';
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'čez %s',
            past: 'pred %s',
            s: processRelativeTime$6,
            ss: processRelativeTime$6,
            m: processRelativeTime$6,
            mm: processRelativeTime$6,
            h: processRelativeTime$6,
            hh: processRelativeTime$6,
            d: processRelativeTime$6,
            dd: processRelativeTime$6,
            M: processRelativeTime$6,
            MM: processRelativeTime$6,
            y: processRelativeTime$6,
            yy: processRelativeTime$6
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('sq', {
        months: 'Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor'.split('_'),
        monthsShort: 'Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj'.split('_'),
        weekdays: 'E Diel_E Hënë_E Martë_E Mërkurë_E Enjte_E Premte_E Shtunë'.split('_'),
        weekdaysShort: 'Die_Hën_Mar_Mër_Enj_Pre_Sht'.split('_'),
        weekdaysMin: 'D_H_Ma_Më_E_P_Sh'.split('_'),
        weekdaysParseExact: true,
        meridiemParse: /PD|MD/,
        isPM: function (input) {
            return input.charAt(0) === 'M';
        },
        meridiem: function (hours, minutes, isLower) {
            return hours < 12 ? 'PD' : 'MD';
        },
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Sot në] LT',
            nextDay: '[Nesër në] LT',
            nextWeek: 'dddd [në] LT',
            lastDay: '[Dje në] LT',
            lastWeek: 'dddd [e kaluar në] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'në %s',
            past: '%s më parë',
            s: 'disa sekonda',
            ss: '%d sekonda',
            m: 'një minutë',
            mm: '%d minuta',
            h: 'një orë',
            hh: '%d orë',
            d: 'një ditë',
            dd: '%d ditë',
            M: 'një muaj',
            MM: '%d muaj',
            y: 'një vit',
            yy: '%d vite'
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var translator$1 = {
        words: { //Different grammatical cases
            ss: ['секунда', 'секунде', 'секунди'],
            m: ['један минут', 'једне минуте'],
            mm: ['минут', 'минуте', 'минута'],
            h: ['један сат', 'једног сата'],
            hh: ['сат', 'сата', 'сати'],
            dd: ['дан', 'дана', 'дана'],
            MM: ['месец', 'месеца', 'месеци'],
            yy: ['година', 'године', 'година']
        },
        correctGrammaticalCase: function (number, wordKey) {
            return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]);
        },
        translate: function (number, withoutSuffix, key) {
            var wordKey = translator$1.words[key];
            if (key.length === 1) {
                return withoutSuffix ? wordKey[0] : wordKey[1];
            } else {
                return number + ' ' + translator$1.correctGrammaticalCase(number, wordKey);
            }
        }
    };

    hooks.defineLocale('sr-cyrl', {
        months: 'јануар_фебруар_март_април_мај_јун_јул_август_септембар_октобар_новембар_децембар'.split('_'),
        monthsShort: 'јан._феб._мар._апр._мај_јун_јул_авг._сеп._окт._нов._дец.'.split('_'),
        monthsParseExact: true,
        weekdays: 'недеља_понедељак_уторак_среда_четвртак_петак_субота'.split('_'),
        weekdaysShort: 'нед._пон._уто._сре._чет._пет._суб.'.split('_'),
        weekdaysMin: 'не_по_ут_ср_че_пе_су'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm',
            LLLL: 'dddd, D. MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[данас у] LT',
            nextDay: '[сутра у] LT',
            nextWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[у] [недељу] [у] LT';
                    case 3:
                        return '[у] [среду] [у] LT';
                    case 6:
                        return '[у] [суботу] [у] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[у] dddd [у] LT';
                }
            },
            lastDay: '[јуче у] LT',
            lastWeek: function () {
                var lastWeekDays = [
                    '[прошле] [недеље] [у] LT',
                    '[прошлог] [понедељка] [у] LT',
                    '[прошлог] [уторка] [у] LT',
                    '[прошле] [среде] [у] LT',
                    '[прошлог] [четвртка] [у] LT',
                    '[прошлог] [петка] [у] LT',
                    '[прошле] [суботе] [у] LT'
                ];
                return lastWeekDays[this.day()];
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'за %s',
            past: 'пре %s',
            s: 'неколико секунди',
            ss: translator$1.translate,
            m: translator$1.translate,
            mm: translator$1.translate,
            h: translator$1.translate,
            hh: translator$1.translate,
            d: 'дан',
            dd: translator$1.translate,
            M: 'месец',
            MM: translator$1.translate,
            y: 'годину',
            yy: translator$1.translate
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var translator$2 = {
        words: { //Different grammatical cases
            ss: ['sekunda', 'sekunde', 'sekundi'],
            m: ['jedan minut', 'jedne minute'],
            mm: ['minut', 'minute', 'minuta'],
            h: ['jedan sat', 'jednog sata'],
            hh: ['sat', 'sata', 'sati'],
            dd: ['dan', 'dana', 'dana'],
            MM: ['mesec', 'meseca', 'meseci'],
            yy: ['godina', 'godine', 'godina']
        },
        correctGrammaticalCase: function (number, wordKey) {
            return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]);
        },
        translate: function (number, withoutSuffix, key) {
            var wordKey = translator$2.words[key];
            if (key.length === 1) {
                return withoutSuffix ? wordKey[0] : wordKey[1];
            } else {
                return number + ' ' + translator$2.correctGrammaticalCase(number, wordKey);
            }
        }
    };

    hooks.defineLocale('sr', {
        months: 'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split('_'),
        monthsShort: 'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split('_'),
        monthsParseExact: true,
        weekdays: 'nedelja_ponedeljak_utorak_sreda_četvrtak_petak_subota'.split('_'),
        weekdaysShort: 'ned._pon._uto._sre._čet._pet._sub.'.split('_'),
        weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM YYYY',
            LLL: 'D. MMMM YYYY H:mm',
            LLLL: 'dddd, D. MMMM YYYY H:mm'
        },
        calendar: {
            sameDay: '[danas u] LT',
            nextDay: '[sutra u] LT',
            nextWeek: function () {
                switch (this.day()) {
                    case 0:
                        return '[u] [nedelju] [u] LT';
                    case 3:
                        return '[u] [sredu] [u] LT';
                    case 6:
                        return '[u] [subotu] [u] LT';
                    case 1:
                    case 2:
                    case 4:
                    case 5:
                        return '[u] dddd [u] LT';
                }
            },
            lastDay: '[juče u] LT',
            lastWeek: function () {
                var lastWeekDays = [
                    '[prošle] [nedelje] [u] LT',
                    '[prošlog] [ponedeljka] [u] LT',
                    '[prošlog] [utorka] [u] LT',
                    '[prošle] [srede] [u] LT',
                    '[prošlog] [četvrtka] [u] LT',
                    '[prošlog] [petka] [u] LT',
                    '[prošle] [subote] [u] LT'
                ];
                return lastWeekDays[this.day()];
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'za %s',
            past: 'pre %s',
            s: 'nekoliko sekundi',
            ss: translator$2.translate,
            m: translator$2.translate,
            mm: translator$2.translate,
            h: translator$2.translate,
            hh: translator$2.translate,
            d: 'dan',
            dd: translator$2.translate,
            M: 'mesec',
            MM: translator$2.translate,
            y: 'godinu',
            yy: translator$2.translate
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('ss', {
        months: "Bhimbidvwane_Indlovana_Indlov'lenkhulu_Mabasa_Inkhwekhweti_Inhlaba_Kholwane_Ingci_Inyoni_Imphala_Lweti_Ingongoni".split('_'),
        monthsShort: 'Bhi_Ina_Inu_Mab_Ink_Inh_Kho_Igc_Iny_Imp_Lwe_Igo'.split('_'),
        weekdays: 'Lisontfo_Umsombuluko_Lesibili_Lesitsatfu_Lesine_Lesihlanu_Umgcibelo'.split('_'),
        weekdaysShort: 'Lis_Umb_Lsb_Les_Lsi_Lsh_Umg'.split('_'),
        weekdaysMin: 'Li_Us_Lb_Lt_Ls_Lh_Ug'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'h:mm A',
            LTS: 'h:mm:ss A',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY h:mm A',
            LLLL: 'dddd, D MMMM YYYY h:mm A'
        },
        calendar: {
            sameDay: '[Namuhla nga] LT',
            nextDay: '[Kusasa nga] LT',
            nextWeek: 'dddd [nga] LT',
            lastDay: '[Itolo nga] LT',
            lastWeek: 'dddd [leliphelile] [nga] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'nga %s',
            past: 'wenteka nga %s',
            s: 'emizuzwana lomcane',
            ss: '%d mzuzwana',
            m: 'umzuzu',
            mm: '%d emizuzu',
            h: 'lihora',
            hh: '%d emahora',
            d: 'lilanga',
            dd: '%d emalanga',
            M: 'inyanga',
            MM: '%d tinyanga',
            y: 'umnyaka',
            yy: '%d iminyaka'
        },
        meridiemParse: /ekuseni|emini|entsambama|ebusuku/,
        meridiem: function (hours, minutes, isLower) {
            if (hours < 11) {
                return 'ekuseni';
            } else if (hours < 15) {
                return 'emini';
            } else if (hours < 19) {
                return 'entsambama';
            } else {
                return 'ebusuku';
            }
        },
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'ekuseni') {
                return hour;
            } else if (meridiem === 'emini') {
                return hour >= 11 ? hour : hour + 12;
            } else if (meridiem === 'entsambama' || meridiem === 'ebusuku') {
                if (hour === 0) {
                    return 0;
                }
                return hour + 12;
            }
        },
        dayOfMonthOrdinalParse: /\d{1,2}/,
        ordinal: '%d',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('sv', {
        months: 'januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december'.split('_'),
        monthsShort: 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'),
        weekdays: 'söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag'.split('_'),
        weekdaysShort: 'sön_mån_tis_ons_tor_fre_lör'.split('_'),
        weekdaysMin: 'sö_må_ti_on_to_fr_lö'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'YYYY-MM-DD',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY [kl.] HH:mm',
            LLLL: 'dddd D MMMM YYYY [kl.] HH:mm',
            lll: 'D MMM YYYY HH:mm',
            llll: 'ddd D MMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Idag] LT',
            nextDay: '[Imorgon] LT',
            lastDay: '[Igår] LT',
            nextWeek: '[På] dddd LT',
            lastWeek: '[I] dddd[s] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'om %s',
            past: 'för %s sedan',
            s: 'några sekunder',
            ss: '%d sekunder',
            m: 'en minut',
            mm: '%d minuter',
            h: 'en timme',
            hh: '%d timmar',
            d: 'en dag',
            dd: '%d dagar',
            M: 'en månad',
            MM: '%d månader',
            y: 'ett år',
            yy: '%d år'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(e|a)/,
        ordinal: function (number) {
            var b = number % 10,
                output = (~~(number % 100 / 10) === 1) ? 'e' :
                    (b === 1) ? 'a' :
                        (b === 2) ? 'a' :
                            (b === 3) ? 'e' : 'e';
            return number + output;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('sw', {
        months: 'Januari_Februari_Machi_Aprili_Mei_Juni_Julai_Agosti_Septemba_Oktoba_Novemba_Desemba'.split('_'),
        monthsShort: 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ago_Sep_Okt_Nov_Des'.split('_'),
        weekdays: 'Jumapili_Jumatatu_Jumanne_Jumatano_Alhamisi_Ijumaa_Jumamosi'.split('_'),
        weekdaysShort: 'Jpl_Jtat_Jnne_Jtan_Alh_Ijm_Jmos'.split('_'),
        weekdaysMin: 'J2_J3_J4_J5_Al_Ij_J1'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[leo saa] LT',
            nextDay: '[kesho saa] LT',
            nextWeek: '[wiki ijayo] dddd [saat] LT',
            lastDay: '[jana] LT',
            lastWeek: '[wiki iliyopita] dddd [saat] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s baadaye',
            past: 'tokea %s',
            s: 'hivi punde',
            ss: 'sekunde %d',
            m: 'dakika moja',
            mm: 'dakika %d',
            h: 'saa limoja',
            hh: 'masaa %d',
            d: 'siku moja',
            dd: 'masiku %d',
            M: 'mwezi mmoja',
            MM: 'miezi %d',
            y: 'mwaka mmoja',
            yy: 'miaka %d'
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var symbolMap$e = {
        '1': '௧',
        '2': '௨',
        '3': '௩',
        '4': '௪',
        '5': '௫',
        '6': '௬',
        '7': '௭',
        '8': '௮',
        '9': '௯',
        '0': '௦'
    }, numberMap$d = {
        '௧': '1',
        '௨': '2',
        '௩': '3',
        '௪': '4',
        '௫': '5',
        '௬': '6',
        '௭': '7',
        '௮': '8',
        '௯': '9',
        '௦': '0'
    };

    hooks.defineLocale('ta', {
        months: 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'),
        monthsShort: 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'),
        weekdays: 'ஞாயிற்றுக்கிழமை_திங்கட்கிழமை_செவ்வாய்கிழமை_புதன்கிழமை_வியாழக்கிழமை_வெள்ளிக்கிழமை_சனிக்கிழமை'.split('_'),
        weekdaysShort: 'ஞாயிறு_திங்கள்_செவ்வாய்_புதன்_வியாழன்_வெள்ளி_சனி'.split('_'),
        weekdaysMin: 'ஞா_தி_செ_பு_வி_வெ_ச'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY, HH:mm',
            LLLL: 'dddd, D MMMM YYYY, HH:mm'
        },
        calendar: {
            sameDay: '[இன்று] LT',
            nextDay: '[நாளை] LT',
            nextWeek: 'dddd, LT',
            lastDay: '[நேற்று] LT',
            lastWeek: '[கடந்த வாரம்] dddd, LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s இல்',
            past: '%s முன்',
            s: 'ஒரு சில விநாடிகள்',
            ss: '%d விநாடிகள்',
            m: 'ஒரு நிமிடம்',
            mm: '%d நிமிடங்கள்',
            h: 'ஒரு மணி நேரம்',
            hh: '%d மணி நேரம்',
            d: 'ஒரு நாள்',
            dd: '%d நாட்கள்',
            M: 'ஒரு மாதம்',
            MM: '%d மாதங்கள்',
            y: 'ஒரு வருடம்',
            yy: '%d ஆண்டுகள்'
        },
        dayOfMonthOrdinalParse: /\d{1,2}வது/,
        ordinal: function (number) {
            return number + 'வது';
        },
        preparse: function (string) {
            return string.replace(/[௧௨௩௪௫௬௭௮௯௦]/g, function (match) {
                return numberMap$d[match];
            });
        },
        postformat: function (string) {
            return string.replace(/\d/g, function (match) {
                return symbolMap$e[match];
            });
        },
        // refer http://ta.wikipedia.org/s/1er1
        meridiemParse: /யாமம்|வைகறை|காலை|நண்பகல்|எற்பாடு|மாலை/,
        meridiem: function (hour, minute, isLower) {
            if (hour < 2) {
                return ' யாமம்';
            } else if (hour < 6) {
                return ' வைகறை';  // வைகறை
            } else if (hour < 10) {
                return ' காலை'; // காலை
            } else if (hour < 14) {
                return ' நண்பகல்'; // நண்பகல்
            } else if (hour < 18) {
                return ' எற்பாடு'; // எற்பாடு
            } else if (hour < 22) {
                return ' மாலை'; // மாலை
            } else {
                return ' யாமம்';
            }
        },
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'யாமம்') {
                return hour < 2 ? hour : hour + 12;
            } else if (meridiem === 'வைகறை' || meridiem === 'காலை') {
                return hour;
            } else if (meridiem === 'நண்பகல்') {
                return hour >= 10 ? hour : hour + 12;
            } else {
                return hour + 12;
            }
        },
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 6  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('te', {
        months: 'జనవరి_ఫిబ్రవరి_మార్చి_ఏప్రిల్_మే_జూన్_జూలై_ఆగస్టు_సెప్టెంబర్_అక్టోబర్_నవంబర్_డిసెంబర్'.split('_'),
        monthsShort: 'జన._ఫిబ్ర._మార్చి_ఏప్రి._మే_జూన్_జూలై_ఆగ._సెప్._అక్టో._నవ._డిసె.'.split('_'),
        monthsParseExact: true,
        weekdays: 'ఆదివారం_సోమవారం_మంగళవారం_బుధవారం_గురువారం_శుక్రవారం_శనివారం'.split('_'),
        weekdaysShort: 'ఆది_సోమ_మంగళ_బుధ_గురు_శుక్ర_శని'.split('_'),
        weekdaysMin: 'ఆ_సో_మం_బు_గు_శు_శ'.split('_'),
        longDateFormat: {
            LT: 'A h:mm',
            LTS: 'A h:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY, A h:mm',
            LLLL: 'dddd, D MMMM YYYY, A h:mm'
        },
        calendar: {
            sameDay: '[నేడు] LT',
            nextDay: '[రేపు] LT',
            nextWeek: 'dddd, LT',
            lastDay: '[నిన్న] LT',
            lastWeek: '[గత] dddd, LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s లో',
            past: '%s క్రితం',
            s: 'కొన్ని క్షణాలు',
            ss: '%d సెకన్లు',
            m: 'ఒక నిమిషం',
            mm: '%d నిమిషాలు',
            h: 'ఒక గంట',
            hh: '%d గంటలు',
            d: 'ఒక రోజు',
            dd: '%d రోజులు',
            M: 'ఒక నెల',
            MM: '%d నెలలు',
            y: 'ఒక సంవత్సరం',
            yy: '%d సంవత్సరాలు'
        },
        dayOfMonthOrdinalParse: /\d{1,2}వ/,
        ordinal: '%dవ',
        meridiemParse: /రాత్రి|ఉదయం|మధ్యాహ్నం|సాయంత్రం/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'రాత్రి') {
                return hour < 4 ? hour : hour + 12;
            } else if (meridiem === 'ఉదయం') {
                return hour;
            } else if (meridiem === 'మధ్యాహ్నం') {
                return hour >= 10 ? hour : hour + 12;
            } else if (meridiem === 'సాయంత్రం') {
                return hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'రాత్రి';
            } else if (hour < 10) {
                return 'ఉదయం';
            } else if (hour < 17) {
                return 'మధ్యాహ్నం';
            } else if (hour < 20) {
                return 'సాయంత్రం';
            } else {
                return 'రాత్రి';
            }
        },
        week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 6  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('tet', {
        months: 'Janeiru_Fevereiru_Marsu_Abril_Maiu_Juñu_Jullu_Agustu_Setembru_Outubru_Novembru_Dezembru'.split('_'),
        monthsShort: 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'),
        weekdays: 'Domingu_Segunda_Tersa_Kuarta_Kinta_Sesta_Sabadu'.split('_'),
        weekdaysShort: 'Dom_Seg_Ters_Kua_Kint_Sest_Sab'.split('_'),
        weekdaysMin: 'Do_Seg_Te_Ku_Ki_Ses_Sa'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Ohin iha] LT',
            nextDay: '[Aban iha] LT',
            nextWeek: 'dddd [iha] LT',
            lastDay: '[Horiseik iha] LT',
            lastWeek: 'dddd [semana kotuk] [iha] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'iha %s',
            past: '%s liuba',
            s: 'minutu balun',
            ss: 'minutu %d',
            m: 'minutu ida',
            mm: 'minutu %d',
            h: 'oras ida',
            hh: 'oras %d',
            d: 'loron ida',
            dd: 'loron %d',
            M: 'fulan ida',
            MM: 'fulan %d',
            y: 'tinan ida',
            yy: 'tinan %d'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/,
        ordinal: function (number) {
            var b = number % 10,
                output = (~~(number % 100 / 10) === 1) ? 'th' :
                    (b === 1) ? 'st' :
                        (b === 2) ? 'nd' :
                            (b === 3) ? 'rd' : 'th';
            return number + output;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var suffixes$3 = {
        0: '-ум',
        1: '-ум',
        2: '-юм',
        3: '-юм',
        4: '-ум',
        5: '-ум',
        6: '-ум',
        7: '-ум',
        8: '-ум',
        9: '-ум',
        10: '-ум',
        12: '-ум',
        13: '-ум',
        20: '-ум',
        30: '-юм',
        40: '-ум',
        50: '-ум',
        60: '-ум',
        70: '-ум',
        80: '-ум',
        90: '-ум',
        100: '-ум'
    };

    hooks.defineLocale('tg', {
        months: 'январ_феврал_март_апрел_май_июн_июл_август_сентябр_октябр_ноябр_декабр'.split('_'),
        monthsShort: 'янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек'.split('_'),
        weekdays: 'якшанбе_душанбе_сешанбе_чоршанбе_панҷшанбе_ҷумъа_шанбе'.split('_'),
        weekdaysShort: 'яшб_дшб_сшб_чшб_пшб_ҷум_шнб'.split('_'),
        weekdaysMin: 'яш_дш_сш_чш_пш_ҷм_шб'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Имрӯз соати] LT',
            nextDay: '[Пагоҳ соати] LT',
            lastDay: '[Дирӯз соати] LT',
            nextWeek: 'dddd[и] [ҳафтаи оянда соати] LT',
            lastWeek: 'dddd[и] [ҳафтаи гузашта соати] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'баъди %s',
            past: '%s пеш',
            s: 'якчанд сония',
            m: 'як дақиқа',
            mm: '%d дақиқа',
            h: 'як соат',
            hh: '%d соат',
            d: 'як рӯз',
            dd: '%d рӯз',
            M: 'як моҳ',
            MM: '%d моҳ',
            y: 'як сол',
            yy: '%d сол'
        },
        meridiemParse: /шаб|субҳ|рӯз|бегоҳ/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === 'шаб') {
                return hour < 4 ? hour : hour + 12;
            } else if (meridiem === 'субҳ') {
                return hour;
            } else if (meridiem === 'рӯз') {
                return hour >= 11 ? hour : hour + 12;
            } else if (meridiem === 'бегоҳ') {
                return hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'шаб';
            } else if (hour < 11) {
                return 'субҳ';
            } else if (hour < 16) {
                return 'рӯз';
            } else if (hour < 19) {
                return 'бегоҳ';
            } else {
                return 'шаб';
            }
        },
        dayOfMonthOrdinalParse: /\d{1,2}-(ум|юм)/,
        ordinal: function (number) {
            var a = number % 10,
                b = number >= 100 ? 100 : null;
            return number + (suffixes$3[number] || suffixes$3[a] || suffixes$3[b]);
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('th', {
        months: 'มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม'.split('_'),
        monthsShort: 'ม.ค._ก.พ._มี.ค._เม.ย._พ.ค._มิ.ย._ก.ค._ส.ค._ก.ย._ต.ค._พ.ย._ธ.ค.'.split('_'),
        monthsParseExact: true,
        weekdays: 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์'.split('_'),
        weekdaysShort: 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์'.split('_'), // yes, three characters difference
        weekdaysMin: 'อา._จ._อ._พ._พฤ._ศ._ส.'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'H:mm',
            LTS: 'H:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY เวลา H:mm',
            LLLL: 'วันddddที่ D MMMM YYYY เวลา H:mm'
        },
        meridiemParse: /ก่อนเที่ยง|หลังเที่ยง/,
        isPM: function (input) {
            return input === 'หลังเที่ยง';
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 12) {
                return 'ก่อนเที่ยง';
            } else {
                return 'หลังเที่ยง';
            }
        },
        calendar: {
            sameDay: '[วันนี้ เวลา] LT',
            nextDay: '[พรุ่งนี้ เวลา] LT',
            nextWeek: 'dddd[หน้า เวลา] LT',
            lastDay: '[เมื่อวานนี้ เวลา] LT',
            lastWeek: '[วัน]dddd[ที่แล้ว เวลา] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'อีก %s',
            past: '%sที่แล้ว',
            s: 'ไม่กี่วินาที',
            ss: '%d วินาที',
            m: '1 นาที',
            mm: '%d นาที',
            h: '1 ชั่วโมง',
            hh: '%d ชั่วโมง',
            d: '1 วัน',
            dd: '%d วัน',
            M: '1 เดือน',
            MM: '%d เดือน',
            y: '1 ปี',
            yy: '%d ปี'
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('tl-ph', {
        months: 'Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre'.split('_'),
        monthsShort: 'Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis'.split('_'),
        weekdays: 'Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado'.split('_'),
        weekdaysShort: 'Lin_Lun_Mar_Miy_Huw_Biy_Sab'.split('_'),
        weekdaysMin: 'Li_Lu_Ma_Mi_Hu_Bi_Sab'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'MM/D/YYYY',
            LL: 'MMMM D, YYYY',
            LLL: 'MMMM D, YYYY HH:mm',
            LLLL: 'dddd, MMMM DD, YYYY HH:mm'
        },
        calendar: {
            sameDay: 'LT [ngayong araw]',
            nextDay: '[Bukas ng] LT',
            nextWeek: 'LT [sa susunod na] dddd',
            lastDay: 'LT [kahapon]',
            lastWeek: 'LT [noong nakaraang] dddd',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'sa loob ng %s',
            past: '%s ang nakalipas',
            s: 'ilang segundo',
            ss: '%d segundo',
            m: 'isang minuto',
            mm: '%d minuto',
            h: 'isang oras',
            hh: '%d oras',
            d: 'isang araw',
            dd: '%d araw',
            M: 'isang buwan',
            MM: '%d buwan',
            y: 'isang taon',
            yy: '%d taon'
        },
        dayOfMonthOrdinalParse: /\d{1,2}/,
        ordinal: function (number) {
            return number;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var numbersNouns = 'pagh_wa’_cha’_wej_loS_vagh_jav_Soch_chorgh_Hut'.split('_');

    function translateFuture(output) {
        var time = output;
        time = (output.indexOf('jaj') !== -1) ?
            time.slice(0, -3) + 'leS' :
            (output.indexOf('jar') !== -1) ?
                time.slice(0, -3) + 'waQ' :
                (output.indexOf('DIS') !== -1) ?
                    time.slice(0, -3) + 'nem' :
                    time + ' pIq';
        return time;
    }

    function translatePast(output) {
        var time = output;
        time = (output.indexOf('jaj') !== -1) ?
            time.slice(0, -3) + 'Hu’' :
            (output.indexOf('jar') !== -1) ?
                time.slice(0, -3) + 'wen' :
                (output.indexOf('DIS') !== -1) ?
                    time.slice(0, -3) + 'ben' :
                    time + ' ret';
        return time;
    }

    function translate$a(number, withoutSuffix, string, isFuture) {
        var numberNoun = numberAsNoun(number);
        switch (string) {
            case 'ss':
                return numberNoun + ' lup';
            case 'mm':
                return numberNoun + ' tup';
            case 'hh':
                return numberNoun + ' rep';
            case 'dd':
                return numberNoun + ' jaj';
            case 'MM':
                return numberNoun + ' jar';
            case 'yy':
                return numberNoun + ' DIS';
        }
    }

    function numberAsNoun(number) {
        var hundred = Math.floor((number % 1000) / 100),
            ten = Math.floor((number % 100) / 10),
            one = number % 10,
            word = '';
        if (hundred > 0) {
            word += numbersNouns[hundred] + 'vatlh';
        }
        if (ten > 0) {
            word += ((word !== '') ? ' ' : '') + numbersNouns[ten] + 'maH';
        }
        if (one > 0) {
            word += ((word !== '') ? ' ' : '') + numbersNouns[one];
        }
        return (word === '') ? 'pagh' : word;
    }

    hooks.defineLocale('tlh', {
        months: 'tera’ jar wa’_tera’ jar cha’_tera’ jar wej_tera’ jar loS_tera’ jar vagh_tera’ jar jav_tera’ jar Soch_tera’ jar chorgh_tera’ jar Hut_tera’ jar wa’maH_tera’ jar wa’maH wa’_tera’ jar wa’maH cha’'.split('_'),
        monthsShort: 'jar wa’_jar cha’_jar wej_jar loS_jar vagh_jar jav_jar Soch_jar chorgh_jar Hut_jar wa’maH_jar wa’maH wa’_jar wa’maH cha’'.split('_'),
        monthsParseExact: true,
        weekdays: 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'),
        weekdaysShort: 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'),
        weekdaysMin: 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[DaHjaj] LT',
            nextDay: '[wa’leS] LT',
            nextWeek: 'LLL',
            lastDay: '[wa’Hu’] LT',
            lastWeek: 'LLL',
            sameElse: 'L'
        },
        relativeTime: {
            future: translateFuture,
            past: translatePast,
            s: 'puS lup',
            ss: translate$a,
            m: 'wa’ tup',
            mm: translate$a,
            h: 'wa’ rep',
            hh: translate$a,
            d: 'wa’ jaj',
            dd: translate$a,
            M: 'wa’ jar',
            MM: translate$a,
            y: 'wa’ DIS',
            yy: translate$a
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    var suffixes$4 = {
        1: '\'inci',
        5: '\'inci',
        8: '\'inci',
        70: '\'inci',
        80: '\'inci',
        2: '\'nci',
        7: '\'nci',
        20: '\'nci',
        50: '\'nci',
        3: '\'üncü',
        4: '\'üncü',
        100: '\'üncü',
        6: '\'ncı',
        9: '\'uncu',
        10: '\'uncu',
        30: '\'uncu',
        60: '\'ıncı',
        90: '\'ıncı'
    };

    hooks.defineLocale('tr', {
        months: 'Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık'.split('_'),
        monthsShort: 'Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara'.split('_'),
        weekdays: 'Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi'.split('_'),
        weekdaysShort: 'Paz_Pts_Sal_Çar_Per_Cum_Cts'.split('_'),
        weekdaysMin: 'Pz_Pt_Sa_Ça_Pe_Cu_Ct'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[bugün saat] LT',
            nextDay: '[yarın saat] LT',
            nextWeek: '[gelecek] dddd [saat] LT',
            lastDay: '[dün] LT',
            lastWeek: '[geçen] dddd [saat] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s sonra',
            past: '%s önce',
            s: 'birkaç saniye',
            ss: '%d saniye',
            m: 'bir dakika',
            mm: '%d dakika',
            h: 'bir saat',
            hh: '%d saat',
            d: 'bir gün',
            dd: '%d gün',
            M: 'bir ay',
            MM: '%d ay',
            y: 'bir yıl',
            yy: '%d yıl'
        },
        ordinal: function (number, period) {
            switch (period) {
                case 'd':
                case 'D':
                case 'Do':
                case 'DD':
                    return number;
                default:
                    if (number === 0) {  // special case for zero
                        return number + '\'ıncı';
                    }
                    var a = number % 10,
                        b = number % 100 - a,
                        c = number >= 100 ? 100 : null;
                    return number + (suffixes$4[a] || suffixes$4[b] || suffixes$4[c]);
            }
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    // After the year there should be a slash and the amount of years since December 26, 1979 in Roman numerals.
    // This is currently too difficult (maybe even impossible) to add.
    hooks.defineLocale('tzl', {
        months: 'Januar_Fevraglh_Març_Avrïu_Mai_Gün_Julia_Guscht_Setemvar_Listopäts_Noemvar_Zecemvar'.split('_'),
        monthsShort: 'Jan_Fev_Mar_Avr_Mai_Gün_Jul_Gus_Set_Lis_Noe_Zec'.split('_'),
        weekdays: 'Súladi_Lúneçi_Maitzi_Márcuri_Xhúadi_Viénerçi_Sáturi'.split('_'),
        weekdaysShort: 'Súl_Lún_Mai_Már_Xhú_Vié_Sát'.split('_'),
        weekdaysMin: 'Sú_Lú_Ma_Má_Xh_Vi_Sá'.split('_'),
        longDateFormat: {
            LT: 'HH.mm',
            LTS: 'HH.mm.ss',
            L: 'DD.MM.YYYY',
            LL: 'D. MMMM [dallas] YYYY',
            LLL: 'D. MMMM [dallas] YYYY HH.mm',
            LLLL: 'dddd, [li] D. MMMM [dallas] YYYY HH.mm'
        },
        meridiemParse: /d\'o|d\'a/i,
        isPM: function (input) {
            return 'd\'o' === input.toLowerCase();
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours > 11) {
                return isLower ? 'd\'o' : 'D\'O';
            } else {
                return isLower ? 'd\'a' : 'D\'A';
            }
        },
        calendar: {
            sameDay: '[oxhi à] LT',
            nextDay: '[demà à] LT',
            nextWeek: 'dddd [à] LT',
            lastDay: '[ieiri à] LT',
            lastWeek: '[sür el] dddd [lasteu à] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'osprei %s',
            past: 'ja%s',
            s: processRelativeTime$7,
            ss: processRelativeTime$7,
            m: processRelativeTime$7,
            mm: processRelativeTime$7,
            h: processRelativeTime$7,
            hh: processRelativeTime$7,
            d: processRelativeTime$7,
            dd: processRelativeTime$7,
            M: processRelativeTime$7,
            MM: processRelativeTime$7,
            y: processRelativeTime$7,
            yy: processRelativeTime$7
        },
        dayOfMonthOrdinalParse: /\d{1,2}\./,
        ordinal: '%d.',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    function processRelativeTime$7(number, withoutSuffix, key, isFuture) {
        var format = {
            's': ['viensas secunds', '\'iensas secunds'],
            'ss': [number + ' secunds', '' + number + ' secunds'],
            'm': ['\'n míut', '\'iens míut'],
            'mm': [number + ' míuts', '' + number + ' míuts'],
            'h': ['\'n þora', '\'iensa þora'],
            'hh': [number + ' þoras', '' + number + ' þoras'],
            'd': ['\'n ziua', '\'iensa ziua'],
            'dd': [number + ' ziuas', '' + number + ' ziuas'],
            'M': ['\'n mes', '\'iens mes'],
            'MM': [number + ' mesen', '' + number + ' mesen'],
            'y': ['\'n ar', '\'iens ar'],
            'yy': [number + ' ars', '' + number + ' ars']
        };
        return isFuture ? format[key][0] : (withoutSuffix ? format[key][0] : format[key][1]);
    }

    //! moment.js locale configuration

    hooks.defineLocale('tzm-latn', {
        months: 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'),
        monthsShort: 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'),
        weekdays: 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'),
        weekdaysShort: 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'),
        weekdaysMin: 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[asdkh g] LT',
            nextDay: '[aska g] LT',
            nextWeek: 'dddd [g] LT',
            lastDay: '[assant g] LT',
            lastWeek: 'dddd [g] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'dadkh s yan %s',
            past: 'yan %s',
            s: 'imik',
            ss: '%d imik',
            m: 'minuḍ',
            mm: '%d minuḍ',
            h: 'saɛa',
            hh: '%d tassaɛin',
            d: 'ass',
            dd: '%d ossan',
            M: 'ayowr',
            MM: '%d iyyirn',
            y: 'asgas',
            yy: '%d isgasn'
        },
        week: {
            dow: 6, // Saturday is the first day of the week.
            doy: 12  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('tzm', {
        months: 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'),
        monthsShort: 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'),
        weekdays: 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'),
        weekdaysShort: 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'),
        weekdaysMin: 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[ⴰⵙⴷⵅ ⴴ] LT',
            nextDay: '[ⴰⵙⴽⴰ ⴴ] LT',
            nextWeek: 'dddd [ⴴ] LT',
            lastDay: '[ⴰⵚⴰⵏⵜ ⴴ] LT',
            lastWeek: 'dddd [ⴴ] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s',
            past: 'ⵢⴰⵏ %s',
            s: 'ⵉⵎⵉⴽ',
            ss: '%d ⵉⵎⵉⴽ',
            m: 'ⵎⵉⵏⵓⴺ',
            mm: '%d ⵎⵉⵏⵓⴺ',
            h: 'ⵙⴰⵄⴰ',
            hh: '%d ⵜⴰⵙⵙⴰⵄⵉⵏ',
            d: 'ⴰⵙⵙ',
            dd: '%d oⵙⵙⴰⵏ',
            M: 'ⴰⵢoⵓⵔ',
            MM: '%d ⵉⵢⵢⵉⵔⵏ',
            y: 'ⴰⵙⴳⴰⵙ',
            yy: '%d ⵉⵙⴳⴰⵙⵏ'
        },
        week: {
            dow: 6, // Saturday is the first day of the week.
            doy: 12  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js language configuration

    hooks.defineLocale('ug-cn', {
        months: 'يانۋار_فېۋرال_مارت_ئاپرېل_ماي_ئىيۇن_ئىيۇل_ئاۋغۇست_سېنتەبىر_ئۆكتەبىر_نويابىر_دېكابىر'.split(
            '_'
        ),
        monthsShort: 'يانۋار_فېۋرال_مارت_ئاپرېل_ماي_ئىيۇن_ئىيۇل_ئاۋغۇست_سېنتەبىر_ئۆكتەبىر_نويابىر_دېكابىر'.split(
            '_'
        ),
        weekdays: 'يەكشەنبە_دۈشەنبە_سەيشەنبە_چارشەنبە_پەيشەنبە_جۈمە_شەنبە'.split(
            '_'
        ),
        weekdaysShort: 'يە_دۈ_سە_چا_پە_جۈ_شە'.split('_'),
        weekdaysMin: 'يە_دۈ_سە_چا_پە_جۈ_شە'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'YYYY-MM-DD',
            LL: 'YYYY-يىلىM-ئاينىڭD-كۈنى',
            LLL: 'YYYY-يىلىM-ئاينىڭD-كۈنى، HH:mm',
            LLLL: 'dddd، YYYY-يىلىM-ئاينىڭD-كۈنى، HH:mm'
        },
        meridiemParse: /يېرىم كېچە|سەھەر|چۈشتىن بۇرۇن|چۈش|چۈشتىن كېيىن|كەچ/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (
                meridiem === 'يېرىم كېچە' ||
                meridiem === 'سەھەر' ||
                meridiem === 'چۈشتىن بۇرۇن'
            ) {
                return hour;
            } else if (meridiem === 'چۈشتىن كېيىن' || meridiem === 'كەچ') {
                return hour + 12;
            } else {
                return hour >= 11 ? hour : hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            var hm = hour * 100 + minute;
            if (hm < 600) {
                return 'يېرىم كېچە';
            } else if (hm < 900) {
                return 'سەھەر';
            } else if (hm < 1130) {
                return 'چۈشتىن بۇرۇن';
            } else if (hm < 1230) {
                return 'چۈش';
            } else if (hm < 1800) {
                return 'چۈشتىن كېيىن';
            } else {
                return 'كەچ';
            }
        },
        calendar: {
            sameDay: '[بۈگۈن سائەت] LT',
            nextDay: '[ئەتە سائەت] LT',
            nextWeek: '[كېلەركى] dddd [سائەت] LT',
            lastDay: '[تۆنۈگۈن] LT',
            lastWeek: '[ئالدىنقى] dddd [سائەت] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s كېيىن',
            past: '%s بۇرۇن',
            s: 'نەچچە سېكونت',
            ss: '%d سېكونت',
            m: 'بىر مىنۇت',
            mm: '%d مىنۇت',
            h: 'بىر سائەت',
            hh: '%d سائەت',
            d: 'بىر كۈن',
            dd: '%d كۈن',
            M: 'بىر ئاي',
            MM: '%d ئاي',
            y: 'بىر يىل',
            yy: '%d يىل'
        },

        dayOfMonthOrdinalParse: /\d{1,2}(-كۈنى|-ئاي|-ھەپتە)/,
        ordinal: function (number, period) {
            switch (period) {
                case 'd':
                case 'D':
                case 'DDD':
                    return number + '-كۈنى';
                case 'w':
                case 'W':
                    return number + '-ھەپتە';
                default:
                    return number;
            }
        },
        preparse: function (string) {
            return string.replace(/،/g, ',');
        },
        postformat: function (string) {
            return string.replace(/,/g, '،');
        },
        week: {
            // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效
            dow: 1, // Monday is the first day of the week.
            doy: 7 // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    function plural$6(word, num) {
        var forms = word.split('_');
        return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]);
    }
    function relativeTimeWithPlural$4(number, withoutSuffix, key) {
        var format = {
            'ss': withoutSuffix ? 'секунда_секунди_секунд' : 'секунду_секунди_секунд',
            'mm': withoutSuffix ? 'хвилина_хвилини_хвилин' : 'хвилину_хвилини_хвилин',
            'hh': withoutSuffix ? 'година_години_годин' : 'годину_години_годин',
            'dd': 'день_дні_днів',
            'MM': 'місяць_місяці_місяців',
            'yy': 'рік_роки_років'
        };
        if (key === 'm') {
            return withoutSuffix ? 'хвилина' : 'хвилину';
        }
        else if (key === 'h') {
            return withoutSuffix ? 'година' : 'годину';
        }
        else {
            return number + ' ' + plural$6(format[key], +number);
        }
    }
    function weekdaysCaseReplace(m, format) {
        var weekdays = {
            'nominative': 'неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота'.split('_'),
            'accusative': 'неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу'.split('_'),
            'genitive': 'неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи'.split('_')
        };

        if (!m) {
            return weekdays['nominative'];
        }

        var nounCase = (/(\[[ВвУу]\]) ?dddd/).test(format) ?
            'accusative' :
            ((/\[?(?:минулої|наступної)? ?\] ?dddd/).test(format) ?
                'genitive' :
                'nominative');
        return weekdays[nounCase][m.day()];
    }
    function processHoursFunction(str) {
        return function () {
            return str + 'о' + (this.hours() === 11 ? 'б' : '') + '] LT';
        };
    }

    hooks.defineLocale('uk', {
        months: {
            'format': 'січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня'.split('_'),
            'standalone': 'січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень'.split('_')
        },
        monthsShort: 'січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд'.split('_'),
        weekdays: weekdaysCaseReplace,
        weekdaysShort: 'нд_пн_вт_ср_чт_пт_сб'.split('_'),
        weekdaysMin: 'нд_пн_вт_ср_чт_пт_сб'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD.MM.YYYY',
            LL: 'D MMMM YYYY р.',
            LLL: 'D MMMM YYYY р., HH:mm',
            LLLL: 'dddd, D MMMM YYYY р., HH:mm'
        },
        calendar: {
            sameDay: processHoursFunction('[Сьогодні '),
            nextDay: processHoursFunction('[Завтра '),
            lastDay: processHoursFunction('[Вчора '),
            nextWeek: processHoursFunction('[У] dddd ['),
            lastWeek: function () {
                switch (this.day()) {
                    case 0:
                    case 3:
                    case 5:
                    case 6:
                        return processHoursFunction('[Минулої] dddd [').call(this);
                    case 1:
                    case 2:
                    case 4:
                        return processHoursFunction('[Минулого] dddd [').call(this);
                }
            },
            sameElse: 'L'
        },
        relativeTime: {
            future: 'за %s',
            past: '%s тому',
            s: 'декілька секунд',
            ss: relativeTimeWithPlural$4,
            m: relativeTimeWithPlural$4,
            mm: relativeTimeWithPlural$4,
            h: 'годину',
            hh: relativeTimeWithPlural$4,
            d: 'день',
            dd: relativeTimeWithPlural$4,
            M: 'місяць',
            MM: relativeTimeWithPlural$4,
            y: 'рік',
            yy: relativeTimeWithPlural$4
        },
        // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason
        meridiemParse: /ночі|ранку|дня|вечора/,
        isPM: function (input) {
            return /^(дня|вечора)$/.test(input);
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 4) {
                return 'ночі';
            } else if (hour < 12) {
                return 'ранку';
            } else if (hour < 17) {
                return 'дня';
            } else {
                return 'вечора';
            }
        },
        dayOfMonthOrdinalParse: /\d{1,2}-(й|го)/,
        ordinal: function (number, period) {
            switch (period) {
                case 'M':
                case 'd':
                case 'DDD':
                case 'w':
                case 'W':
                    return number + '-й';
                case 'D':
                    return number + '-го';
                default:
                    return number;
            }
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    var months$8 = [
        'جنوری',
        'فروری',
        'مارچ',
        'اپریل',
        'مئی',
        'جون',
        'جولائی',
        'اگست',
        'ستمبر',
        'اکتوبر',
        'نومبر',
        'دسمبر'
    ];
    var days$2 = [
        'اتوار',
        'پیر',
        'منگل',
        'بدھ',
        'جمعرات',
        'جمعہ',
        'ہفتہ'
    ];

    hooks.defineLocale('ur', {
        months: months$8,
        monthsShort: months$8,
        weekdays: days$2,
        weekdaysShort: days$2,
        weekdaysMin: days$2,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd، D MMMM YYYY HH:mm'
        },
        meridiemParse: /صبح|شام/,
        isPM: function (input) {
            return 'شام' === input;
        },
        meridiem: function (hour, minute, isLower) {
            if (hour < 12) {
                return 'صبح';
            }
            return 'شام';
        },
        calendar: {
            sameDay: '[آج بوقت] LT',
            nextDay: '[کل بوقت] LT',
            nextWeek: 'dddd [بوقت] LT',
            lastDay: '[گذشتہ روز بوقت] LT',
            lastWeek: '[گذشتہ] dddd [بوقت] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s بعد',
            past: '%s قبل',
            s: 'چند سیکنڈ',
            ss: '%d سیکنڈ',
            m: 'ایک منٹ',
            mm: '%d منٹ',
            h: 'ایک گھنٹہ',
            hh: '%d گھنٹے',
            d: 'ایک دن',
            dd: '%d دن',
            M: 'ایک ماہ',
            MM: '%d ماہ',
            y: 'ایک سال',
            yy: '%d سال'
        },
        preparse: function (string) {
            return string.replace(/،/g, ',');
        },
        postformat: function (string) {
            return string.replace(/,/g, '،');
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('uz-latn', {
        months: 'Yanvar_Fevral_Mart_Aprel_May_Iyun_Iyul_Avgust_Sentabr_Oktabr_Noyabr_Dekabr'.split('_'),
        monthsShort: 'Yan_Fev_Mar_Apr_May_Iyun_Iyul_Avg_Sen_Okt_Noy_Dek'.split('_'),
        weekdays: 'Yakshanba_Dushanba_Seshanba_Chorshanba_Payshanba_Juma_Shanba'.split('_'),
        weekdaysShort: 'Yak_Dush_Sesh_Chor_Pay_Jum_Shan'.split('_'),
        weekdaysMin: 'Ya_Du_Se_Cho_Pa_Ju_Sha'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'D MMMM YYYY, dddd HH:mm'
        },
        calendar: {
            sameDay: '[Bugun soat] LT [da]',
            nextDay: '[Ertaga] LT [da]',
            nextWeek: 'dddd [kuni soat] LT [da]',
            lastDay: '[Kecha soat] LT [da]',
            lastWeek: '[O\'tgan] dddd [kuni soat] LT [da]',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'Yaqin %s ichida',
            past: 'Bir necha %s oldin',
            s: 'soniya',
            ss: '%d soniya',
            m: 'bir daqiqa',
            mm: '%d daqiqa',
            h: 'bir soat',
            hh: '%d soat',
            d: 'bir kun',
            dd: '%d kun',
            M: 'bir oy',
            MM: '%d oy',
            y: 'bir yil',
            yy: '%d yil'
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 1st is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('uz', {
        months: 'январ_феврал_март_апрел_май_июн_июл_август_сентябр_октябр_ноябр_декабр'.split('_'),
        monthsShort: 'янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек'.split('_'),
        weekdays: 'Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба'.split('_'),
        weekdaysShort: 'Якш_Душ_Сеш_Чор_Пай_Жум_Шан'.split('_'),
        weekdaysMin: 'Як_Ду_Се_Чо_Па_Жу_Ша'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'D MMMM YYYY, dddd HH:mm'
        },
        calendar: {
            sameDay: '[Бугун соат] LT [да]',
            nextDay: '[Эртага] LT [да]',
            nextWeek: 'dddd [куни соат] LT [да]',
            lastDay: '[Кеча соат] LT [да]',
            lastWeek: '[Утган] dddd [куни соат] LT [да]',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'Якин %s ичида',
            past: 'Бир неча %s олдин',
            s: 'фурсат',
            ss: '%d фурсат',
            m: 'бир дакика',
            mm: '%d дакика',
            h: 'бир соат',
            hh: '%d соат',
            d: 'бир кун',
            dd: '%d кун',
            M: 'бир ой',
            MM: '%d ой',
            y: 'бир йил',
            yy: '%d йил'
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 7  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('vi', {
        months: 'tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12'.split('_'),
        monthsShort: 'Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12'.split('_'),
        monthsParseExact: true,
        weekdays: 'chủ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy'.split('_'),
        weekdaysShort: 'CN_T2_T3_T4_T5_T6_T7'.split('_'),
        weekdaysMin: 'CN_T2_T3_T4_T5_T6_T7'.split('_'),
        weekdaysParseExact: true,
        meridiemParse: /sa|ch/i,
        isPM: function (input) {
            return /^ch$/i.test(input);
        },
        meridiem: function (hours, minutes, isLower) {
            if (hours < 12) {
                return isLower ? 'sa' : 'SA';
            } else {
                return isLower ? 'ch' : 'CH';
            }
        },
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM [năm] YYYY',
            LLL: 'D MMMM [năm] YYYY HH:mm',
            LLLL: 'dddd, D MMMM [năm] YYYY HH:mm',
            l: 'DD/M/YYYY',
            ll: 'D MMM YYYY',
            lll: 'D MMM YYYY HH:mm',
            llll: 'ddd, D MMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[Hôm nay lúc] LT',
            nextDay: '[Ngày mai lúc] LT',
            nextWeek: 'dddd [tuần tới lúc] LT',
            lastDay: '[Hôm qua lúc] LT',
            lastWeek: 'dddd [tuần rồi lúc] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: '%s tới',
            past: '%s trước',
            s: 'vài giây',
            ss: '%d giây',
            m: 'một phút',
            mm: '%d phút',
            h: 'một giờ',
            hh: '%d giờ',
            d: 'một ngày',
            dd: '%d ngày',
            M: 'một tháng',
            MM: '%d tháng',
            y: 'một năm',
            yy: '%d năm'
        },
        dayOfMonthOrdinalParse: /\d{1,2}/,
        ordinal: function (number) {
            return number;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('x-pseudo', {
        months: 'J~áñúá~rý_F~ébrú~árý_~Márc~h_Áp~ríl_~Máý_~Júñé~_Júl~ý_Áú~gúst~_Sép~témb~ér_Ó~ctób~ér_Ñ~óvém~bér_~Décé~mbér'.split('_'),
        monthsShort: 'J~áñ_~Féb_~Már_~Ápr_~Máý_~Júñ_~Júl_~Áúg_~Sép_~Óct_~Ñóv_~Déc'.split('_'),
        monthsParseExact: true,
        weekdays: 'S~úñdá~ý_Mó~ñdáý~_Túé~sdáý~_Wéd~ñésd~áý_T~húrs~dáý_~Fríd~áý_S~átúr~dáý'.split('_'),
        weekdaysShort: 'S~úñ_~Móñ_~Túé_~Wéd_~Thú_~Frí_~Sát'.split('_'),
        weekdaysMin: 'S~ú_Mó~_Tú_~Wé_T~h_Fr~_Sá'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY HH:mm',
            LLLL: 'dddd, D MMMM YYYY HH:mm'
        },
        calendar: {
            sameDay: '[T~ódá~ý át] LT',
            nextDay: '[T~ómó~rró~w át] LT',
            nextWeek: 'dddd [át] LT',
            lastDay: '[Ý~ést~érdá~ý át] LT',
            lastWeek: '[L~ást] dddd [át] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'í~ñ %s',
            past: '%s á~gó',
            s: 'á ~féw ~sécó~ñds',
            ss: '%d s~écóñ~ds',
            m: 'á ~míñ~úté',
            mm: '%d m~íñú~tés',
            h: 'á~ñ hó~úr',
            hh: '%d h~óúrs',
            d: 'á ~dáý',
            dd: '%d d~áýs',
            M: 'á ~móñ~th',
            MM: '%d m~óñt~hs',
            y: 'á ~ýéár',
            yy: '%d ý~éárs'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
        ordinal: function (number) {
            var b = number % 10,
                output = (~~(number % 100 / 10) === 1) ? 'th' :
                    (b === 1) ? 'st' :
                        (b === 2) ? 'nd' :
                            (b === 3) ? 'rd' : 'th';
            return number + output;
        },
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('yo', {
        months: 'Sẹ́rẹ́_Èrèlè_Ẹrẹ̀nà_Ìgbé_Èbibi_Òkùdu_Agẹmo_Ògún_Owewe_Ọ̀wàrà_Bélú_Ọ̀pẹ̀̀'.split('_'),
        monthsShort: 'Sẹ́r_Èrl_Ẹrn_Ìgb_Èbi_Òkù_Agẹ_Ògú_Owe_Ọ̀wà_Bél_Ọ̀pẹ̀̀'.split('_'),
        weekdays: 'Àìkú_Ajé_Ìsẹ́gun_Ọjọ́rú_Ọjọ́bọ_Ẹtì_Àbámẹ́ta'.split('_'),
        weekdaysShort: 'Àìk_Ajé_Ìsẹ́_Ọjr_Ọjb_Ẹtì_Àbá'.split('_'),
        weekdaysMin: 'Àì_Aj_Ìs_Ọr_Ọb_Ẹt_Àb'.split('_'),
        longDateFormat: {
            LT: 'h:mm A',
            LTS: 'h:mm:ss A',
            L: 'DD/MM/YYYY',
            LL: 'D MMMM YYYY',
            LLL: 'D MMMM YYYY h:mm A',
            LLLL: 'dddd, D MMMM YYYY h:mm A'
        },
        calendar: {
            sameDay: '[Ònì ni] LT',
            nextDay: '[Ọ̀la ni] LT',
            nextWeek: 'dddd [Ọsẹ̀ tón\'bọ] [ni] LT',
            lastDay: '[Àna ni] LT',
            lastWeek: 'dddd [Ọsẹ̀ tólọ́] [ni] LT',
            sameElse: 'L'
        },
        relativeTime: {
            future: 'ní %s',
            past: '%s kọjá',
            s: 'ìsẹjú aayá die',
            ss: 'aayá %d',
            m: 'ìsẹjú kan',
            mm: 'ìsẹjú %d',
            h: 'wákati kan',
            hh: 'wákati %d',
            d: 'ọjọ́ kan',
            dd: 'ọjọ́ %d',
            M: 'osù kan',
            MM: 'osù %d',
            y: 'ọdún kan',
            yy: 'ọdún %d'
        },
        dayOfMonthOrdinalParse: /ọjọ́\s\d{1,2}/,
        ordinal: 'ọjọ́ %d',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4 // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('zh-cn', {
        months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
        monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
        weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
        weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'),
        weekdaysMin: '日_一_二_三_四_五_六'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'YYYY/MM/DD',
            LL: 'YYYY年M月D日',
            LLL: 'YYYY年M月D日Ah点mm分',
            LLLL: 'YYYY年M月D日ddddAh点mm分',
            l: 'YYYY/M/D',
            ll: 'YYYY年M月D日',
            lll: 'YYYY年M月D日 HH:mm',
            llll: 'YYYY年M月D日dddd HH:mm'
        },
        meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === '凌晨' || meridiem === '早上' ||
                meridiem === '上午') {
                return hour;
            } else if (meridiem === '下午' || meridiem === '晚上') {
                return hour + 12;
            } else {
                // '中午'
                return hour >= 11 ? hour : hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            var hm = hour * 100 + minute;
            if (hm < 600) {
                return '凌晨';
            } else if (hm < 900) {
                return '早上';
            } else if (hm < 1130) {
                return '上午';
            } else if (hm < 1230) {
                return '中午';
            } else if (hm < 1800) {
                return '下午';
            } else {
                return '晚上';
            }
        },
        calendar: {
            sameDay: '[今天]LT',
            nextDay: '[明天]LT',
            nextWeek: '[下]ddddLT',
            lastDay: '[昨天]LT',
            lastWeek: '[上]ddddLT',
            sameElse: 'L'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(日|月|周)/,
        ordinal: function (number, period) {
            switch (period) {
                case 'd':
                case 'D':
                case 'DDD':
                    return number + '日';
                case 'M':
                    return number + '月';
                case 'w':
                case 'W':
                    return number + '周';
                default:
                    return number;
            }
        },
        relativeTime: {
            future: '%s内',
            past: '%s前',
            s: '几秒',
            ss: '%d 秒',
            m: '1 分钟',
            mm: '%d 分钟',
            h: '1 小时',
            hh: '%d 小时',
            d: '1 天',
            dd: '%d 天',
            M: '1 个月',
            MM: '%d 个月',
            y: '1 年',
            yy: '%d 年'
        },
        week: {
            // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('zh-hk', {
        months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
        monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
        weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
        weekdaysShort: '週日_週一_週二_週三_週四_週五_週六'.split('_'),
        weekdaysMin: '日_一_二_三_四_五_六'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'YYYY/MM/DD',
            LL: 'YYYY年M月D日',
            LLL: 'YYYY年M月D日 HH:mm',
            LLLL: 'YYYY年M月D日dddd HH:mm',
            l: 'YYYY/M/D',
            ll: 'YYYY年M月D日',
            lll: 'YYYY年M月D日 HH:mm',
            llll: 'YYYY年M月D日dddd HH:mm'
        },
        meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') {
                return hour;
            } else if (meridiem === '中午') {
                return hour >= 11 ? hour : hour + 12;
            } else if (meridiem === '下午' || meridiem === '晚上') {
                return hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            var hm = hour * 100 + minute;
            if (hm < 600) {
                return '凌晨';
            } else if (hm < 900) {
                return '早上';
            } else if (hm < 1130) {
                return '上午';
            } else if (hm < 1230) {
                return '中午';
            } else if (hm < 1800) {
                return '下午';
            } else {
                return '晚上';
            }
        },
        calendar: {
            sameDay: '[今天]LT',
            nextDay: '[明天]LT',
            nextWeek: '[下]ddddLT',
            lastDay: '[昨天]LT',
            lastWeek: '[上]ddddLT',
            sameElse: 'L'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/,
        ordinal: function (number, period) {
            switch (period) {
                case 'd':
                case 'D':
                case 'DDD':
                    return number + '日';
                case 'M':
                    return number + '月';
                case 'w':
                case 'W':
                    return number + '週';
                default:
                    return number;
            }
        },
        relativeTime: {
            future: '%s內',
            past: '%s前',
            s: '幾秒',
            ss: '%d 秒',
            m: '1 分鐘',
            mm: '%d 分鐘',
            h: '1 小時',
            hh: '%d 小時',
            d: '1 天',
            dd: '%d 天',
            M: '1 個月',
            MM: '%d 個月',
            y: '1 年',
            yy: '%d 年'
        }
    });

    //! moment.js locale configuration

    hooks.defineLocale('zh-tw', {
        months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
        monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
        weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
        weekdaysShort: '週日_週一_週二_週三_週四_週五_週六'.split('_'),
        weekdaysMin: '日_一_二_三_四_五_六'.split('_'),
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'YYYY/MM/DD',
            LL: 'YYYY年M月D日',
            LLL: 'YYYY年M月D日 HH:mm',
            LLLL: 'YYYY年M月D日dddd HH:mm',
            l: 'YYYY/M/D',
            ll: 'YYYY年M月D日',
            lll: 'YYYY年M月D日 HH:mm',
            llll: 'YYYY年M月D日dddd HH:mm'
        },
        meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
        meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') {
                return hour;
            } else if (meridiem === '中午') {
                return hour >= 11 ? hour : hour + 12;
            } else if (meridiem === '下午' || meridiem === '晚上') {
                return hour + 12;
            }
        },
        meridiem: function (hour, minute, isLower) {
            var hm = hour * 100 + minute;
            if (hm < 600) {
                return '凌晨';
            } else if (hm < 900) {
                return '早上';
            } else if (hm < 1130) {
                return '上午';
            } else if (hm < 1230) {
                return '中午';
            } else if (hm < 1800) {
                return '下午';
            } else {
                return '晚上';
            }
        },
        calendar: {
            sameDay: '[今天] LT',
            nextDay: '[明天] LT',
            nextWeek: '[下]dddd LT',
            lastDay: '[昨天] LT',
            lastWeek: '[上]dddd LT',
            sameElse: 'L'
        },
        dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/,
        ordinal: function (number, period) {
            switch (period) {
                case 'd':
                case 'D':
                case 'DDD':
                    return number + '日';
                case 'M':
                    return number + '月';
                case 'w':
                case 'W':
                    return number + '週';
                default:
                    return number;
            }
        },
        relativeTime: {
            future: '%s內',
            past: '%s前',
            s: '幾秒',
            ss: '%d 秒',
            m: '1 分鐘',
            mm: '%d 分鐘',
            h: '1 小時',
            hh: '%d 小時',
            d: '1 天',
            dd: '%d 天',
            M: '1 個月',
            MM: '%d 個月',
            y: '1 年',
            yy: '%d 年'
        }
    });

    hooks.locale('en');

    return hooks;

})));;
(function ($) {
    $.fn.extend({

        passwordValidation: function (_options, _callback, _confirmcallback) {
            //var _unicodeSpecialSet = "^\\x00-\\x1F\\x7F\\x80-\\x9F0-9A-Za-z"; //All chars other than above (and C0/C1)
            var CHARSETS = {
                upperCaseSet: "A-Z", 	//All UpperCase (Acii/Unicode)
                lowerCaseSet: "a-z", 	//All LowerCase (Acii/Unicode)
                digitSet: "0-9", 		//All digits (Acii/Unicode)
                specialSet: "\\x20-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\x7E\\x80-\\xFF", //All Other printable Ascii
            };

            //Ensure parameters are correctly defined
            if ($.isFunction(_options)) {
                if ($.isFunction(_callback)) {
                    if ($.isFunction(_confirmcallback)) {
                        console.log("Warning in passValidate: 3 or more callbacks were defined... First two will be used.");
                    }
                    _confirmcallback = _callback;
                }
                _callback = _options;
                _options = {};
            }

            var _defaults = {
                minLength: 12,		  //Minimum Length of password 
                minUpperCase: 2,	  //Minimum number of Upper Case Letters characters in password
                minLowerCase: 2,	  //Minimum number of Lower Case Letters characters in password
                minDigits: 2,		  //Minimum number of digits characters in password
                minSpecial: 2,		  //Minimum number of special characters in password
                maxRepeats: 5,		  //Maximum number of repeated alphanumeric characters in password dhgurAAAfjewd <- 3 A's
                maxConsecutive: 3,	  //Maximum number of alphanumeric characters from one set back to back
                noUpper: false,		  //Disallow Upper Case Lettera
                noLower: false,		  //Disallow Lower Case Letters
                noDigit: false,		  //Disallow Digits
                noSpecial: false,	  //Disallow Special Characters
                //NOT IMPLEMENTED YET allowUnicode: false,  //Switches Ascii Special Set out for Unicode Special Set 
                failRepeats: true,    //Disallow user to have x number of repeated alphanumeric characters ex.. ..A..a..A.. <- fails if maxRepeats <= 3 CASE INSENSITIVE
                failConsecutive: true,//Disallow user to have x number of consecutive alphanumeric characters from any set ex.. abc <- fails if maxConsecutive <= 3
                confirmField: undefined
            };

            //concatenate user options with _defaults

            _options = $.extend(_defaults, _options);
            if (_options.maxRepeats < 2) _options.maxRepeats = 2;

            function charsetToString() {
                return CHARSETS.upperCaseSet + CHARSETS.lowerCaseSet + CHARSETS.digitSet + CHARSETS.specialSet;
            }

            //GENERATE ALL REGEXs FOR EVERY CASE
            function buildPasswordRegex() {
                var cases = [];

                //if(_options.allowUnicode) CHARSETS.specialSet = _unicodeSpecialSet;
                if (_options.noUpper) cases.push({ "regex": "(?=" + CHARSETS.upperCaseSet + ")", "value": 5 });
                else cases.push({ "regex": "(?=" + ("[" + CHARSETS.upperCaseSet + "][^" + CHARSETS.upperCaseSet + "]*").repeat(_options.minUpperCase) + ")", "value": 5 });
                if (_options.noLower) cases.push({ "regex": "(?=" + CHARSETS.lowerCaseSet + ")", "value": 2 });
                else cases.push({ "regex": "(?=" + ("[" + CHARSETS.lowerCaseSet + "][^" + CHARSETS.lowerCaseSet + "]*").repeat(_options.minLowerCase) + ")", "value": 2 });
                if (_options.noDigit) cases.push({ "regex": "(?=" + CHARSETS.digitSet + ")", "value": 3 });
                else cases.push({ "regex": "(?=" + ("[" + CHARSETS.digitSet + "][^" + CHARSETS.digitSet + "]*").repeat(_options.minDigits) + ")", "value": 3 });
                if (_options.noSpecial) cases.push({ "regex": "(?=" + CHARSETS.specialSet + ")", "value": 4 });
                else cases.push({ "regex": "(?=" + ("[" + CHARSETS.specialSet + "][^" + CHARSETS.specialSet + "]*").repeat(_options.minSpecial) + ")", "value": 4 });

                cases.push({ "regex": "[" + charsetToString() + "]{" + _options.minLength + ",}", "value": 1 });

                return cases;
            }
            var _cases = buildPasswordRegex();

            var _element = this;
            var $confirmField = (_options.confirmField != undefined) ? $(_options.confirmField) : undefined;

            //Field validation on every captured event
            function validateField() {
                var failedCases = [];

                //Evaluate all verbose cases
                $.each(_cases, function (i, _case) {
                    if ($(_element).val().search(new RegExp(_case.regex, "g")) == -1) {
                        failedCases.push(_case.value);
                    }
                });
                if (_options.failRepeats && $(_element).val().search(new RegExp("(.)" + (".*\\1").repeat(_options.maxRepeats - 1), "gi")) != -1) {
                    //failedCases.push(resourcesMessages.SuppressionSuccess);//"Password can not contain " + _options.maxRepeats + " of the same character case insensitive.");
                }
                if (_options.failConsecutive && $(_element).val().search(new RegExp("(?=(.)" + ("\\1").repeat(_options.maxConsecutive) + ")", "g")) != -1) {
                    // failedCases.push(resourcesMessages.SuppressionSuccess);//"Password can not contain " + _options.maxRepeats + " of the same character case insensitive.");
                }

                //Determine if valid
                var validPassword = (failedCases.length == 0) && ($(_element).val().length >= _options.minLength);
                var fieldsMatch = true;
                if ($confirmField != undefined) {
                    fieldsMatch = ($confirmField.val() == $(_element).val());
                }

                _callback(_element, validPassword, validPassword && fieldsMatch, failedCases);
            }

            //Add custom classes to fields
            this.each(function () {
                //Validate field if it is already filled
                if ($(this).val()) {
                    validateField().apply(this);
                }

                $(this).toggleClass("jqPassField", true);
                if ($confirmField != undefined) {
                    $confirmField.toggleClass("jqPassConfirmField", true);
                }
            });

            //Add event bindings to the password fields
            return this.each(function () {
                $(this).bind('keyup focus input proprtychange mouseup', validateField);
                if ($confirmField != undefined) {
                    $confirmField.bind('keyup focus input proprtychange mouseup', validateField);
                }
            });
        }
    });
})(jQuery);;
/*!
 * Globalize
 *
 * http://github.com/jquery/globalize
 *
 * Copyright Software Freedom Conservancy, Inc.
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 */

(function( window, undefined ) {

var Globalize,
	// private variables
	regexHex,
	regexInfinity,
	regexParseFloat,
	regexTrim,
	// private JavaScript utility functions
	arrayIndexOf,
	endsWith,
	extend,
	isArray,
	isFunction,
	isObject,
	startsWith,
	trim,
	truncate,
	zeroPad,
	// private Globalization utility functions
	appendPreOrPostMatch,
	expandFormat,
	formatDate,
	formatNumber,
	getTokenRegExp,
	getEra,
	getEraYear,
	parseExact,
	parseNegativePattern;

// Global variable (Globalize) or CommonJS module (globalize)
Globalize = function( cultureSelector ) {
	return new Globalize.prototype.init( cultureSelector );
};

if ( typeof require !== "undefined" &&
	typeof exports !== "undefined" &&
	typeof module !== "undefined" ) {
	// Assume CommonJS
	module.exports = Globalize;
} else {
	// Export as global variable
	window.Globalize = Globalize;
}

Globalize.cultures = {};

Globalize.prototype = {
	constructor: Globalize,
	init: function( cultureSelector ) {
		this.cultures = Globalize.cultures;
		this.cultureSelector = cultureSelector;

		return this;
	}
};
Globalize.prototype.init.prototype = Globalize.prototype;

// 1. When defining a culture, all fields are required except the ones stated as optional.
// 2. Each culture should have a ".calendars" object with at least one calendar named "standard"
//    which serves as the default calendar in use by that culture.
// 3. Each culture should have a ".calendar" object which is the current calendar being used,
//    it may be dynamically changed at any time to one of the calendars in ".calendars".
Globalize.cultures[ "default" ] = {
	// A unique name for the culture in the form <language code>-<country/region code>
	name: "en",
	// the name of the culture in the english language
	englishName: "English",
	// the name of the culture in its own language
	nativeName: "English",
	// whether the culture uses right-to-left text
	isRTL: false,
	// "language" is used for so-called "specific" cultures.
	// For example, the culture "es-CL" means "Spanish, in Chili".
	// It represents the Spanish-speaking culture as it is in Chili,
	// which might have different formatting rules or even translations
	// than Spanish in Spain. A "neutral" culture is one that is not
	// specific to a region. For example, the culture "es" is the generic
	// Spanish culture, which may be a more generalized version of the language
	// that may or may not be what a specific culture expects.
	// For a specific culture like "es-CL", the "language" field refers to the
	// neutral, generic culture information for the language it is using.
	// This is not always a simple matter of the string before the dash.
	// For example, the "zh-Hans" culture is netural (Simplified Chinese).
	// And the "zh-SG" culture is Simplified Chinese in Singapore, whose lanugage
	// field is "zh-CHS", not "zh".
	// This field should be used to navigate from a specific culture to it's
	// more general, neutral culture. If a culture is already as general as it
	// can get, the language may refer to itself.
	language: "en",
	// numberFormat defines general number formatting rules, like the digits in
	// each grouping, the group separator, and how negative numbers are displayed.
	numberFormat: {
		// [negativePattern]
		// Note, numberFormat.pattern has no "positivePattern" unlike percent and currency,
		// but is still defined as an array for consistency with them.
		//   negativePattern: one of "(n)|-n|- n|n-|n -"
		pattern: [ "-n" ],
		// number of decimal places normally shown
		decimals: 2,
		// string that separates number groups, as in 1,000,000
		",": ",",
		// string that separates a number from the fractional portion, as in 1.99
		".": ".",
		// array of numbers indicating the size of each number group.
		// TODO: more detailed description and example
		groupSizes: [ 3 ],
		// symbol used for positive numbers
		"+": "+",
		// symbol used for negative numbers
		"-": "-",
		// symbol used for NaN (Not-A-Number)
		"NaN": "NaN",
		// symbol used for Negative Infinity
		negativeInfinity: "-Infinity",
		// symbol used for Positive Infinity
		positiveInfinity: "Infinity",
		percent: {
			// [negativePattern, positivePattern]
			//   negativePattern: one of "-n %|-n%|-%n|%-n|%n-|n-%|n%-|-% n|n %-|% n-|% -n|n- %"
			//   positivePattern: one of "n %|n%|%n|% n"
			pattern: [ "-n %", "n %" ],
			// number of decimal places normally shown
			decimals: 2,
			// array of numbers indicating the size of each number group.
			// TODO: more detailed description and example
			groupSizes: [ 3 ],
			// string that separates number groups, as in 1,000,000
			",": ",",
			// string that separates a number from the fractional portion, as in 1.99
			".": ".",
			// symbol used to represent a percentage
			symbol: "%"
		},
		currency: {
			// [negativePattern, positivePattern]
			//   negativePattern: one of "($n)|-$n|$-n|$n-|(n$)|-n$|n-$|n$-|-n $|-$ n|n $-|$ n-|$ -n|n- $|($ n)|(n $)"
			//   positivePattern: one of "$n|n$|$ n|n $"
			pattern: [ "($n)", "$n" ],
			// number of decimal places normally shown
			decimals: 2,
			// array of numbers indicating the size of each number group.
			// TODO: more detailed description and example
			groupSizes: [ 3 ],
			// string that separates number groups, as in 1,000,000
			",": ",",
			// string that separates a number from the fractional portion, as in 1.99
			".": ".",
			// symbol used to represent currency
			symbol: "$"
		}
	},
	// calendars defines all the possible calendars used by this culture.
	// There should be at least one defined with name "standard", and is the default
	// calendar used by the culture.
	// A calendar contains information about how dates are formatted, information about
	// the calendar's eras, a standard set of the date formats,
	// translations for day and month names, and if the calendar is not based on the Gregorian
	// calendar, conversion functions to and from the Gregorian calendar.
	calendars: {
		standard: {
			// name that identifies the type of calendar this is
			name: "Gregorian_USEnglish",
			// separator of parts of a date (e.g. "/" in 11/05/1955)
			"/": "/",
			// separator of parts of a time (e.g. ":" in 05:44 PM)
			":": ":",
			// the first day of the week (0 = Sunday, 1 = Monday, etc)
			firstDay: 0,
			days: {
				// full day names
				names: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ],
				// abbreviated day names
				namesAbbr: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ],
				// shortest day names
				namesShort: [ "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" ]
			},
			months: {
				// full month names (13 months for lunar calendards -- 13th month should be "" if not lunar)
				names: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", "" ],
				// abbreviated month names
				namesAbbr: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "" ]
			},
			// AM and PM designators in one of these forms:
			// The usual view, and the upper and lower case versions
			//   [ standard, lowercase, uppercase ]
			// The culture does not use AM or PM (likely all standard date formats use 24 hour time)
			//   null
			AM: [ "AM", "am", "AM" ],
			PM: [ "PM", "pm", "PM" ],
			eras: [
				// eras in reverse chronological order.
				// name: the name of the era in this culture (e.g. A.D., C.E.)
				// start: when the era starts in ticks (gregorian, gmt), null if it is the earliest supported era.
				// offset: offset in years from gregorian calendar
				{
					"name": "A.D.",
					"start": null,
					"offset": 0
				}
			],
			// when a two digit year is given, it will never be parsed as a four digit
			// year greater than this year (in the appropriate era for the culture)
			// Set it as a full year (e.g. 2029) or use an offset format starting from
			// the current year: "+19" would correspond to 2029 if the current year 2010.
			twoDigitYearMax: 2029,
			// set of predefined date and time patterns used by the culture
			// these represent the format someone in this culture would expect
			// to see given the portions of the date that are shown.
			patterns: {
				// short date pattern
				d: "M/d/yyyy",
				// long date pattern
				D: "dddd, MMMM dd, yyyy",
				// short time pattern
				t: "h:mm tt",
				// long time pattern
				T: "h:mm:ss tt",
				// long date, short time pattern
				f: "dddd, MMMM dd, yyyy h:mm tt",
				// long date, long time pattern
				F: "dddd, MMMM dd, yyyy h:mm:ss tt",
				// month/day pattern
				M: "MMMM dd",
				// month/year pattern
				Y: "yyyy MMMM",
				// S is a sortable format that does not vary by culture
				S: "yyyy\u0027-\u0027MM\u0027-\u0027dd\u0027T\u0027HH\u0027:\u0027mm\u0027:\u0027ss"
			}
			// optional fields for each calendar:
			/*
			monthsGenitive:
				Same as months but used when the day preceeds the month.
				Omit if the culture has no genitive distinction in month names.
				For an explaination of genitive months, see http://blogs.msdn.com/michkap/archive/2004/12/25/332259.aspx
			convert:
				Allows for the support of non-gregorian based calendars. This convert object is used to
				to convert a date to and from a gregorian calendar date to handle parsing and formatting.
				The two functions:
					fromGregorian( date )
						Given the date as a parameter, return an array with parts [ year, month, day ]
						corresponding to the non-gregorian based year, month, and day for the calendar.
					toGregorian( year, month, day )
						Given the non-gregorian year, month, and day, return a new Date() object
						set to the corresponding date in the gregorian calendar.
			*/
		}
	},
	// For localized strings
	messages: {}
};

Globalize.cultures[ "default" ].calendar = Globalize.cultures[ "default" ].calendars.standard;

Globalize.cultures.en = Globalize.cultures[ "default" ];

Globalize.cultureSelector = "en";

//
// private variables
//

regexHex = /^0x[a-f0-9]+$/i;
regexInfinity = /^[+\-]?infinity$/i;
regexParseFloat = /^[+\-]?\d*\.?\d*(e[+\-]?\d+)?$/;
regexTrim = /^\s+|\s+$/g;

//
// private JavaScript utility functions
//

arrayIndexOf = function( array, item ) {
	if ( array.indexOf ) {
		return array.indexOf( item );
	}
	for ( var i = 0, length = array.length; i < length; i++ ) {
		if ( array[i] === item ) {
			return i;
		}
	}
	return -1;
};

endsWith = function( value, pattern ) {
	return value.substr( value.length - pattern.length ) === pattern;
};

extend = function() {
	var options, name, src, copy, copyIsArray, clone,
		target = arguments[0] || {},
		i = 1,
		length = arguments.length,
		deep = false;

	// Handle a deep copy situation
	if ( typeof target === "boolean" ) {
		deep = target;
		target = arguments[1] || {};
		// skip the boolean and the target
		i = 2;
	}

	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target !== "object" && !isFunction(target) ) {
		target = {};
	}

	for ( ; i < length; i++ ) {
		// Only deal with non-null/undefined values
		if ( (options = arguments[ i ]) != null ) {
			// Extend the base object
			for ( name in options ) {
				src = target[ name ];
				copy = options[ name ];

				// Prevent never-ending loop
				if ( target === copy ) {
					continue;
				}

				// Recurse if we're merging plain objects or arrays
				if ( deep && copy && ( isObject(copy) || (copyIsArray = isArray(copy)) ) ) {
					if ( copyIsArray ) {
						copyIsArray = false;
						clone = src && isArray(src) ? src : [];

					} else {
						clone = src && isObject(src) ? src : {};
					}

					// Never move original objects, clone them
					target[ name ] = extend( deep, clone, copy );

				// Don't bring in undefined values
				} else if ( copy !== undefined ) {
					target[ name ] = copy;
				}
			}
		}
	}

	// Return the modified object
	return target;
};

isArray = Array.isArray || function( obj ) {
	return Object.prototype.toString.call( obj ) === "[object Array]";
};

isFunction = function( obj ) {
	return Object.prototype.toString.call( obj ) === "[object Function]";
};

isObject = function( obj ) {
	return Object.prototype.toString.call( obj ) === "[object Object]";
};

startsWith = function( value, pattern ) {
	return value.indexOf( pattern ) === 0;
};

trim = function( value ) {
	return ( value + "" ).replace( regexTrim, "" );
};

truncate = function( value ) {
	if ( isNaN( value ) ) {
		return NaN;
	}
	return Math[ value < 0 ? "ceil" : "floor" ]( value );
};

zeroPad = function( str, count, left ) {
	var l;
	for ( l = str.length; l < count; l += 1 ) {
		str = ( left ? ("0" + str) : (str + "0") );
	}
	return str;
};

//
// private Globalization utility functions
//

appendPreOrPostMatch = function( preMatch, strings ) {
	// appends pre- and post- token match strings while removing escaped characters.
	// Returns a single quote count which is used to determine if the token occurs
	// in a string literal.
	var quoteCount = 0,
		escaped = false;
	for ( var i = 0, il = preMatch.length; i < il; i++ ) {
		var c = preMatch.charAt( i );
		switch ( c ) {
			case "\'":
				if ( escaped ) {
					strings.push( "\'" );
				}
				else {
					quoteCount++;
				}
				escaped = false;
				break;
			case "\\":
				if ( escaped ) {
					strings.push( "\\" );
				}
				escaped = !escaped;
				break;
			default:
				strings.push( c );
				escaped = false;
				break;
		}
	}
	return quoteCount;
};

expandFormat = function( cal, format ) {
	// expands unspecified or single character date formats into the full pattern.
	format = format || "F";
	var pattern,
		patterns = cal.patterns,
		len = format.length;
	if ( len === 1 ) {
		pattern = patterns[ format ];
		if ( !pattern ) {
			throw "Invalid date format string \'" + format + "\'.";
		}
		format = pattern;
	}
	else if ( len === 2 && format.charAt(0) === "%" ) {
		// %X escape format -- intended as a custom format string that is only one character, not a built-in format.
		format = format.charAt( 1 );
	}
	return format;
};

formatDate = function( value, format, culture ) {
	var cal = culture.calendar,
		convert = cal.convert,
		ret;

	if ( !format || !format.length || format === "i" ) {
		if ( culture && culture.name.length ) {
			if ( convert ) {
				// non-gregorian calendar, so we cannot use built-in toLocaleString()
				ret = formatDate( value, cal.patterns.F, culture );
			}
			else {
				var eraDate = new Date( value.getTime() ),
					era = getEra( value, cal.eras );
				eraDate.setFullYear( getEraYear(value, cal, era) );
				ret = eraDate.toLocaleString();
			}
		}
		else {
			ret = value.toString();
		}
		return ret;
	}

	var eras = cal.eras,
		sortable = format === "s";
	format = expandFormat( cal, format );

	// Start with an empty string
	ret = [];
	var hour,
		zeros = [ "0", "00", "000" ],
		foundDay,
		checkedDay,
		dayPartRegExp = /([^d]|^)(d|dd)([^d]|$)/g,
		quoteCount = 0,
		tokenRegExp = getTokenRegExp(),
		converted;

	function padZeros( num, c ) {
		var r, s = num + "";
		if ( c > 1 && s.length < c ) {
			r = ( zeros[c - 2] + s);
			return r.substr( r.length - c, c );
		}
		else {
			r = s;
		}
		return r;
	}

	function hasDay() {
		if ( foundDay || checkedDay ) {
			return foundDay;
		}
		foundDay = dayPartRegExp.test( format );
		checkedDay = true;
		return foundDay;
	}

	function getPart( date, part ) {
		if ( converted ) {
			return converted[ part ];
		}
		switch ( part ) {
			case 0:
				return date.getFullYear();
			case 1:
				return date.getMonth();
			case 2:
				return date.getDate();
			default:
				throw "Invalid part value " + part;
		}
	}

	if ( !sortable && convert ) {
		converted = convert.fromGregorian( value );
	}

	for ( ; ; ) {
		// Save the current index
		var index = tokenRegExp.lastIndex,
			// Look for the next pattern
			ar = tokenRegExp.exec( format );

		// Append the text before the pattern (or the end of the string if not found)
		var preMatch = format.slice( index, ar ? ar.index : format.length );
		quoteCount += appendPreOrPostMatch( preMatch, ret );

		if ( !ar ) {
			break;
		}

		// do not replace any matches that occur inside a string literal.
		if ( quoteCount % 2 ) {
			ret.push( ar[0] );
			continue;
		}

		var current = ar[ 0 ],
			clength = current.length;

		switch ( current ) {
			case "ddd":
				//Day of the week, as a three-letter abbreviation
			case "dddd":
				// Day of the week, using the full name
				var names = ( clength === 3 ) ? cal.days.namesAbbr : cal.days.names;
				ret.push( names[value.getDay()] );
				break;
			case "d":
				// Day of month, without leading zero for single-digit days
			case "dd":
				// Day of month, with leading zero for single-digit days
				foundDay = true;
				ret.push(
					padZeros( getPart(value, 2), clength )
				);
				break;
			case "MMM":
				// Month, as a three-letter abbreviation
			case "MMMM":
				// Month, using the full name
				var part = getPart( value, 1 );
				ret.push(
					( cal.monthsGenitive && hasDay() ) ?
					( cal.monthsGenitive[ clength === 3 ? "namesAbbr" : "names" ][ part ] ) :
					( cal.months[ clength === 3 ? "namesAbbr" : "names" ][ part ] )
				);
				break;
			case "M":
				// Month, as digits, with no leading zero for single-digit months
			case "MM":
				// Month, as digits, with leading zero for single-digit months
				ret.push(
					padZeros( getPart(value, 1) + 1, clength )
				);
				break;
			case "y":
				// Year, as two digits, but with no leading zero for years less than 10
			case "yy":
				// Year, as two digits, with leading zero for years less than 10
			case "yyyy":
				// Year represented by four full digits
				part = converted ? converted[ 0 ] : getEraYear( value, cal, getEra(value, eras), sortable );
				if ( clength < 4 ) {
					part = part % 100;
				}
				ret.push(
					padZeros( part, clength )
				);
				break;
			case "h":
				// Hours with no leading zero for single-digit hours, using 12-hour clock
			case "hh":
				// Hours with leading zero for single-digit hours, using 12-hour clock
				hour = value.getHours() % 12;
				if ( hour === 0 ) hour = 12;
				ret.push(
					padZeros( hour, clength )
				);
				break;
			case "H":
				// Hours with no leading zero for single-digit hours, using 24-hour clock
			case "HH":
				// Hours with leading zero for single-digit hours, using 24-hour clock
				ret.push(
					padZeros( value.getHours(), clength )
				);
				break;
			case "m":
				// Minutes with no leading zero for single-digit minutes
			case "mm":
				// Minutes with leading zero for single-digit minutes
				ret.push(
					padZeros( value.getMinutes(), clength )
				);
				break;
			case "s":
				// Seconds with no leading zero for single-digit seconds
			case "ss":
				// Seconds with leading zero for single-digit seconds
				ret.push(
					padZeros( value.getSeconds(), clength )
				);
				break;
			case "t":
				// One character am/pm indicator ("a" or "p")
			case "tt":
				// Multicharacter am/pm indicator
				part = value.getHours() < 12 ? ( cal.AM ? cal.AM[0] : " " ) : ( cal.PM ? cal.PM[0] : " " );
				ret.push( clength === 1 ? part.charAt(0) : part );
				break;
			case "f":
				// Deciseconds
			case "ff":
				// Centiseconds
			case "fff":
				// Milliseconds
				ret.push(
					padZeros( value.getMilliseconds(), 3 ).substr( 0, clength )
				);
				break;
			case "z":
				// Time zone offset, no leading zero
			case "zz":
				// Time zone offset with leading zero
				hour = value.getTimezoneOffset() / 60;
				ret.push(
					( hour <= 0 ? "+" : "-" ) + padZeros( Math.floor(Math.abs(hour)), clength )
				);
				break;
			case "zzz":
				// Time zone offset with leading zero
				hour = value.getTimezoneOffset() / 60;
				ret.push(
					( hour <= 0 ? "+" : "-" ) + padZeros( Math.floor(Math.abs(hour)), 2 ) +
					// Hard coded ":" separator, rather than using cal.TimeSeparator
					// Repeated here for consistency, plus ":" was already assumed in date parsing.
					":" + padZeros( Math.abs(value.getTimezoneOffset() % 60), 2 )
				);
				break;
			case "g":
			case "gg":
				if ( cal.eras ) {
					ret.push(
						cal.eras[ getEra(value, eras) ].name
					);
				}
				break;
		case "/":
			ret.push( cal["/"] );
			break;
		default:
			throw "Invalid date format pattern \'" + current + "\'.";
		}
	}
	return ret.join( "" );
};

// formatNumber
(function() {
	var expandNumber;

	expandNumber = function( number, precision, formatInfo ) {
		var groupSizes = formatInfo.groupSizes,
			curSize = groupSizes[ 0 ],
			curGroupIndex = 1,
			factor = Math.pow( 10, precision ),
			rounded = Math.round( number * factor ) / factor;

		if ( !isFinite(rounded) ) {
			rounded = number;
		}
		number = rounded;

		var numberString = number+"",
			right = "",
			split = numberString.split( /e/i ),
			exponent = split.length > 1 ? parseInt( split[1], 10 ) : 0;
		numberString = split[ 0 ];
		split = numberString.split( "." );
		numberString = split[ 0 ];
		right = split.length > 1 ? split[ 1 ] : "";

		if ( exponent > 0 ) {
			right = zeroPad( right, exponent, false );
			numberString += right.slice( 0, exponent );
			right = right.substr( exponent );
		}
		else if ( exponent < 0 ) {
			exponent = -exponent;
			numberString = zeroPad( numberString, exponent + 1, true );
			right = numberString.slice( -exponent, numberString.length ) + right;
			numberString = numberString.slice( 0, -exponent );
		}

		if ( precision > 0 ) {
			right = formatInfo[ "." ] +
				( (right.length > precision) ? right.slice(0, precision) : zeroPad(right, precision) );
		}
		else {
			right = "";
		}

		var stringIndex = numberString.length - 1,
			sep = formatInfo[ "," ],
			ret = "";

		while ( stringIndex >= 0 ) {
			if ( curSize === 0 || curSize > stringIndex ) {
				return numberString.slice( 0, stringIndex + 1 ) + ( ret.length ? (sep + ret + right) : right );
			}
			ret = numberString.slice( stringIndex - curSize + 1, stringIndex + 1 ) + ( ret.length ? (sep + ret) : "" );

			stringIndex -= curSize;

			if ( curGroupIndex < groupSizes.length ) {
				curSize = groupSizes[ curGroupIndex ];
				curGroupIndex++;
			}
		}

		return numberString.slice( 0, stringIndex + 1 ) + sep + ret + right;
	};

	formatNumber = function( value, format, culture ) {
		if ( !isFinite(value) ) {
			if ( value === Infinity ) {
				return culture.numberFormat.positiveInfinity;
			}
			if ( value === -Infinity ) {
				return culture.numberFormat.negativeInfinity;
			}
			return culture.numberFormat.NaN;
		}
		if ( !format || format === "i" ) {
			return culture.name.length ? value.toLocaleString() : value.toString();
		}
		format = format || "D";

		var nf = culture.numberFormat,
			number = Math.abs( value ),
			precision = -1,
			pattern;
		if ( format.length > 1 ) precision = parseInt( format.slice(1), 10 );

		var current = format.charAt( 0 ).toUpperCase(),
			formatInfo;

		switch ( current ) {
			case "D":
				pattern = "n";
				number = truncate( number );
				if ( precision !== -1 ) {
					number = zeroPad( "" + number, precision, true );
				}
				if ( value < 0 ) number = "-" + number;
				break;
			case "N":
				formatInfo = nf;
				/* falls through */
			case "C":
				formatInfo = formatInfo || nf.currency;
				/* falls through */
			case "P":
				formatInfo = formatInfo || nf.percent;
				pattern = value < 0 ? formatInfo.pattern[ 0 ] : ( formatInfo.pattern[1] || "n" );
				if ( precision === -1 ) precision = formatInfo.decimals;
				number = expandNumber( number * (current === "P" ? 100 : 1), precision, formatInfo );
				break;
			default:
				throw "Bad number format specifier: " + current;
		}

		var patternParts = /n|\$|-|%/g,
			ret = "";
		for ( ; ; ) {
			var index = patternParts.lastIndex,
				ar = patternParts.exec( pattern );

			ret += pattern.slice( index, ar ? ar.index : pattern.length );

			if ( !ar ) {
				break;
			}

			switch ( ar[0] ) {
				case "n":
					ret += number;
					break;
				case "$":
					ret += nf.currency.symbol;
					break;
				case "-":
					// don't make 0 negative
					if ( /[1-9]/.test(number) ) {
						ret += nf[ "-" ];
					}
					break;
				case "%":
					ret += nf.percent.symbol;
					break;
			}
		}

		return ret;
	};

}());

getTokenRegExp = function() {
	// regular expression for matching date and time tokens in format strings.
	return (/\/|dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z|gg|g/g);
};

getEra = function( date, eras ) {
	if ( !eras ) return 0;
	var start, ticks = date.getTime();
	for ( var i = 0, l = eras.length; i < l; i++ ) {
		start = eras[ i ].start;
		if ( start === null || ticks >= start ) {
			return i;
		}
	}
	return 0;
};

getEraYear = function( date, cal, era, sortable ) {
	var year = date.getFullYear();
	if ( !sortable && cal.eras ) {
		// convert normal gregorian year to era-shifted gregorian
		// year by subtracting the era offset
		year -= cal.eras[ era ].offset;
	}
	return year;
};

// parseExact
(function() {
	var expandYear,
		getDayIndex,
		getMonthIndex,
		getParseRegExp,
		outOfRange,
		toUpper,
		toUpperArray;

	expandYear = function( cal, year ) {
		// expands 2-digit year into 4 digits.
		if ( year < 100 ) {
			var now = new Date(),
				era = getEra( now ),
				curr = getEraYear( now, cal, era ),
				twoDigitYearMax = cal.twoDigitYearMax;
			twoDigitYearMax = typeof twoDigitYearMax === "string" ? new Date().getFullYear() % 100 + parseInt( twoDigitYearMax, 10 ) : twoDigitYearMax;
			year += curr - ( curr % 100 );
			if ( year > twoDigitYearMax ) {
				year -= 100;
			}
		}
		return year;
	};

	getDayIndex = function	( cal, value, abbr ) {
		var ret,
			days = cal.days,
			upperDays = cal._upperDays;
		if ( !upperDays ) {
			cal._upperDays = upperDays = [
				toUpperArray( days.names ),
				toUpperArray( days.namesAbbr ),
				toUpperArray( days.namesShort )
			];
		}
		value = toUpper( value );
		if ( abbr ) {
			ret = arrayIndexOf( upperDays[1], value );
			if ( ret === -1 ) {
				ret = arrayIndexOf( upperDays[2], value );
			}
		}
		else {
			ret = arrayIndexOf( upperDays[0], value );
		}
		return ret;
	};

	getMonthIndex = function( cal, value, abbr ) {
		var months = cal.months,
			monthsGen = cal.monthsGenitive || cal.months,
			upperMonths = cal._upperMonths,
			upperMonthsGen = cal._upperMonthsGen;
		if ( !upperMonths ) {
			cal._upperMonths = upperMonths = [
				toUpperArray( months.names ),
				toUpperArray( months.namesAbbr )
			];
			cal._upperMonthsGen = upperMonthsGen = [
				toUpperArray( monthsGen.names ),
				toUpperArray( monthsGen.namesAbbr )
			];
		}
		value = toUpper( value );
		var i = arrayIndexOf( abbr ? upperMonths[1] : upperMonths[0], value );
		if ( i < 0 ) {
			i = arrayIndexOf( abbr ? upperMonthsGen[1] : upperMonthsGen[0], value );
		}
		return i;
	};

	getParseRegExp = function( cal, format ) {
		// converts a format string into a regular expression with groups that
		// can be used to extract date fields from a date string.
		// check for a cached parse regex.
		var re = cal._parseRegExp;
		if ( !re ) {
			cal._parseRegExp = re = {};
		}
		else {
			var reFormat = re[ format ];
			if ( reFormat ) {
				return reFormat;
			}
		}

		// expand single digit formats, then escape regular expression characters.
		var expFormat = expandFormat( cal, format ).replace( /([\^\$\.\*\+\?\|\[\]\(\)\{\}])/g, "\\\\$1" ),
			regexp = [ "^" ],
			groups = [],
			index = 0,
			quoteCount = 0,
			tokenRegExp = getTokenRegExp(),
			match;

		// iterate through each date token found.
		while ( (match = tokenRegExp.exec(expFormat)) !== null ) {
			var preMatch = expFormat.slice( index, match.index );
			index = tokenRegExp.lastIndex;

			// don't replace any matches that occur inside a string literal.
			quoteCount += appendPreOrPostMatch( preMatch, regexp );
			if ( quoteCount % 2 ) {
				regexp.push( match[0] );
				continue;
			}

			// add a regex group for the token.
			var m = match[ 0 ],
				len = m.length,
				add;
			switch ( m ) {
				case "dddd": case "ddd":
				case "MMMM": case "MMM":
				case "gg": case "g":
					add = "(\\D+)";
					break;
				case "tt": case "t":
					add = "(\\D*)";
					break;
				case "yyyy":
				case "fff":
				case "ff":
				case "f":
					add = "(\\d{" + len + "})";
					break;
				case "dd": case "d":
				case "MM": case "M":
				case "yy": case "y":
				case "HH": case "H":
				case "hh": case "h":
				case "mm": case "m":
				case "ss": case "s":
					add = "(\\d\\d?)";
					break;
				case "zzz":
					add = "([+-]?\\d\\d?:\\d{2})";
					break;
				case "zz": case "z":
					add = "([+-]?\\d\\d?)";
					break;
				case "/":
					add = "(\\/)";
					break;
				default:
					throw "Invalid date format pattern \'" + m + "\'.";
			}
			if ( add ) {
				regexp.push( add );
			}
			groups.push( match[0] );
		}
		appendPreOrPostMatch( expFormat.slice(index), regexp );
		regexp.push( "$" );

		// allow whitespace to differ when matching formats.
		var regexpStr = regexp.join( "" ).replace( /\s+/g, "\\s+" ),
			parseRegExp = { "regExp": regexpStr, "groups": groups };

		// cache the regex for this format.
		return re[ format ] = parseRegExp;
	};

	outOfRange = function( value, low, high ) {
		return value < low || value > high;
	};

	toUpper = function( value ) {
		// "he-IL" has non-breaking space in weekday names.
		return value.split( "\u00A0" ).join( " " ).toUpperCase();
	};

	toUpperArray = function( arr ) {
		var results = [];
		for ( var i = 0, l = arr.length; i < l; i++ ) {
			results[ i ] = toUpper( arr[i] );
		}
		return results;
	};

	parseExact = function( value, format, culture ) {
		// try to parse the date string by matching against the format string
		// while using the specified culture for date field names.
		value = trim( value );
		var cal = culture.calendar,
			// convert date formats into regular expressions with groupings.
			// use the regexp to determine the input format and extract the date fields.
			parseInfo = getParseRegExp( cal, format ),
			match = new RegExp( parseInfo.regExp ).exec( value );
		if ( match === null ) {
			return null;
		}
		// found a date format that matches the input.
		var groups = parseInfo.groups,
			era = null, year = null, month = null, date = null, weekDay = null,
			hour = 0, hourOffset, min = 0, sec = 0, msec = 0, tzMinOffset = null,
			pmHour = false;
		// iterate the format groups to extract and set the date fields.
		for ( var j = 0, jl = groups.length; j < jl; j++ ) {
			var matchGroup = match[ j + 1 ];
			if ( matchGroup ) {
				var current = groups[ j ],
					clength = current.length,
					matchInt = parseInt( matchGroup, 10 );
				switch ( current ) {
					case "dd": case "d":
						// Day of month.
						date = matchInt;
						// check that date is generally in valid range, also checking overflow below.
						if ( outOfRange(date, 1, 31) ) return null;
						break;
					case "MMM": case "MMMM":
						month = getMonthIndex( cal, matchGroup, clength === 3 );
						if ( outOfRange(month, 0, 11) ) return null;
						break;
					case "M": case "MM":
						// Month.
						month = matchInt - 1;
						if ( outOfRange(month, 0, 11) ) return null;
						break;
					case "y": case "yy":
					case "yyyy":
						year = clength < 4 ? expandYear( cal, matchInt ) : matchInt;
						if ( outOfRange(year, 0, 9999) ) return null;
						break;
					case "h": case "hh":
						// Hours (12-hour clock).
						hour = matchInt;
						if ( hour === 12 ) hour = 0;
						if ( outOfRange(hour, 0, 11) ) return null;
						break;
					case "H": case "HH":
						// Hours (24-hour clock).
						hour = matchInt;
						if ( outOfRange(hour, 0, 23) ) return null;
						break;
					case "m": case "mm":
						// Minutes.
						min = matchInt;
						if ( outOfRange(min, 0, 59) ) return null;
						break;
					case "s": case "ss":
						// Seconds.
						sec = matchInt;
						if ( outOfRange(sec, 0, 59) ) return null;
						break;
					case "tt": case "t":
						// AM/PM designator.
						// see if it is standard, upper, or lower case PM. If not, ensure it is at least one of
						// the AM tokens. If not, fail the parse for this format.
						pmHour = cal.PM && ( matchGroup === cal.PM[0] || matchGroup === cal.PM[1] || matchGroup === cal.PM[2] );
						if (
							!pmHour && (
								!cal.AM || ( matchGroup !== cal.AM[0] && matchGroup !== cal.AM[1] && matchGroup !== cal.AM[2] )
							)
						) return null;
						break;
					case "f":
						// Deciseconds.
					case "ff":
						// Centiseconds.
					case "fff":
						// Milliseconds.
						msec = matchInt * Math.pow( 10, 3 - clength );
						if ( outOfRange(msec, 0, 999) ) return null;
						break;
					case "ddd":
						// Day of week.
					case "dddd":
						// Day of week.
						weekDay = getDayIndex( cal, matchGroup, clength === 3 );
						if ( outOfRange(weekDay, 0, 6) ) return null;
						break;
					case "zzz":
						// Time zone offset in +/- hours:min.
						var offsets = matchGroup.split( /:/ );
						if ( offsets.length !== 2 ) return null;
						hourOffset = parseInt( offsets[0], 10 );
						if ( outOfRange(hourOffset, -12, 13) ) return null;
						var minOffset = parseInt( offsets[1], 10 );
						if ( outOfRange(minOffset, 0, 59) ) return null;
						tzMinOffset = ( hourOffset * 60 ) + ( startsWith(matchGroup, "-") ? -minOffset : minOffset );
						break;
					case "z": case "zz":
						// Time zone offset in +/- hours.
						hourOffset = matchInt;
						if ( outOfRange(hourOffset, -12, 13) ) return null;
						tzMinOffset = hourOffset * 60;
						break;
					case "g": case "gg":
						var eraName = matchGroup;
						if ( !eraName || !cal.eras ) return null;
						eraName = trim( eraName.toLowerCase() );
						for ( var i = 0, l = cal.eras.length; i < l; i++ ) {
							if ( eraName === cal.eras[i].name.toLowerCase() ) {
								era = i;
								break;
							}
						}
						// could not find an era with that name
						if ( era === null ) return null;
						break;
				}
			}
		}
		var result = new Date(), defaultYear, convert = cal.convert;
		defaultYear = convert ? convert.fromGregorian( result )[ 0 ] : result.getFullYear();
		if ( year === null ) {
			year = defaultYear;
		}
		else if ( cal.eras ) {
			// year must be shifted to normal gregorian year
			// but not if year was not specified, its already normal gregorian
			// per the main if clause above.
			year += cal.eras[( era || 0 )].offset;
		}
		// set default day and month to 1 and January, so if unspecified, these are the defaults
		// instead of the current day/month.
		if ( month === null ) {
			month = 0;
		}
		if ( date === null ) {
			date = 1;
		}
		// now have year, month, and date, but in the culture's calendar.
		// convert to gregorian if necessary
		if ( convert ) {
			result = convert.toGregorian( year, month, date );
			// conversion failed, must be an invalid match
			if ( result === null ) return null;
		}
		else {
			// have to set year, month and date together to avoid overflow based on current date.
			result.setFullYear( year, month, date );
			// check to see if date overflowed for specified month (only checked 1-31 above).
			if ( result.getDate() !== date ) return null;
			// invalid day of week.
			if ( weekDay !== null && result.getDay() !== weekDay ) {
				return null;
			}
		}
		// if pm designator token was found make sure the hours fit the 24-hour clock.
		if ( pmHour && hour < 12 ) {
			hour += 12;
		}
		result.setHours( hour, min, sec, msec );
		if ( tzMinOffset !== null ) {
			// adjust timezone to utc before applying local offset.
			var adjustedMin = result.getMinutes() - ( tzMinOffset + result.getTimezoneOffset() );
			// Safari limits hours and minutes to the range of -127 to 127.  We need to use setHours
			// to ensure both these fields will not exceed this range.	adjustedMin will range
			// somewhere between -1440 and 1500, so we only need to split this into hours.
			result.setHours( result.getHours() + parseInt(adjustedMin / 60, 10), adjustedMin % 60 );
		}
		return result;
	};
}());

parseNegativePattern = function( value, nf, negativePattern ) {
	var neg = nf[ "-" ],
		pos = nf[ "+" ],
		ret;
	switch ( negativePattern ) {
		case "n -":
			neg = " " + neg;
			pos = " " + pos;
			/* falls through */
		case "n-":
			if ( endsWith(value, neg) ) {
				ret = [ "-", value.substr(0, value.length - neg.length) ];
			}
			else if ( endsWith(value, pos) ) {
				ret = [ "+", value.substr(0, value.length - pos.length) ];
			}
			break;
		case "- n":
			neg += " ";
			pos += " ";
			/* falls through */
		case "-n":
			if ( startsWith(value, neg) ) {
				ret = [ "-", value.substr(neg.length) ];
			}
			else if ( startsWith(value, pos) ) {
				ret = [ "+", value.substr(pos.length) ];
			}
			break;
		case "(n)":
			if ( startsWith(value, "(") && endsWith(value, ")") ) {
				ret = [ "-", value.substr(1, value.length - 2) ];
			}
			break;
	}
	return ret || [ "", value ];
};

//
// public instance functions
//

Globalize.prototype.findClosestCulture = function( cultureSelector ) {
	return Globalize.findClosestCulture.call( this, cultureSelector );
};

Globalize.prototype.format = function( value, format, cultureSelector ) {
	return Globalize.format.call( this, value, format, cultureSelector );
};

Globalize.prototype.localize = function( key, cultureSelector ) {
	return Globalize.localize.call( this, key, cultureSelector );
};

Globalize.prototype.parseInt = function( value, radix, cultureSelector ) {
	return Globalize.parseInt.call( this, value, radix, cultureSelector );
};

Globalize.prototype.parseFloat = function( value, radix, cultureSelector ) {
	return Globalize.parseFloat.call( this, value, radix, cultureSelector );
};

Globalize.prototype.culture = function( cultureSelector ) {
	return Globalize.culture.call( this, cultureSelector );
};

//
// public singleton functions
//

Globalize.addCultureInfo = function( cultureName, baseCultureName, info ) {

	var base = {},
		isNew = false;

	if ( typeof cultureName !== "string" ) {
		// cultureName argument is optional string. If not specified, assume info is first
		// and only argument. Specified info deep-extends current culture.
		info = cultureName;
		cultureName = this.culture().name;
		base = this.cultures[ cultureName ];
	} else if ( typeof baseCultureName !== "string" ) {
		// baseCultureName argument is optional string. If not specified, assume info is second
		// argument. Specified info deep-extends specified culture.
		// If specified culture does not exist, create by deep-extending default
		info = baseCultureName;
		isNew = ( this.cultures[ cultureName ] == null );
		base = this.cultures[ cultureName ] || this.cultures[ "default" ];
	} else {
		// cultureName and baseCultureName specified. Assume a new culture is being created
		// by deep-extending an specified base culture
		isNew = true;
		base = this.cultures[ baseCultureName ];
	}

	this.cultures[ cultureName ] = extend(true, {},
		base,
		info
	);
	// Make the standard calendar the current culture if it's a new culture
	if ( isNew ) {
		this.cultures[ cultureName ].calendar = this.cultures[ cultureName ].calendars.standard;
	}
};

Globalize.findClosestCulture = function( name ) {
	var match;
	if ( !name ) {
		return this.findClosestCulture( this.cultureSelector ) || this.cultures[ "default" ];
	}
	if ( typeof name === "string" ) {
		name = name.split( "," );
	}
	if ( isArray(name) ) {
		var lang,
			cultures = this.cultures,
			list = name,
			i, l = list.length,
			prioritized = [];
		for ( i = 0; i < l; i++ ) {
			name = trim( list[i] );
			var pri, parts = name.split( ";" );
			lang = trim( parts[0] );
			if ( parts.length === 1 ) {
				pri = 1;
			}
			else {
				name = trim( parts[1] );
				if ( name.indexOf("q=") === 0 ) {
					name = name.substr( 2 );
					pri = parseFloat( name );
					pri = isNaN( pri ) ? 0 : pri;
				}
				else {
					pri = 1;
				}
			}
			prioritized.push({ lang: lang, pri: pri });
		}
		prioritized.sort(function( a, b ) {
			if ( a.pri < b.pri ) {
				return 1;
			} else if ( a.pri > b.pri ) {
				return -1;
			}
			return 0;
		});
		// exact match
		for ( i = 0; i < l; i++ ) {
			lang = prioritized[ i ].lang;
			match = cultures[ lang ];
			if ( match ) {
				return match;
			}
		}

		// neutral language match
		for ( i = 0; i < l; i++ ) {
			lang = prioritized[ i ].lang;
			do {
				var index = lang.lastIndexOf( "-" );
				if ( index === -1 ) {
					break;
				}
				// strip off the last part. e.g. en-US => en
				lang = lang.substr( 0, index );
				match = cultures[ lang ];
				if ( match ) {
					return match;
				}
			}
			while ( 1 );
		}

		// last resort: match first culture using that language
		for ( i = 0; i < l; i++ ) {
			lang = prioritized[ i ].lang;
			for ( var cultureKey in cultures ) {
				var culture = cultures[ cultureKey ];
				if ( culture.language === lang ) {
					return culture;
				}
			}
		}
	}
	else if ( typeof name === "object" ) {
		return name;
	}
	return match || null;
};

Globalize.format = function( value, format, cultureSelector ) {
	var culture = this.findClosestCulture( cultureSelector );
	if ( value instanceof Date ) {
		value = formatDate( value, format, culture );
	}
	else if ( typeof value === "number" ) {
		value = formatNumber( value, format, culture );
	}
	return value;
};

Globalize.localize = function( key, cultureSelector ) {
	return this.findClosestCulture( cultureSelector ).messages[ key ] ||
		this.cultures[ "default" ].messages[ key ];
};

Globalize.parseDate = function( value, formats, culture ) {
	culture = this.findClosestCulture( culture );

	var date, prop, patterns;
	if ( formats ) {
		if ( typeof formats === "string" ) {
			formats = [ formats ];
		}
		if ( formats.length ) {
			for ( var i = 0, l = formats.length; i < l; i++ ) {
				var format = formats[ i ];
				if ( format ) {
					date = parseExact( value, format, culture );
					if ( date ) {
						break;
					}
				}
			}
		}
	} else {
		patterns = culture.calendar.patterns;
		for ( prop in patterns ) {
			date = parseExact( value, patterns[prop], culture );
			if ( date ) {
				break;
			}
		}
	}

	return date || null;
};

Globalize.parseInt = function( value, radix, cultureSelector ) {
	return truncate( Globalize.parseFloat(value, radix, cultureSelector) );
};

Globalize.parseFloat = function( value, radix, cultureSelector ) {
	// radix argument is optional
	if ( typeof radix !== "number" ) {
		cultureSelector = radix;
		radix = 10;
	}

	var culture = this.findClosestCulture( cultureSelector );
	var ret = NaN,
		nf = culture.numberFormat;

	if ( value.indexOf(culture.numberFormat.currency.symbol) > -1 ) {
		// remove currency symbol
		value = value.replace( culture.numberFormat.currency.symbol, "" );
		// replace decimal seperator
		value = value.replace( culture.numberFormat.currency["."], culture.numberFormat["."] );
	}

	//Remove percentage character from number string before parsing
	if ( value.indexOf(culture.numberFormat.percent.symbol) > -1){
		value = value.replace( culture.numberFormat.percent.symbol, "" );
	}

	// remove spaces: leading, trailing and between - and number. Used for negative currency pt-BR
	value = value.replace( / /g, "" );

	// allow infinity or hexidecimal
	if ( regexInfinity.test(value) ) {
		ret = parseFloat( value );
	}
	else if ( !radix && regexHex.test(value) ) {
		ret = parseInt( value, 16 );
	}
	else {

		// determine sign and number
		var signInfo = parseNegativePattern( value, nf, nf.pattern[0] ),
			sign = signInfo[ 0 ],
			num = signInfo[ 1 ];

		// #44 - try parsing as "(n)"
		if ( sign === "" && nf.pattern[0] !== "(n)" ) {
			signInfo = parseNegativePattern( value, nf, "(n)" );
			sign = signInfo[ 0 ];
			num = signInfo[ 1 ];
		}

		// try parsing as "-n"
		if ( sign === "" && nf.pattern[0] !== "-n" ) {
			signInfo = parseNegativePattern( value, nf, "-n" );
			sign = signInfo[ 0 ];
			num = signInfo[ 1 ];
		}

		sign = sign || "+";

		// determine exponent and number
		var exponent,
			intAndFraction,
			exponentPos = num.indexOf( "e" );
		if ( exponentPos < 0 ) exponentPos = num.indexOf( "E" );
		if ( exponentPos < 0 ) {
			intAndFraction = num;
			exponent = null;
		}
		else {
			intAndFraction = num.substr( 0, exponentPos );
			exponent = num.substr( exponentPos + 1 );
		}
		// determine decimal position
		var integer,
			fraction,
			decSep = nf[ "." ],
			decimalPos = intAndFraction.indexOf( decSep );
		if ( decimalPos < 0 ) {
			integer = intAndFraction;
			fraction = null;
		}
		else {
			integer = intAndFraction.substr( 0, decimalPos );
			fraction = intAndFraction.substr( decimalPos + decSep.length );
		}
		// handle groups (e.g. 1,000,000)
		var groupSep = nf[ "," ];
		integer = integer.split( groupSep ).join( "" );
		var altGroupSep = groupSep.replace( /\u00A0/g, " " );
		if ( groupSep !== altGroupSep ) {
			integer = integer.split( altGroupSep ).join( "" );
		}
		// build a natively parsable number string
		var p = sign + integer;
		if ( fraction !== null ) {
			p += "." + fraction;
		}
		if ( exponent !== null ) {
			// exponent itself may have a number patternd
			var expSignInfo = parseNegativePattern( exponent, nf, "-n" );
			p += "e" + ( expSignInfo[0] || "+" ) + expSignInfo[ 1 ];
		}
		if ( regexParseFloat.test(p) ) {
			ret = parseFloat( p );
		}
	}
	return ret;
};

Globalize.culture = function( cultureSelector ) {
	// setter
	if ( typeof cultureSelector !== "undefined" ) {
		this.cultureSelector = cultureSelector;
	}
	// getter
	return this.findClosestCulture( cultureSelector ) || this.cultures[ "default" ];
};

}( this ));
;
/*
 * Globalize Culture fr-FR
 *
 * http://github.com/jquery/globalize
 *
 * Copyright Software Freedom Conservancy, Inc.
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * This file was generated by the Globalize Culture Generator
 * Translation: bugs found in this file need to be fixed in the generator
 */

(function( window, undefined ) {

var Globalize;

if ( typeof require !== "undefined" &&
	typeof exports !== "undefined" &&
	typeof module !== "undefined" ) {
	// Assume CommonJS
	Globalize = require( "globalize" );
} else {
	// Global variable
	Globalize = window.Globalize;
}

Globalize.addCultureInfo( "fr-FR", "default", {
	name: "fr-FR",
	englishName: "French (France)",
	nativeName: "français (France)",
	language: "fr",
	numberFormat: {
		",": " ",
		".": ",",
		"NaN": "Non Numérique",
		negativeInfinity: "-Infini",
		positiveInfinity: "+Infini",
		percent: {
			",": " ",
			".": ","
		},
		currency: {
			pattern: ["-n $","n $"],
			",": " ",
			".": ",",
			symbol: "€"
		}
	},
	calendars: {
		standard: {
			firstDay: 1,
			days: {
				names: ["dimanche","lundi","mardi","mercredi","jeudi","vendredi","samedi"],
				namesAbbr: ["dim.","lun.","mar.","mer.","jeu.","ven.","sam."],
				namesShort: ["di","lu","ma","me","je","ve","sa"]
			},
			months: {
				names: ["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre",""],
				namesAbbr: ["janv.","févr.","mars","avr.","mai","juin","juil.","août","sept.","oct.","nov.","déc.",""]
			},
			AM: null,
			PM: null,
			eras: [{"name":"ap. J.-C.","start":null,"offset":0}],
			patterns: {
				d: "dd/MM/yyyy",
				D: "dddd d MMMM yyyy",
				t: "HH:mm",
				T: "HH:mm:ss",
				f: "dddd d MMMM yyyy HH:mm",
				F: "dddd d MMMM yyyy HH:mm:ss",
				M: "d MMMM",
				Y: "MMMM yyyy",
				dt: "dd/MM/yyyy HH:mm"
			}
		}
	}
});

}( this ));
;
var foolproof=function(){};foolproof.is=function(a,h,b,f){if(f){var e=function(a){return a==null||a==undefined||a==""},c=e(a),d=e(b);if(c&&!d||d&&!c)return true}var g=function(a){return a-0==a&&a.length>0},j=function(b){var a=new RegExp(/(?=\d)^(?:(?!(?:10\D(?:0?[5-9]|1[0-4])\D(?:1582))|(?:0?9\D(?:0?[3-9]|1[0-3])\D(?:1752)))((?:0?[13578]|1[02])|(?:0?[469]|11)(?!\/31)(?!-31)(?!\.31)|(?:0?2(?=.?(?:(?:29.(?!000[04]|(?:(?:1[^0-6]|[2468][^048]|[3579][^26])00))(?:(?:(?:\d\d)(?:[02468][048]|[13579][26])(?!\x20BC))|(?:00(?:42|3[0369]|2[147]|1[258]|09)\x20BC))))))|(?:0?2(?=.(?:(?:\d\D)|(?:[01]\d)|(?:2[0-8])))))([-.\/])(0?[1-9]|[12]\d|3[01])\2(?!0000)((?=(?:00(?:4[0-5]|[0-3]?\d)\x20BC)|(?:\d{4}(?!\x20BC)))\d{4}(?:\x20BC)?)(?:$|(?=\x20\d)\x20))?((?:(?:0?[1-9]|1[012])(?::[0-5]\d){0,2}(?:\x20[aApP][mM]))|(?:[01]\d|2[0-3])(?::[0-5]\d){1,2})?$/);return a.test(b)},i=function(a){return a===true||a===false||a==="true"||a==="false"};if(j(a)){a=Date.parse(a);b=Date.parse(b)}else if(i(a)){if(a=="false")a=false;if(b=="false")b=false;a=!!a;b=!!b}else if(g(a)){a=parseFloat(a);b=parseFloat(b)}switch(h){case"EqualTo":if(a==b)return true;break;case"NotEqualTo":if(a!=b)return true;break;case"GreaterThan":if(a>b)return true;break;case"LessThan":if(a<b)return true;break;case"GreaterThanOrEqualTo":if(a>=b)return true;break;case"LessThanOrEqualTo":if(a<=b)return true;break;case"RegExMatch":return(new RegExp(b)).test(a);break;case"NotRegExMatch":return!(new RegExp(b)).test(a)}return false};foolproof.getId=function(a,b){var c=a.id.lastIndexOf("_")+1;return a.id.substr(0,c)+b.replace(/\./g,"_")};foolproof.getName=function(a,b){var c=a.name.lastIndexOf(".")+1;return a.name.substr(0,c)+b};(function(){jQuery.validator.addMethod("is",function(g,f,a){var b=foolproof.getId(f,a.dependentproperty),e=a.operator,d=a.passonnull,c=document.getElementById(b).value;return foolproof.is(g,e,c,d)?true:false});jQuery.validator.addMethod("requiredif",function(e,j,c){var h=foolproof.getName(j,c.dependentproperty),g=c.dependentvalue,i=c.operator,f=c.pattern,a=document.getElementsByName(h),b=null;if(a.length>1){for(var d=0;d!=a.length;d++)if(a[d].checked){b=a[d].value;break}if(b==null)b=false}else b=a[0].value;if(foolproof.is(b,i,g))if(f==null){if(e!=null&&e.toString().replace(/^\s\s*/,"").replace(/\s\s*$/,"")!="")return true}else return(new RegExp(f)).test(e);else return true;return false});jQuery.validator.addMethod("requiredifempty",function(b,d,e){var c=foolproof.getId(d,e.dependentproperty),a=document.getElementById(c).value;if(a==null||a.toString().replace(/^\s\s*/,"").replace(/\s\s*$/,"")==""){if(b!=null&&b.toString().replace(/^\s\s*/,"").replace(/\s\s*$/,"")!="")return true}else return true;return false});jQuery.validator.addMethod("requiredifnotempty",function(b,d,e){var c=foolproof.getId(d,e.dependentproperty),a=document.getElementById(c).value;if(a!=null&&a.toString().replace(/^\s\s*/,"").replace(/\s\s*$/,"")!=""){if(b!=null&&b.toString().replace(/^\s\s*/,"").replace(/\s\s*$/,"")!="")return true}else return true;return false});var a=function(a,b,c){a.rules[b]=c;if(a.message)a.messages[b]=a.message},b=$.validator.unobtrusive;b.adapters.add("requiredif",["dependentproperty","dependentvalue","operator","pattern"],function(b){var c={dependentproperty:b.params.dependentproperty,dependentvalue:b.params.dependentvalue,operator:b.params.operator,pattern:b.params.pattern};a(b,"requiredif",c)});b.adapters.add("is",["dependentproperty","operator","passonnull"],function(b){a(b,"is",{dependentproperty:b.params.dependentproperty,operator:b.params.operator,passonnull:b.params.passonnull})});b.adapters.add("requiredifempty",["dependentproperty"],function(b){a(b,"requiredifempty",{dependentproperty:b.params.dependentproperty})});b.adapters.add("requiredifnotempty",["dependentproperty"],function(b){a(b,"requiredifnotempty",{dependentproperty:b.params.dependentproperty})})})();;
/*
CSS Browser Selector v0.4.0 (Nov 02, 2010)
Rafael Lima (http://rafael.adm.br)
http://rafael.adm.br/css_browser_selector
License: http://creativecommons.org/licenses/by/2.5/
Contributors: http://rafael.adm.br/css_browser_selector#contributors
*/
function css_browser_selector(u) { var ua = u.toLowerCase(), is = function (t) { return ua.indexOf(t) > -1 }, g = 'gecko', w = 'webkit', s = 'safari', o = 'opera', m = 'mobile', h = document.documentElement, b = [(!(/opera|webtv/i.test(ua)) && /msie\s(\d)/.test(ua)) ? ('ie ie' + RegExp.$1) : is('firefox/2') ? g + ' ff2' : is('firefox/3.5') ? g + ' ff3 ff3_5' : is('firefox/3.6') ? g + ' ff3 ff3_6' : is('firefox/3') ? g + ' ff3' : is('gecko/') ? g : is('opera') ? o + (/version\/(\d+)/.test(ua) ? ' ' + o + RegExp.$1 : (/opera(\s|\/)(\d+)/.test(ua) ? ' ' + o + RegExp.$2 : '')) : is('konqueror') ? 'konqueror' : is('blackberry') ? m + ' blackberry' : is('android') ? m + ' android' : is('chrome') ? w + ' chrome' : is('iron') ? w + ' iron' : is('applewebkit/') ? w + ' ' + s + (/version\/(\d+)/.test(ua) ? ' ' + s + RegExp.$1 : '') : is('mozilla/') ? g : '', is('j2me') ? m + ' j2me' : is('iphone') ? m + ' iphone' : is('ipod') ? m + ' ipod' : is('ipad') ? m + ' ipad' : is('mac') ? 'mac' : is('darwin') ? 'mac' : is('webtv') ? 'webtv' : is('win') ? 'win' + (is('windows nt 6.0') ? ' vista' : '') : is('freebsd') ? 'freebsd' : (is('x11') || is('linux')) ? 'linux' : '', 'js']; c = b.join(' '); h.className += ' ' + c; return c; }; css_browser_selector(navigator.userAgent);
;
/*
 * Flip! jQuery Plugin (http://lab.smashup.it/flip/)
 * @author Luca Manno (luca@smashup.it) [http://i.smashup.it]
 *              [Original idea by Nicola Rizzo (thanks!)]
 *
 * @version 0.9.9 [Nov. 2009]
 *
 * @changelog
 * v 0.9.9      ->      Fix transparency over non-colored background. Added dontChangeColor option.
 *                      Added $clone and $this parameters to on.. callback functions.
 *                      Force hexadecimal color values. Made safe for noConflict use.
 *                      Some refactoring. [Henrik Hjelte, Jul. 10, 2009]
 * 						Added revert options, fixes and improvements on color management.
 * 						Released in Nov 2009
 * v 0.5        ->      Added patch to make it work with Opera (thanks to Peter Siewert), Added callbacks [Feb. 1, 2008]
 * v 0.4.1      ->      Fixed a regression in Chrome and Safari caused by getTransparent [Oct. 1, 2008]
 * v 0.4        ->      Fixed some bugs with transparent color. Now Flip! works on non-white backgrounds | Update: jquery.color.js plugin or jqueryUI still needed :( [Sept. 29, 2008]
 * v 0.3        ->      Now is possibile to define the content after the animation.
 *                              (jQuery object or text/html is allowed) [Sept. 25, 2008]
 * v 0.2        ->      Fixed chainability and buggy innertext rendering (xNephilimx thanks!)
 * v 0.1        ->      Starting release [Sept. 11, 2008]
 *
 */
(function($) {

function int_prop(fx){
    fx.elem.style[ fx.prop ] = parseInt(fx.now,10) + fx.unit;
}

var throwError=function(message) {
    throw({name:"jquery.flip.js plugin error",message:message});
};

var isIE6orOlder=function() {
    // User agent sniffing is clearly out of fashion and $.browser will be be deprectad.
    // Now, I can't think of a way to feature detect that IE6 doesn't show transparent
    // borders in the correct way.
    // Until then, this function will do, and be partly political correct, allowing
    // 0.01 percent of the internet users to tweak with their UserAgent string.
    //
    // Not leadingWhiteSpace is to separate IE family from, well who knows?
    // Maybe some version of Opera?
    // The second guess behind this is that IE7+  will keep supporting maxHeight in the future.
	
	// First guess changed to dean edwards ie sniffing http://dean.edwards.name/weblog/2007/03/sniff/
    return (/*@cc_on!@*/false && (typeof document.body.style.maxHeight === "undefined"));
};


// Some named colors to work with
// From Interface by Stefan Petre
// http://interface.eyecon.ro/

var colors = {
	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],
	transparent: [255,255,255]
};

var acceptHexColor=function(color) {
	if(color && color.indexOf("#")==-1 && color.indexOf("(")==-1){
		return "rgb("+colors[color].toString()+")";
	} else {
		return color;
	}
};

$.extend( $.fx.step, {
    borderTopWidth : int_prop,
    borderBottomWidth : int_prop,
    borderLeftWidth: int_prop,
    borderRightWidth: int_prop
});

$.fn.revertFlip = function(){
	return this.each( function(){
		var $this = $(this);
		$this.flip($this.data('flipRevertedSettings'));		
	});
};

$.fn.flip = function(settings){
    return this.each( function() {
        var $this=$(this), flipObj, $clone, dirOption, dirOptions, newContent, ie6=isIE6orOlder();

        if($this.data('flipLock')){
            return false;
        }
		
		var revertedSettings = {
			direction: (function(direction){
				switch(direction)
				{
				case "tb":
				  return "bt";
				case "bt":
				  return "tb";
				case "lr":
				  return "rl";
				case "rl":
				  return "lr";		  
				default:
				  return "bt";
				}
			})(settings.direction),
			bgColor: acceptHexColor(settings.color) || "#999",
			color: acceptHexColor(settings.bgColor) || $this.css("background-color"),
			content: $this.html(),
			speed: settings.speed || 500,
            onBefore: settings.onBefore || function(){},
            onEnd: settings.onEnd || function(){},
            onAnimation: settings.onAnimation || function(){}
		};
		
		$this
			.data('flipRevertedSettings',revertedSettings)
			.data('flipLock',1)
			.data('flipSettings',revertedSettings);

        flipObj = {
            width: $this.width(),
            height: $this.height(),
            bgColor: acceptHexColor(settings.bgColor) || $this.css("background-color"),
            fontSize: $this.css("font-size") || "12px",
            direction: settings.direction || "tb",
            toColor: acceptHexColor(settings.color) || "#999",
            speed: settings.speed || 500,
            top: $this.offset().top,
            left: $this.offset().left,
            target: settings.content || null,
            transparent: "transparent",
            dontChangeColor: settings.dontChangeColor || false,
            onBefore: settings.onBefore || function(){},
            onEnd: settings.onEnd || function(){},
            onAnimation: settings.onAnimation || function(){}
        };

        // This is the first part of a trick to support
        // transparent borders using chroma filter for IE6
        // The color below is arbitrary, lets just hope it is not used in the animation
        ie6 && (flipObj.transparent="#123456");

        $clone= $this.css("visibility","hidden")
            .clone(true)
			.data('flipLock',1)
            .appendTo("body")
            .html("")
            .css({visibility:"visible",position:"absolute",left:flipObj.left,top:flipObj.top,margin:0,zIndex:9999,"-webkit-box-shadow":"0px 0px 0px #000","-moz-box-shadow":"0px 0px 0px #000"});

        var defaultStart=function() {
            return {
                backgroundColor: flipObj.transparent,
                fontSize:0,
                lineHeight:0,
                borderTopWidth:0,
                borderLeftWidth:0,
                borderRightWidth:0,
                borderBottomWidth:0,
                borderTopColor:flipObj.transparent,
                borderBottomColor:flipObj.transparent,
                borderLeftColor:flipObj.transparent,
                borderRightColor:flipObj.transparent,
				background: "none",
                borderStyle:'solid',
                height:0,
                width:0
            };
        };
        var defaultHorizontal=function() {
            var waist=(flipObj.height/100)*25;
            var start=defaultStart();
            start.width=flipObj.width;
            return {
                "start": start,
                "first": {
                    borderTopWidth: 0,
                    borderLeftWidth: waist,
                    borderRightWidth: waist,
                    borderBottomWidth: 0,
                    borderTopColor: '#999',
                    borderBottomColor: '#999',
                    top: (flipObj.top+(flipObj.height/2)),
                    left: (flipObj.left-waist)},
                "second": {
                    borderBottomWidth: 0,
                    borderTopWidth: 0,
                    borderLeftWidth: 0,
                    borderRightWidth: 0,
                    borderTopColor: flipObj.transparent,
                    borderBottomColor: flipObj.transparent,
                    top: flipObj.top,
                    left: flipObj.left}
            };
        };
        var defaultVertical=function() {
            var waist=(flipObj.height/100)*25;
            var start=defaultStart();
            start.height=flipObj.height;
            return {
                "start": start,
                "first": {
                    borderTopWidth: waist,
                    borderLeftWidth: 0,
                    borderRightWidth: 0,
                    borderBottomWidth: waist,
                    borderLeftColor: '#999',
                    borderRightColor: '#999',
                    top: flipObj.top-waist,
                    left: flipObj.left+(flipObj.width/2)},
                "second": {
                    borderTopWidth: 0,
                    borderLeftWidth: 0,
                    borderRightWidth: 0,
                    borderBottomWidth: 0,
                    borderLeftColor: flipObj.transparent,
                    borderRightColor: flipObj.transparent,
                    top: flipObj.top,
                    left: flipObj.left}
            };
        };

        dirOptions = {
            "tb": function () {
                var d=defaultHorizontal();
                d.start.borderTopWidth=flipObj.height;
                d.start.borderTopColor=flipObj.bgColor;
                d.second.borderBottomWidth= flipObj.height;
                d.second.borderBottomColor= flipObj.toColor;
                return d;
            },
            "bt": function () {
                var d=defaultHorizontal();
                d.start.borderBottomWidth=flipObj.height;
                d.start.borderBottomColor= flipObj.bgColor;
                d.second.borderTopWidth= flipObj.height;
                d.second.borderTopColor= flipObj.toColor;
                return d;
            },
            "lr": function () {
                var d=defaultVertical();
                d.start.borderLeftWidth=flipObj.width;
                d.start.borderLeftColor=flipObj.bgColor;
                d.second.borderRightWidth= flipObj.width;
                d.second.borderRightColor= flipObj.toColor;
                return d;
            },
            "rl": function () {
                var d=defaultVertical();
                d.start.borderRightWidth=flipObj.width;
                d.start.borderRightColor=flipObj.bgColor;
                d.second.borderLeftWidth= flipObj.width;
                d.second.borderLeftColor= flipObj.toColor;
                return d;
            }
        };

        dirOption=dirOptions[flipObj.direction]();

        // Second part of IE6 transparency trick.
        ie6 && (dirOption.start.filter="chroma(color="+flipObj.transparent+")");

        newContent = function(){
            var target = flipObj.target;
            return target && target.jquery ? target.html() : target;
        };

        $clone.queue(function(){
            flipObj.onBefore($clone,$this);
            $clone.html('').css(dirOption.start);
            $clone.dequeue();
        });

        $clone.animate(dirOption.first,flipObj.speed);

        $clone.queue(function(){
            flipObj.onAnimation($clone,$this);
            $clone.dequeue();
        });
        $clone.animate(dirOption.second,flipObj.speed);

        $clone.queue(function(){
            if (!flipObj.dontChangeColor) {
                $this.css({backgroundColor: flipObj.toColor});
            }
            $this.css({visibility: "visible"});

            var nC = newContent();
            if(nC){$this.html(nC);}
            $clone.remove();
            flipObj.onEnd($clone,$this);
            $this.removeData('flipLock');
            $clone.dequeue();
        });
    });
};
})(jQuery);
;
/**
*
* @license Guriddo jqGrid JS - v5.5.2 - 2021-01-26
* Copyright(c) 2008, Tony Tomov, tony@trirand.com
* 
* License: http://guriddo.net/?page_id=103334
*/

!function (e) { "use strict"; "function" == typeof define && define.amd ? define(["jquery"], e) : e(jQuery) }(function ($) { "use strict"; $.jgrid = $.jgrid || {}, $.jgrid.hasOwnProperty("defaults") || ($.jgrid.defaults = {}), $.extend($.jgrid, { version: "5.5.2", htmlDecode: function (e) { return e && ("&nbsp;" === e || "&#160;" === e || 1 === e.length && 160 === e.charCodeAt(0)) ? "" : e && String(e).replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"').replace(/&amp;/g, "&") }, htmlEncode: function (e) { return e && String(e).replace(/&/g, "&amp;").replace(/\"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;") }, template: function (e) { var o, a = $.makeArray(arguments).slice(1), n = a.length; return null == e && (e = ""), e.replace(/\{([\w\-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g, function (e, t) { if (!isNaN(parseInt(t, 10))) return a[parseInt(t, 10)]; for (o = 0; o < n; o++)if ($.isArray(a[o])) for (var r = a[o], i = r.length; i--;)if (t === r[i].nm) return r[i].v }) }, msie: function () { return 0 < $.jgrid.msiever() }, msiever: function () { var e = 0, t = window.navigator.userAgent, r = t.indexOf("MSIE"); return 0 < r ? e = parseInt(t.substring(r + 5, t.indexOf(".", r))) : navigator.userAgent.match(/Trident\/7\./) && (e = 11), e }, getCellIndex: function (e) { e = $(e); return e.is("tr") ? -1 : (e = (e.is("td") || e.is("th") ? e : e.closest("td,th"))[0], $.jgrid.msie() ? $.inArray(e, e.parentNode.cells) : e.cellIndex) }, stripHtml: function (e) { return (e = String(e)) ? (e = e.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi, "")) && "&nbsp;" !== e && "&#160;" !== e ? e.replace(/\"/g, "'") : "" : e }, stripPref: function (e, t) { var r = $.type(e); return "string" !== r && "number" !== r || (t = "" !== (e = String(e)) ? String(t).replace(String(e), "") : t), t }, useJSON: !0, parse: function (jsonString) { var js = jsonString; return "while(1);" === js.substr(0, 9) && (js = js.substr(9)), "/*" === js.substr(0, 2) && (js = js.substr(2, js.length - 4)), js = js || "{}", !0 === $.jgrid.useJSON && "object" == typeof JSON && "function" == typeof JSON.parse ? JSON.parse(js) : eval("(" + js + ")") }, parseDate: function (e, t, r, i) { function o(e, t) { for (e = String(e), t = parseInt(t, 10) || 2; e.length < t;)e = "0" + e; return e } function a(e, t) { return 0 === e ? 12 === t && (t = 0) : 12 !== t && (t += 12), t } var n, l, s, d = new RegExp("^/Date\\((([-+])?[0-9]+)(([-+])([0-9]{2})([0-9]{2}))?\\)/$"), p = "string" == typeof t ? t.match(d) : null, c = { m: 1, d: 1, y: 1970, h: 0, i: 0, s: 0, u: 0 }, u = 0, h = 0; if (void 0 === i && (i = $.jgrid.getRegional(this, "formatter.date")), void 0 === i && (i = {}), void 0 === i.parseRe && (i.parseRe = /[#%\\\/:_;.,\t\s-]/), void 0 === i.AmPm && (i.AmPm = ["am", "pm", "AM", "PM"]), i.masks && i.masks.hasOwnProperty(e) && (e = i.masks[e]), t && null != t) if (isNaN(+t) || "u" !== String(e).toLowerCase()) if (t.constructor === Date) u = t, i.validate = !1; else if (null !== p) u = new Date(parseInt(p[1], 10)), p[3] && (h = 60 * Number(p[5]) + Number(p[6]), h *= "-" === p[4] ? 1 : -1, h -= u.getTimezoneOffset(), u.setTime(Number(Number(u) + 60 * h * 1e3))), i.validate = !1; else { for ("ISO8601Long" === i.srcformat && "Z" === t.charAt(t.length - 1) && (h -= (new Date).getTimezoneOffset()), t = String(t).replace(/\T/g, "#").replace(/\t/, "%").split(i.parseRe), l = 0, s = (e = e.replace(/\T/g, "#").replace(/\t/, "%").split(i.parseRe)).length; l < s; l++) { switch (e[l]) { case "M": -1 !== (n = $.inArray(t[l], i.monthNames)) && n < 12 && (t[l] = n + 1, c.m = t[l]); break; case "F": -1 !== (n = $.inArray(t[l], i.monthNames, 12)) && 11 < n && (t[l] = n + 1 - 12, c.m = t[l]); break; case "n": e[l] = "m"; break; case "j": e[l] = "d"; break; case "a": -1 !== (n = $.inArray(t[l], i.AmPm)) && n < 2 && t[l] === i.AmPm[n] && (t[l] = n, c.h = a(t[l], c.h)); break; case "A": -1 !== (n = $.inArray(t[l], i.AmPm)) && 1 < n && t[l] === i.AmPm[n] && (t[l] = n - 2, c.h = a(t[l], c.h)); break; case "g": c.h = parseInt(t[l], 10) }void 0 !== t[l] && (c[e[l].toLowerCase()] = parseInt(t[l], 10)) } if (c.f && (c.m = c.f), 0 === c.m && 0 === c.y && 0 === c.d) return "&#160;"; c.m = parseInt(c.m, 10) - 1; var g = c.y; 70 <= g && g <= 99 ? c.y = 1900 + c.y : 0 <= g && g <= 69 && (c.y = 2e3 + c.y), u = new Date(c.y, c.m, c.d, c.h, c.i, c.s, c.u), 0 !== h && u.setTime(Number(Number(u) + 60 * h * 1e3)) } else u = new Date(1e3 * parseFloat(t)), i.validate = !1; else u = new Date(c.y, c.m, c.d, c.h, c.i, c.s, c.u); if (i && !0 === i.validate) { const _ = new Date(c.y, +c.m, c.d, c.h, c.i); return Boolean(+_) && _.getDate() === c.d && _.getHours() === c.h && _.getMinutes() === c.i } if (i.userLocalTime && 0 === h && 0 !== (h -= (new Date).getTimezoneOffset()) && u.setTime(Number(Number(u) + 60 * h * 1e3)), void 0 === r) return u; r = i.masks && i.masks.hasOwnProperty(r) ? i.masks[r] : r || "Y-m-d"; var f = u.getHours(), m = u.getMinutes(), v = u.getDate(), b = u.getMonth() + 1, j = u.getTimezoneOffset(), y = u.getSeconds(), w = u.getMilliseconds(), d = u.getDay(), p = u.getFullYear(), g = (d + 6) % 7 + 1, h = (new Date(p, b - 1, v) - new Date(p, 0, 1)) / 864e5, x = { d: o(v), D: i.dayNames[d], j: v, l: i.dayNames[d + 7], N: g, S: i.S(v), w: d, z: h, W: g < 5 ? Math.floor((h + g - 1) / 7) + 1 : Math.floor((h + g - 1) / 7) || ((new Date(p - 1, 0, 1).getDay() + 6) % 7 < 4 ? 53 : 52), F: i.monthNames[b - 1 + 12], m: o(b), M: i.monthNames[b - 1], n: b, t: "?", L: "?", o: "?", Y: p, y: String(p).substring(2), a: f < 12 ? i.AmPm[0] : i.AmPm[1], A: f < 12 ? i.AmPm[2] : i.AmPm[3], B: "?", g: f % 12 || 12, G: f, h: o(f % 12 || 12), H: o(f), i: o(m), s: o(y), u: w, e: "?", I: "?", O: (0 < j ? "-" : "+") + o(100 * Math.floor(Math.abs(j) / 60) + Math.abs(j) % 60, 4), P: "?", T: (String(u).match(/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g) || [""]).pop().replace(/[^-+\dA-Z]/g, ""), Z: "?", c: "?", r: "?", U: Math.floor(u / 1e3) }; return r.replace(/\\.|[dDjlNSwzWFmMntLoYyaABgGhHisueIOPTZcrU]/g, function (e) { return x.hasOwnProperty(e) ? x[e] : e.substring(1) }) }, jqID: function (e) { return String(e).replace(/[!"#$%&'()*+,.\/:; <=>?@\[\\\]\^`{|}~]/g, "\\$&") }, guid: 1, uidPref: "jqg", randId: function (e) { return (e || $.jgrid.uidPref) + $.jgrid.guid++ }, getAccessor: function (e, t) { var r, i, o = []; if ("function" == typeof t) return t(e); if (void 0 === (r = e[t])) try { if ("string" == typeof t && (o = t.split(".")), i = o.length) for (r = e; r && i--;)r = r[o.shift()] } catch (e) { } return r }, getXmlData: function (e, t, r) { var i = "string" == typeof t ? t.match(/^(.*)\[(\w+)\]$/) : null; return "function" == typeof t ? t(e) : i && i[2] ? (i[1] ? $(i[1], e) : $(e)).attr(i[2]) : (e = $(t, e), r ? e : 0 < e.length ? $(e).text() : void 0) }, cellWidth: function () { var e = $("<div class='ui-jqgrid' style='left:10000px'><table class='ui-jqgrid-btable ui-common-table' style='width:5px;'><tr class='jqgrow'><td style='width:5px;display:block;'></td></tr></table></div>"), t = e.appendTo("body").find("td").width(); return e.remove(), .1 < Math.abs(t - 5) }, isLocalStorage: function () { try { return "localStorage" in window && null !== window.localStorage } catch (e) { return !1 } }, getRegional: function (e, t, r) { var i; return void 0 !== r ? r : (e.p && e.p.regional && $.jgrid.regional && (i = $.jgrid.getAccessor($.jgrid.regional[e.p.regional] || {}, t)), void 0 === i && (i = $.jgrid.getAccessor($.jgrid, t)), i) }, isMobile: function () { try { return /Android|webOS|iPhone|iPad|iPod|pocket|psp|kindle|avantgo|blazer|midori|Tablet|Palm|maemo|plucker|phone|BlackBerry|symbian|IEMobile|mobile|ZuneWP7|Windows Phone|Opera Mini/i.test(navigator.userAgent) ? !0 : !1 } catch (e) { return !1 } }, cell_width: !0, scrollbarWidth: function () { var e = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>'); $("body").append(e); var t = $("div", e).innerWidth(); e.css("overflow-y", "scroll"); var r = $("div", e).innerWidth(); return $(e).remove(), t - r < 0 ? 18 : t - r }, ajaxOptions: {}, from: function (source) { var $t = this, QueryObject = function (d, q) { "string" == typeof d && (d = $.data(d)); var self = this, _data = d, _usecase = !0, _trim = !1, _query = q, _stripNum = /[\$,%]/g, _lastCommand = null, _lastField = null, _orDepth = 0, _negate = !1, _queuedOperator = "", _sorting = [], _useProperties = !0; if ("object" != typeof d || !d.push) throw "data provides is not an array"; return 0 < d.length && (_useProperties = "object" == typeof d[0]), this._hasData = function () { return null !== _data && 0 !== _data.length }, this._getStr = function (e) { var t = []; return _trim && t.push("jQuery.trim("), t.push("String(" + e + ")"), _trim && t.push(")"), _usecase || t.push(".toLowerCase()"), t.join("") }, this._strComp = function (e) { return "string" == typeof e ? ".toString()" : "" }, this._group = function (e, t) { return { field: e.toString(), unique: t, items: [] } }, this._toStr = function (e) { return _trim && (e = $.trim(e)), e = e.toString().replace(/\\/g, "\\\\").replace(/\"/g, '\\"'), _usecase ? e : e.toLowerCase() }, this._funcLoop = function (r) { var i = []; return $.each(_data, function (e, t) { i.push(r(t)) }), i }, this._append = function (e) { var t; for (null === _query ? _query = "" : _query += "" === _queuedOperator ? " && " : _queuedOperator, t = 0; t < _orDepth; t++)_query += "("; _negate && (_query += "!"), _query += "(" + e + ")", _negate = !1, _queuedOperator = "", _orDepth = 0 }, this._setCommand = function (e, t) { _lastCommand = e, _lastField = t }, this._resetNegate = function () { _negate = !1 }, this._repeatCommand = function (e, t) { return null === _lastCommand ? self : null !== e && null !== t ? _lastCommand(e, t) : null !== _lastField && _useProperties ? _lastCommand(_lastField, e) : _lastCommand(e) }, this._equals = function (e, t) { return 0 === self._compare(e, t, 1) }, this._compare = function (e, t, r) { var i = Object.prototype.toString; return void 0 === r && (r = 1), void 0 === e && (e = null), void 0 === t && (t = null), null === e && null === t ? 0 : null === e && null !== t ? 1 : null !== e && null === t ? -1 : ("[object Date]" === i.call(e) && "[object Date]" === i.call(t) || _usecase || "number" == typeof e || "number" == typeof t || (e = String(e), t = String(t)), e < t ? -r : t < e ? r : 0) }, this._performSort = function () { 0 !== _sorting.length && (_data = self._doSort(_data, 0)) }, this._doSort = function (e, t) { var r = _sorting[t].by, i = _sorting[t].dir, o = _sorting[t].type, a = _sorting[t].datefmt, n = _sorting[t].sfunc; if (t === _sorting.length - 1) return self._getOrder(e, r, i, o, a, n); t++; for (var l, s, d = self._getGroup(e, r, i, o, a), p = [], c = 0; c < d.length; c++)for (s = self._doSort(d[c].items, t), l = 0; l < s.length; l++)p.push(s[l]); return p }, this._getOrder = function (e, r, t, i, o, a) { var n, l, s, d, p = [], c = [], u = "a" === t ? 1 : -1; void 0 === i && (i = "text"), d = "float" === i || "number" === i || "currency" === i || "numeric" === i ? function (e) { e = parseFloat(String(e).replace(_stripNum, "")); return isNaN(e) ? Number.NEGATIVE_INFINITY : e } : "int" === i || "integer" === i ? function (e) { return e ? parseFloat(String(e).replace(_stripNum, "")) : Number.NEGATIVE_INFINITY } : "date" === i || "datetime" === i ? function (e) { return $.jgrid.parseDate.call($t, o, e).getTime() } : $.isFunction(i) ? i : function (e) { return e = e ? $.trim(String(e)) : "", _usecase ? e : e.toLowerCase() }, $.each(e, function (e, t) { void 0 === (l = "" !== r ? $.jgrid.getAccessor(t, r) : t) && (l = ""), l = d(l, t), c.push({ vSort: l, index: e }) }), $.isFunction(a) ? c.sort(function (e, t) { return a.call(this, e.vSort, t.vSort, u, e, t) }) : c.sort(function (e, t) { return self._compare(e.vSort, t.vSort, u) }), s = 0; for (var h = e.length; s < h;)n = c[s].index, p.push(e[n]), s++; return p }, this._getGroup = function (e, r, t, i, o) { var a, n = [], l = null, s = null; return $.each(self._getOrder(e, r, t, i, o), function (e, t) { null == (a = $.jgrid.getAccessor(t, r)) && (a = ""), self._equals(s, a) || (s = a, null !== l && n.push(l), l = self._group(r, a)), l.items.push(t) }), null !== l && n.push(l), n }, this.ignoreCase = function () { return _usecase = !1, self }, this.useCase = function () { return _usecase = !0, self }, this.trim = function () { return _trim = !0, self }, this.noTrim = function () { return _trim = !1, self }, this.execute = function () { var match = _query, results = []; return null === match ? self : ($.each(_data, function () { eval(match) && results.push(this) }), _data = results, self) }, this.data = function () { return _data }, this.select = function (r) { if (self._performSort(), !self._hasData()) return []; if (self.execute(), $.isFunction(r)) { var i = []; return $.each(_data, function (e, t) { i.push(r(t)) }), i } return _data }, this.hasMatch = function () { return !!self._hasData() && (self.execute(), 0 < _data.length) }, this.andNot = function (e, t, r) { return _negate = !_negate, self.and(e, t, r) }, this.orNot = function (e, t, r) { return _negate = !_negate, self.or(e, t, r) }, this.not = function (e, t, r) { return self.andNot(e, t, r) }, this.and = function (e, t, r) { return _queuedOperator = " && ", void 0 === e ? self : self._repeatCommand(e, t, r) }, this.or = function (e, t, r) { return _queuedOperator = " || ", void 0 === e ? self : self._repeatCommand(e, t, r) }, this.orBegin = function () { return _orDepth++, self }, this.orEnd = function () { return null !== _query && (_query += ")"), self }, this.isNot = function (e) { return _negate = !_negate, self.is(e) }, this.is = function (e) { return self._append("this." + e), self._resetNegate(), self }, this._compareValues = function (e, t, r, i, o) { var a = _useProperties ? "jQuery.jgrid.getAccessor(this,'" + t + "')" : "this"; void 0 === r && (r = null); var n = r, l = void 0 === o.stype ? "text" : o.stype; if (null !== r) switch (l) { case "int": case "integer": a = "parseInt(" + a + ",10)", n = "parseInt(" + (n = isNaN(Number(n)) || "" === n ? Number.NEGATIVE_INFINITY : n) + ",10)"; break; case "float": case "number": case "numeric": n = String(n).replace(_stripNum, ""), a = "parseFloat(" + a + ")", n = "parseFloat(" + (n = isNaN(Number(n)) || "" === n ? Number.NEGATIVE_INFINITY : Number(n)) + ")"; break; case "date": case "datetime": n = String($.jgrid.parseDate.call($t, o.srcfmt || "Y-m-d", n).getTime()), a = 'jQuery.jgrid.parseDate.call(jQuery("#' + $.jgrid.jqID($t.p.id) + '")[0],"' + o.srcfmt + '",' + a + ").getTime()"; break; default: a = self._getStr(a), n = self._getStr('"' + self._toStr(n) + '"') }return self._append(a + " " + i + " " + n), self._setCommand(e, t), self._resetNegate(), self }, this.equals = function (e, t, r) { return self._compareValues(self.equals, e, t, "==", r) }, this.notEquals = function (e, t, r) { return self._compareValues(self.equals, e, t, "!==", r) }, this.isNull = function (e, t, r) { return self._compareValues(self.equals, e, null, "===", r) }, this.greater = function (e, t, r) { return self._compareValues(self.greater, e, t, ">", r) }, this.less = function (e, t, r) { return self._compareValues(self.less, e, t, "<", r) }, this.greaterOrEquals = function (e, t, r) { return self._compareValues(self.greaterOrEquals, e, t, ">=", r) }, this.lessOrEquals = function (e, t, r) { return self._compareValues(self.lessOrEquals, e, t, "<=", r) }, this.startsWith = function (e, t) { var r = null == t ? e : t, r = (_trim ? $.trim(r.toString()) : r.toString()).length; return _useProperties ? self._append(self._getStr("jQuery.jgrid.getAccessor(this,'" + e + "')") + ".substr(0," + r + ") == " + self._getStr('"' + self._toStr(t) + '"')) : (null != t && (r = (_trim ? $.trim(t.toString()) : t.toString()).length), self._append(self._getStr("this") + ".substr(0," + r + ") == " + self._getStr('"' + self._toStr(e) + '"'))), self._setCommand(self.startsWith, e), self._resetNegate(), self }, this.endsWith = function (e, t) { var r = null == t ? e : t, r = (_trim ? $.trim(r.toString()) : r.toString()).length; return _useProperties ? self._append(self._getStr("jQuery.jgrid.getAccessor(this,'" + e + "')") + ".substr(" + self._getStr("jQuery.jgrid.getAccessor(this,'" + e + "')") + ".length-" + r + "," + r + ') == "' + self._toStr(t) + '"') : self._append(self._getStr("this") + ".substr(" + self._getStr("this") + '.length-"' + self._toStr(e) + '".length,"' + self._toStr(e) + '".length) == "' + self._toStr(e) + '"'), self._setCommand(self.endsWith, e), self._resetNegate(), self }, this.contains = function (e, t) { return _useProperties ? self._append(self._getStr("jQuery.jgrid.getAccessor(this,'" + e + "')") + '.indexOf("' + self._toStr(t) + '",0) > -1') : self._append(self._getStr("this") + '.indexOf("' + self._toStr(e) + '",0) > -1'), self._setCommand(self.contains, e), self._resetNegate(), self }, this.user = function (e, t, r) { return self._append("$t.p.customFilterDef." + e + '.action.call($t ,{rowItem:this, searchName:"' + t + '",searchValue:"' + r + '"})'), self._setCommand(self.user, t), self._resetNegate(), self }, this.inData = function (e, t, r) { t = void 0 === t ? "" : self._getStr('"' + self._toStr(t) + '"'); return _useProperties ? self._append(t + ".split(',').indexOf( jQuery.jgrid.getAccessor(this,'" + e + "') ) > -1") : self._append(t + ".split(',').indexOf(this." + e + ") > -1"), self._setCommand(self.inData, e), self._resetNegate(), self }, this.groupBy = function (e, t, r, i) { return self._hasData() ? self._getGroup(_data, e, t, r, i) : null }, this.orderBy = function (e, t, r, i, o) { return null == r && (r = "text"), null == i && (i = "Y-m-d"), null == o && (o = !1), "desc" !== (t = null == t ? "a" : $.trim(t.toString().toLowerCase())) && "descending" !== t || (t = "d"), "asc" !== t && "ascending" !== t || (t = "a"), _sorting.push({ by: e, dir: t, type: r, datefmt: i, sfunc: o }), self }, self }; return new QueryObject(source, null) }, getMethod: function (e) { return this.getAccessor($.fn.jqGrid, e) }, extend: function (e) { $.extend($.fn.jqGrid, e), this.no_legacy_api || $.fn.extend(e) }, clearBeforeUnload: function (e) { var t, r = $("#" + $.jgrid.jqID(e))[0]; if (r.grid) { t = r.grid, $.isFunction(t.emptyRows) && t.emptyRows.call(r, !0, !0), $(document).off("mouseup.jqGrid" + r.p.id), $(t.hDiv).off("mousemove"), $(r).off(); for (var i = t.headers.length, o = ["formatCol", "sortData", "updatepager", "refreshIndex", "setHeadCheckBox", "constructTr", "formatter", "addXmlData", "addJSONData", "grid", "p", "addLocalData"], a = 0; a < i; a++)t.headers[a].el = null; for (a in t) t.hasOwnProperty(a) && (t[a] = null); for (a in r.p) r.p.hasOwnProperty(a) && (r.p[a] = $.isArray(r.p[a]) ? [] : null); for (i = o.length, a = 0; a < i; a++)r.hasOwnProperty(o[a]) && (r[o[a]] = null, delete r[o[a]]) } }, gridUnload: function (e) { var t, r, i, o; e && (0 === (e = $.trim(e)).indexOf("#") && (e = e.substring(1)), (t = $("#" + $.jgrid.jqID(e))[0]).grid && (r = { id: $(t).attr("id"), cl: $(t).attr("class") }, t.p.pager && $(t.p.pager).off().empty().removeClass("ui-state-default ui-jqgrid-pager ui-corner-bottom"), (i = document.createElement("table")).className = r.cl, o = $.jgrid.jqID(t.id), $(i).removeClass("ui-jqgrid-btable ui-common-table").insertBefore("#gbox_" + o), 1 === $(t.p.pager).parents("#gbox_" + o).length && $(t.p.pager).insertBefore("#gbox_" + o), $.jgrid.clearBeforeUnload(e), $("#gbox_" + o).remove(), $(i).attr({ id: r.id }), $("#alertmod_" + $.jgrid.jqID(e)).remove())) }, gridDestroy: function (e) { if (e) { 0 === (e = $.trim(e)).indexOf("#") && (e = e.substring(1)); var t = $("#" + $.jgrid.jqID(e))[0]; if (t.grid) { t.p.pager && $(t.p.pager).remove(); try { $.jgrid.clearBeforeUnload(e), $("#gbox_" + $.jgrid.jqID(e)).remove() } catch (e) { } } } }, isElementInViewport: function (e) { e = e.getBoundingClientRect(); return 0 <= e.left && e.right <= (window.innerWidth || document.documentElement.clientWidth) }, getTextWidth: function (e, t) { var r; return jQuery._cacheCanvas || (r = document.createElement("canvas"), document.createDocumentFragment().appendChild(r), jQuery._cacheCanvas = r.getContext("2d"), t && (jQuery._cacheCanvas.font = t)), jQuery._cacheCanvas.measureText($.jgrid.stripHtml(e)).width }, getFont: function (e) { e = window.getComputedStyle(e, null); return e.getPropertyValue("font-style") + " " + e.getPropertyValue("font-size") + " " + e.getPropertyValue("font-family") }, setSelNavIndex: function (r, i) { var e = $(".ui-pg-button", r.p.pager); $.each(e, function (e, t) { if (i === t) return r.p.navIndex = e, !1 }), $(i).attr("tabindex", "0") }, splitSearch: function (e) { var t, r = '{"groupOp":"' + e.mergeOper + '","rules":[],"groups":['; for (t in e) e.hasOwnProperty(t) && "mergeOper" !== t && (r += null !== e[t] ? e[t] + "," : "", 0); return r = r.slice(0, -1), r += "]}" }, styleUI: { jQueryUI: { common: { disabled: "ui-state-disabled", highlight: "ui-state-highlight", hover: "ui-state-hover", cornerall: "ui-corner-all", cornertop: "ui-corner-top", cornerbottom: "ui-corner-bottom", hidden: "ui-helper-hidden", icon_base: "ui-icon", overlay: "ui-widget-overlay", active: "ui-state-active", error: "ui-state-error", button: "ui-state-default ui-corner-all", content: "ui-widget-content" }, base: { entrieBox: "ui-widget ui-widget-content ui-corner-all", viewBox: "", headerTable: "", headerBox: "ui-state-default", rowTable: "", rowBox: "ui-widget-content", stripedTable: "ui-jqgrid-table-striped", footerTable: "", footerBox: "ui-widget-content", headerRowTable: "", headerRowBox: "ui-widget-content", headerDiv: "ui-state-default", gridtitleBox: "ui-widget-header ui-corner-top ui-helper-clearfix", customtoolbarBox: "ui-state-default", loadingBox: "ui-state-default ui-state-active", rownumBox: "ui-state-default", scrollBox: "ui-widget-content", multiBox: "", pagerBox: "ui-state-default ui-corner-bottom", pagerTable: "", toppagerBox: "ui-state-default", pgInput: "ui-corner-all", pgSelectBox: "ui-widget-content ui-corner-all", pgButtonBox: "ui-corner-all", icon_first: "ui-icon-seek-first", icon_prev: "ui-icon-seek-prev", icon_next: "ui-icon-seek-next", icon_end: "ui-icon-seek-end", icon_asc: "ui-icon-triangle-1-n", icon_desc: "ui-icon-triangle-1-s", icon_caption_open: "ui-icon-circle-triangle-n", icon_caption_close: "ui-icon-circle-triangle-s" }, modal: { modal: "ui-widget ui-widget-content ui-corner-all ui-dialog", header: "ui-widget-header ui-corner-all ui-helper-clearfix", content: "ui-widget-content", resizable: "ui-resizable-handle ui-resizable-se", icon_close: "ui-icon-closethick", icon_resizable: "ui-icon-gripsmall-diagonal-se" }, celledit: { inputClass: "ui-widget-content ui-corner-all" }, inlinedit: { inputClass: "ui-widget-content ui-corner-all", icon_edit_nav: "ui-icon-pencil", icon_add_nav: "ui-icon-plus", icon_save_nav: "ui-icon-disk", icon_cancel_nav: "ui-icon-cancel" }, formedit: { inputClass: "ui-widget-content ui-corner-all", icon_prev: "ui-icon-triangle-1-w", icon_next: "ui-icon-triangle-1-e", icon_save: "ui-icon-disk", icon_close: "ui-icon-close", icon_del: "ui-icon-scissors", icon_cancel: "ui-icon-cancel" }, navigator: { icon_edit_nav: "ui-icon-pencil", icon_add_nav: "ui-icon-plus", icon_del_nav: "ui-icon-trash", icon_search_nav: "ui-icon-search", icon_refresh_nav: "ui-icon-refresh", icon_view_nav: "ui-icon-document", icon_newbutton_nav: "ui-icon-newwin" }, grouping: { icon_plus: "ui-icon-circlesmall-plus", icon_minus: "ui-icon-circlesmall-minus" }, filter: { table_widget: "ui-widget ui-widget-content", srSelect: "ui-widget-content ui-corner-all", srInput: "ui-widget-content ui-corner-all", menu_widget: "ui-widget ui-widget-content ui-corner-all", icon_search: "ui-icon-search", icon_reset: "ui-icon-arrowreturnthick-1-w", icon_query: "ui-icon-comment" }, subgrid: { icon_plus: "ui-icon-plus", icon_minus: "ui-icon-minus", icon_open: "ui-icon-carat-1-sw" }, treegrid: { icon_plus: "ui-icon-triangle-1-", icon_minus: "ui-icon-triangle-1-s", icon_leaf: "ui-icon-radio-off" }, fmatter: { icon_edit: "ui-icon-pencil", icon_add: "ui-icon-plus", icon_save: "ui-icon-disk", icon_cancel: "ui-icon-cancel", icon_del: "ui-icon-trash" }, colmenu: { menu_widget: "ui-widget ui-widget-content ui-corner-all", input_checkbox: "ui-widget ui-widget-content", filter_select: "ui-widget-content ui-corner-all", filter_input: "ui-widget-content ui-corner-all", icon_menu: "ui-icon-comment", icon_sort_asc: "ui-icon-arrow-1-n", icon_sort_desc: "ui-icon-arrow-1-s", icon_columns: "ui-icon-extlink", icon_filter: "ui-icon-calculator", icon_group: "ui-icon-grip-solid-horizontal", icon_freeze: "ui-icon-grip-solid-vertical", icon_move: "ui-icon-arrow-4", icon_new_item: "ui-icon-newwin", icon_toolbar_menu: "ui-icon-document" } }, Bootstrap: { common: { disabled: "ui-disabled", highlight: "success", hover: "active", cornerall: "", cornertop: "", cornerbottom: "", hidden: "", icon_base: "glyphicon", overlay: "ui-overlay", active: "active", error: "bg-danger", button: "btn btn-default", content: "" }, base: { entrieBox: "", viewBox: "table-responsive", headerTable: "table table-bordered", headerBox: "", rowTable: "table table-bordered", rowBox: "", stripedTable: "table-striped", footerTable: "table table-bordered", footerBox: "", headerRowTable: "table table-bordered", headerRowBox: "", headerDiv: "", gridtitleBox: "", customtoolbarBox: "", loadingBox: "row", rownumBox: "active", scrollBox: "", multiBox: "checkbox", pagerBox: "", pagerTable: "table", toppagerBox: "", pgInput: "form-control", pgSelectBox: "form-control", pgButtonBox: "", icon_first: "glyphicon-step-backward", icon_prev: "glyphicon-backward", icon_next: "glyphicon-forward", icon_end: "glyphicon-step-forward", icon_asc: "glyphicon-triangle-top", icon_desc: "glyphicon-triangle-bottom", icon_caption_open: "glyphicon-circle-arrow-up", icon_caption_close: "glyphicon-circle-arrow-down" }, modal: { modal: "modal-content", header: "modal-header", title: "modal-title", content: "modal-body", resizable: "ui-resizable-handle ui-resizable-se", icon_close: "glyphicon-remove-circle", icon_resizable: "glyphicon-import" }, celledit: { inputClass: "form-control" }, inlinedit: { inputClass: "form-control", icon_edit_nav: "glyphicon-edit", icon_add_nav: "glyphicon-plus", icon_save_nav: "glyphicon-save", icon_cancel_nav: "glyphicon-remove-circle" }, formedit: { inputClass: "form-control", icon_prev: "glyphicon-step-backward", icon_next: "glyphicon-step-forward", icon_save: "glyphicon-save", icon_close: "glyphicon-remove-circle", icon_del: "glyphicon-trash", icon_cancel: "glyphicon-remove-circle" }, navigator: { icon_edit_nav: "glyphicon-edit", icon_add_nav: "glyphicon-plus", icon_del_nav: "glyphicon-trash", icon_search_nav: "glyphicon-search", icon_refresh_nav: "glyphicon-refresh", icon_view_nav: "glyphicon-info-sign", icon_newbutton_nav: "glyphicon-new-window" }, grouping: { icon_plus: "glyphicon-triangle-right", icon_minus: "glyphicon-triangle-bottom" }, filter: { table_widget: "table table-condensed", srSelect: "form-control", srInput: "form-control", menu_widget: "", icon_search: "glyphicon-search", icon_reset: "glyphicon-refresh", icon_query: "glyphicon-comment" }, subgrid: { icon_plus: "glyphicon-triangle-right", icon_minus: "glyphicon-triangle-bottom", icon_open: "glyphicon-indent-left" }, treegrid: { icon_plus: "glyphicon-triangle-right", icon_minus: "glyphicon-triangle-bottom", icon_leaf: "glyphicon-unchecked" }, fmatter: { icon_edit: "glyphicon-edit", icon_add: "glyphicon-plus", icon_save: "glyphicon-save", icon_cancel: "glyphicon-remove-circle", icon_del: "glyphicon-trash" }, colmenu: { menu_widget: "", input_checkbox: "", filter_select: "form-control", filter_input: "form-control", icon_menu: "glyphicon-menu-hamburger", icon_sort_asc: "glyphicon-sort-by-alphabet", icon_sort_desc: "glyphicon-sort-by-alphabet-alt", icon_columns: "glyphicon-list-alt", icon_filter: "glyphicon-filter", icon_group: "glyphicon-align-left", icon_freeze: "glyphicon-object-align-horizontal", icon_move: "glyphicon-move", icon_new_item: "glyphicon-new-window", icon_toolbar_menu: "glyphicon-menu-hamburger" } }, Bootstrap4: { common: { disabled: "ui-disabled", highlight: "table-success", hover: "table-active", cornerall: "", cornertop: "", cornerbottom: "", hidden: "", overlay: "ui-overlay", active: "active", error: "alert-danger", button: "btn btn-light", content: "" }, base: { entrieBox: "", viewBox: "table-responsive", headerTable: "table table-bordered", headerBox: "", rowTable: "table table-bordered", rowBox: "", stripedTable: "table-striped", footerTable: "table table-bordered", footerBox: "", headerRowTable: "table table-bordered", headerRowBox: "", headerDiv: "", gridtitleBox: "", customtoolbarBox: "", loadingBox: "row", rownumBox: "active", scrollBox: "", multiBox: "checkbox", pagerBox: "", pagerTable: "table", toppagerBox: "", pgInput: "form-control", pgSelectBox: "form-control", pgButtonBox: "" }, modal: { modal: "modal-content", header: "modal-header", title: "modal-title", content: "modal-body", resizable: "ui-resizable-handle ui-resizable-se", icon_close: "oi-circle-x", icon_resizable: "oi-circle-x" }, celledit: { inputClass: "form-control" }, inlinedit: { inputClass: "form-control" }, formedit: { inputClass: "form-control" }, navigator: {}, grouping: {}, filter: { table_widget: "table table-condensed", srSelect: "form-control", srInput: "form-control", menu_widget: "" }, subgrid: {}, treegrid: {}, fmatter: {}, colmenu: { menu_widget: "", input_checkbox: "", filter_select: "form-control", filter_input: "form-control" } } }, iconSet: { Iconic: { common: { icon_base: "oi" }, base: { icon_first: "oi-media-step-backward", icon_prev: "oi-caret-left", icon_next: "oi-caret-right", icon_end: "oi-media-step-forward", icon_asc: "oi-caret-top", icon_desc: "oi-caret-bottom", icon_caption_open: "oi-collapse-up", icon_caption_close: "oi-expand-down" }, modal: { icon_close: "oi-circle-x", icon_resizable: "oi-plus" }, inlinedit: { icon_edit_nav: "oi-pencil", icon_add_nav: "oi-plus", icon_save_nav: "oi-check", icon_cancel_nav: "oi-action-undo" }, formedit: { icon_prev: "oi-chevron-left", icon_next: "oi-chevron-right", icon_save: "oi-check", icon_close: "oi-ban", icon_del: "oi-delete", icon_cancel: "oi-ban" }, navigator: { icon_edit_nav: "oi-pencil", icon_add_nav: "oi-plus", icon_del_nav: "oi-trash", icon_search_nav: "oi-zoom-in", icon_refresh_nav: "oi-reload", icon_view_nav: "oi-browser", icon_newbutton_nav: "oi-book" }, grouping: { icon_plus: "oi-caret-right", icon_minus: "oi-caret-bottom" }, filter: { icon_search: "oi-magnifying-glass", icon_reset: "oi-reload", icon_query: "oi-comment-square" }, subgrid: { icon_plus: "oi-chevron-right", icon_minus: "oi-chevron-bottom", icon_open: "oi-expand-left" }, treegrid: { icon_plus: "oi-plus", icon_minus: "oi-minus", icon_leaf: "oi-media-record" }, fmatter: { icon_edit: "oi-pencil", icon_add: "oi-plus", icon_save: "oi-check", icon_cancel: "oi-action-undo", icon_del: "oi-trash" }, colmenu: { icon_menu: "oi-list", icon_sort_asc: "oi-sort-ascending", icon_sort_desc: "oi-sort-descending", icon_columns: "oi-project", icon_filter: "oi-magnifying-glass", icon_group: "oi-list-rich", icon_freeze: "oi-spreadsheet", icon_move: "oi-move", icon_new_item: "oi-external-link", icon_toolbar_menu: "oi-menu" } }, Octicons: { common: { icon_base: "octicon" }, base: { icon_first: "octicon-triangle-left", icon_prev: "octicon-chevron-left", icon_next: "octicon-chevron-right", icon_end: "octicon-triangle-right", icon_asc: "octicon-triangle-up", icon_desc: "octicon-triangle-down", icon_caption_open: "octicon-triangle-up", icon_caption_close: "octicon-triangle-down" }, modal: { icon_close: "octicon-x", icon_resizable: "octicon-plus" }, inlinedit: { icon_edit_nav: "octicon-pencil", icon_add_nav: "octicon-plus", icon_save_nav: "octicon-check", icon_cancel_nav: "octicon-circle-slash" }, formedit: { icon_prev: "octicon-chevron-left", icon_next: "octicon-chevron-right", icon_save: "octicon-check", icon_close: "octicon-x", icon_del: "octicon-trashcan", icon_cancel: "octicon-circle-slash" }, navigator: { icon_edit_nav: "octicon-pencil", icon_add_nav: "octicon-plus", icon_del_nav: "octicon-trashcan", icon_search_nav: "octicon-search", icon_refresh_nav: "octicon-sync", icon_view_nav: "octicon-file", icon_newbutton_nav: "octicon-link-external" }, grouping: { icon_plus: "octicon-triangle-right", icon_minus: "octicon-triangle-down" }, filter: { icon_search: "octicon-search", icon_reset: "octicon-sync", icon_query: "octicon-file-code" }, subgrid: { icon_plus: "octicon-triangle-right", icon_minus: "octicon-triangle-down", icon_open: "octicon-git-merge" }, treegrid: { icon_plus: "octicon-triangle-right", icon_minus: "octicon-triangle-down", icon_leaf: "octicon-primitive-dot" }, fmatter: { icon_edit: "octicon-pencil", icon_add: "octicon-plus", icon_save: "octicon-check", icon_cancel: "octicon-circle-slash", icon_del: "octicon-trashcan" }, colmenu: { icon_menu: "octicon-grabber", icon_sort_asc: "octicon-arrow-up", icon_sort_desc: "octicon-arrow-down", icon_columns: "octicon-repo", icon_filter: "octicon-search", icon_group: "octicon-list-unordered", icon_freeze: "octicon-repo", icon_move: "octicon-git-compare", icon_new_item: "octicon-link-external", icon_toolbar_menu: "octicon-three-bars" } }, fontAwesome: { common: { icon_base: "fas" }, base: { icon_first: "fa-step-backward", icon_prev: "fa-backward", icon_next: "fa-forward", icon_end: "fa-step-forward", icon_asc: "fa-caret-up", icon_desc: "fa-caret-down", icon_caption_open: "fa-caret-square-up", icon_caption_close: "fa-caret-square-down " }, modal: { icon_close: "fa-window-close", icon_resizable: "fa-plus" }, inlinedit: { icon_edit_nav: "fa-edit", icon_add_nav: "fa-plus", icon_save_nav: "fa-save", icon_cancel_nav: "fa-replay" }, formedit: { icon_prev: "fa-chevron-left", icon_next: "fa-chevron-right", icon_save: "fa-save", icon_close: "fa-window-close", icon_del: "fa-trash", icon_cancel: "fa-times" }, navigator: { icon_edit_nav: "fa-edit", icon_add_nav: "fa-plus", icon_del_nav: "fa-trash", icon_search_nav: "fa-search", icon_refresh_nav: "fa-sync", icon_view_nav: "fa-sticky-note", icon_newbutton_nav: "fa-external-link-alt" }, grouping: { icon_plus: "fa-caret-right", icon_minus: "fa-caret-down" }, filter: { icon_search: "fa-search", icon_reset: "fa-reply", icon_query: "fa-pen-square " }, subgrid: { icon_plus: "fa-arrow-circle-right", icon_minus: "fa-arrow-circle-down", icon_open: "fa-ellipsis-v" }, treegrid: { icon_plus: "fa-plus", icon_minus: "fa-minus", icon_leaf: "fa-circle" }, fmatter: { icon_edit: "fa-edit", icon_add: "fa-plus", icon_save: "fa-save", icon_cancel: "fa-undo", icon_del: "fa-trash" }, colmenu: { icon_menu: "fa-ellipsis-v", icon_sort_asc: "fa-sort-amount-up", icon_sort_desc: "fa-sort-amount-down", icon_columns: "fa-columns", icon_filter: "fa-filter", icon_group: "fa-object-group", icon_freeze: "fa-snowflake", icon_move: "fa-expand-arrows-alt", icon_new_item: "fa-external-link-alt", icon_toolbar_menu: "fa-list" } } } }), $.fn.jqGrid = function (Be) { if ("string" != typeof Be) return this.each(function () { if (!this.grid) { null != Be && void 0 !== Be.data && (pe = Be.data, Be.data = []); var u = $.extend(!0, { url: "", height: 150, page: 1, rowNum: 20, rowTotal: null, records: 0, pager: "", pgbuttons: !0, pginput: !0, colModel: [], rowList: [], colNames: [], sortorder: "asc", sortname: "", datatype: "xml", mtype: "GET", altRows: !1, selarrrow: [], preserveSelection: !1, savedRow: [], shrinkToFit: !0, xmlReader: {}, jsonReader: {}, subGrid: !1, subGridModel: [], reccount: 0, lastpage: 0, lastsort: 0, selrow: null, beforeSelectRow: null, onSelectRow: null, onSortCol: null, ondblClickRow: null, onRightClickRow: null, onPaging: null, onSelectAll: null, onInitGrid: null, loadComplete: null, gridComplete: null, loadError: null, loadBeforeSend: null, afterInsertRow: null, beforeRequest: null, beforeProcessing: null, onHeaderClick: null, viewrecords: !1, loadonce: !1, multiselect: !1, multikey: !1, multiboxonly: !1, multimail: !1, multiselectWidth: 30, editurl: null, search: !1, caption: "", hidegrid: !0, hiddengrid: !1, postData: {}, userData: {}, treeGrid: !1, treeGridModel: "nested", treeReader: {}, treeANode: -1, ExpandColumn: null, tree_root_level: 0, prmNames: { page: "page", rows: "rows", sort: "sidx", order: "sord", search: "_search", nd: "nd", id: "id", oper: "oper", editoper: "edit", addoper: "add", deloper: "del", subgridid: "id", npage: null, totalrows: "totalrows" }, forceFit: !1, gridstate: "visible", cellEdit: !1, cellsubmit: "remote", nv: 0, loadui: "enable", toolbar: [!1, ""], scroll: !1, deselectAfterSort: !0, scrollrows: !1, autowidth: !1, scrollOffset: $.jgrid.scrollbarWidth() + 3, cellLayout: 5, subGridWidth: 20, gridview: !0, rownumWidth: 35, rownumbers: !1, pagerpos: "center", recordpos: "right", footerrow: !1, userDataOnFooter: !1, headerrow: !1, userDataOnHeader: !1, hoverrows: !0, viewsortcols: [!1, "vertical", !0], resizeclass: "", autoencode: !1, remapColumns: [], ajaxGridOptions: {}, direction: "ltr", toppager: !1, headertitles: !1, scrollTimeout: 40, data: [], _index: {}, grouping: !1, groupingView: { groupField: [], groupOrder: [], groupText: [], groupColumnShow: [], groupSummary: [], showSummaryOnHide: !1, sortitems: [], sortnames: [], summary: [], summaryval: [], plusicon: "", minusicon: "", displayField: [], groupSummaryPos: [], formatDisplayField: [], _locgr: !1 }, groupHeaderOn: !1, ignoreCase: !0, cmTemplate: {}, idPrefix: "", multiSort: !1, minColWidth: 33, scrollPopUp: !1, scrollTopOffset: 0, scrollLeftOffset: "100%", scrollMaxBuffer: 0, storeNavOptions: !1, regional: "en", styleUI: "jQueryUI", iconSet: "Iconic", responsive: !1, forcePgButtons: !1, restoreCellonFail: !0, editNextRowCell: !1, colFilters: {}, colMenu: !1, colMenuCustom: {}, colMenuColumnDone: null, treeGrid_bigData: !1, treeGrid_rootParams: { otherData: {} }, treeGrid_beforeRequest: null, treeGrid_afterLoadComplete: null, useNameForSearch: !1, formatFooterData: !1, formatHeaderData: !1, mergeSearch: !1, searchModules: { mergeOper: "AND", filterInput: !0, filterToolbar: !0, searchGrid: !0 } }, $.jgrid.defaults, Be); void 0 !== pe && (u.data = pe, Be.data = pe); var V = this, g = { headers: [], cols: [], footers: [], hrheaders: [], dragStart: function (e, t, r) { var i = $(this.bDiv).offset().left, o = parseInt(u.colModel[e].minResizeWidth || u.minColWidth, 10); isNaN(o) && (o = 33), this.resizing = { idx: e, startX: t.pageX, sOL: t.pageX - i, minW: o }, this.hDiv.style.cursor = "col-resize", this.curGbox = $("#rs_m" + $.jgrid.jqID(u.id), "#gbox_" + $.jgrid.jqID(u.id)), this.curGbox.css({ display: "block", left: t.pageX - i, top: r[1], height: r[2] }), $(V).triggerHandler("jqGridResizeStart", [t, e]), $.isFunction(u.resizeStart) && u.resizeStart.call(V, t, e), document.onselectstart = function () { return !1 } }, dragMove: function (e) { var t, r, i, o; this.resizing && (t = e.pageX - this.resizing.startX, r = this.headers[this.resizing.idx], (i = "ltr" === u.direction ? r.width + t : r.width - t) > this.resizing.minW && (this.curGbox.css({ left: this.resizing.sOL + t }), !0 === u.forceFit ? (o = this.headers[this.resizing.idx + u.nv], (e = "ltr" === u.direction ? o.width - t : o.width + t) > this.resizing.minW && (r.newWidth = i, o.newWidth = e)) : (this.newWidth = "ltr" === u.direction ? u.tblwidth + t : u.tblwidth - t, r.newWidth = i))) }, dragEnd: function (e) { var t, r; this.hDiv.style.cursor = "default", this.resizing && (t = this.resizing.idx, r = this.headers[t].newWidth || this.headers[t].width, r = parseInt(r, 10), this.resizing = !1, $("#rs_m" + $.jgrid.jqID(u.id)).css("display", "none"), u.colModel[t].width = r, this.headers[t].width = r, this.headers[t].el.style.width = r + "px", this.cols[t].style.width = r + "px", 0 < this.footers.length && (this.footers[t].style.width = r + "px"), 0 < this.hrheaders.length && (this.hrheaders[t].style.width = r + "px"), !0 === u.forceFit ? (r = this.headers[t + u.nv].newWidth || this.headers[t + u.nv].width, this.headers[t + u.nv].width = r, this.headers[t + u.nv].el.style.width = r + "px", this.cols[t + u.nv].style.width = r + "px", 0 < this.footers.length && (this.footers[t + u.nv].style.width = r + "px"), 0 < this.hrheaders.length && (this.hrheaders[t + u.nv].style.width = r + "px"), u.colModel[t + u.nv].width = r) : (u.tblwidth = this.newWidth || u.tblwidth, $("table:first", this.bDiv).css("width", u.tblwidth + "px"), $("table:first", this.hDiv).css("width", u.tblwidth + "px"), this.hDiv.scrollLeft = this.bDiv.scrollLeft, u.footerrow && ($("table:first", this.sDiv).css("width", u.tblwidth + "px"), this.sDiv.scrollLeft = this.bDiv.scrollLeft), u.headerrow && ($("table:first", this.hrDiv).css("width", u.tblwidth + "px"), this.hrDiv.scrollLeft = this.bDiv.scrollLeft)), e && ($(V).triggerHandler("jqGridResizeStop", [r, t]), $.isFunction(u.resizeStop) && u.resizeStop.call(V, r, t)), u.frozenColumns && ($("#" + $.jgrid.jqID(u.id)).jqGrid("destroyFrozenColumns"), $("#" + $.jgrid.jqID(u.id)).jqGrid("setFrozenColumns"))), this.curGbox = null, document.onselectstart = function () { return !0 } }, populateVisible: function () { g.timer && clearTimeout(g.timer), g.timer = null; var e = $(g.bDiv).height(); if (e) { var t, r, i, o, a, n, l, s, d, p, c = $("table:first", g.bDiv); if (c[0].rows.length) try { r = (t = c[0].rows[1]) && $(t).outerHeight() || g.prevRowHeight } catch (e) { r = g.prevRowHeight } r && (g.prevRowHeight = r, i = u.rowNum, o = g.scrollTop = g.bDiv.scrollTop, l = r * i, (n = (a = Math.round(c.position().top) - o) + c.height()) < e && a <= 0 && (void 0 === u.lastpage || (parseInt((n + o + l - 1) / l, 10) || 0) <= u.lastpage) && (d = parseInt((e - n + l - 1) / l, 10) || 1, a = 0 <= n || d < 2 || !0 === u.scroll ? (s = (Math.round((n + o) / l) || 0) + 1, -1) : 1), 0 < a && (s = (parseInt(o / l, 10) || 0) + 1, d = (parseInt((o + e) / l, 10) || 0) + 2 - s, p = !0), d && (u.lastpage && (s > u.lastpage || 1 === u.lastpage || s === u.page && s === u.lastpage) || (g.hDiv.loading ? g.timer = setTimeout(g.populateVisible, u.scrollTimeout) : (u.page = s, 0 < u.scrollMaxBuffer && (0 < i && u.scrollMaxBuffer < i && (u.scrollMaxBuffer = i + 1), u.reccount > u.scrollMaxBuffer - (0 < i ? i : 0) && (p = !0)), p && (g.selectionPreserver(c[0]), g.emptyRows.call(c[0], !1, !1)), g.populate(d)), u.scrollPopUp && null != u.lastpage && ($("#scroll_g" + u.id).show().html($.jgrid.template($.jgrid.getRegional(V, "defaults.pgtext", u.pgtext), u.page, u.lastpage)).css({ top: u.scrollTopOffset + o * ((parseInt(u.height, 10) - 45) / (parseInt(r, 10) * parseInt(u.records, 10))) + "px", left: u.scrollLeftOffset }), $(this).mouseout(function () { $("#scroll_g" + u.id).hide() }))))) } }, scrollGrid: function () { var e; u.scroll && (e = g.bDiv.scrollTop, void 0 === g.scrollTop && (g.scrollTop = 0), e !== g.scrollTop && (g.scrollTop = e, g.timer && clearTimeout(g.timer), g.timer = setTimeout(g.populateVisible, u.scrollTimeout))), g.hDiv.scrollLeft = g.bDiv.scrollLeft, u.footerrow && (g.sDiv.scrollLeft = g.bDiv.scrollLeft), u.headerrow && (g.hrDiv.scrollLeft = g.bDiv.scrollLeft), u.frozenColumns && $(g.fbDiv).scrollTop(g.bDiv.scrollTop); try { $("#column_menu").remove() } catch (e) { } }, selectionPreserver: function (t) { var r = t.p, i = r.selrow, o = r.selarrrow ? $.makeArray(r.selarrrow) : null, a = t.grid.bDiv.scrollLeft, n = function () { var e; if (r.multiselect && o && 0 < o.length) for (e = 0; e < o.length; e++)o[e] && $(t).jqGrid("setSelection", o[e], !1, "_sp_"); !r.multiselect && i && $(t).jqGrid("setSelection", i, !1, null), t.grid.bDiv.scrollLeft = a, $(t).off(".selectionPreserver", n) }; $(t).on("jqGridGridComplete.selectionPreserver", n) } }; if ("TABLE" === this.tagName.toUpperCase() && null != this.id) if (void 0 !== document.documentMode && document.documentMode <= 5) alert("Grid can not be used in this ('quirks') mode!"); else { var e, t, m, W, r = 0; for (t in $.jgrid.regional) $.jgrid.regional.hasOwnProperty(t) && (0 === r && (e = t), r++); if (1 === r && e !== u.regional && (u.regional = e), $(this).empty().attr("tabindex", "0"), this.p = u, this.p.useProp = !!$.fn.prop, 0 === this.p.colNames.length) for (r = 0; r < this.p.colModel.length; r++)this.p.colNames[r] = this.p.colModel[r].label || this.p.colModel[r].name; if (this.p.colNames.length === this.p.colModel.length) { "Bootstrap4" === V.p.styleUI && $.jgrid.iconSet.hasOwnProperty(V.p.iconSet) && $.extend(!0, $.jgrid.styleUI.Bootstrap4, $.jgrid.iconSet[V.p.iconSet]); var Q = $.jgrid.getMethod("getStyleUI"), X = V.p.styleUI + ".common", v = Q(X, "disabled", !0), Y = Q(X, "highlight", !0), y = Q(X, "hover", !0), i = Q(X, "cornerall", !0), w = Q(X, "icon_base", !0), x = $.jgrid.styleUI[V.p.styleUI || "jQueryUI"].colmenu, o = $.jgrid.msie(), C = [], F = [], a = [], X = V.p.styleUI + ".base", n = $("<div " + Q(X, "viewBox", !1, "ui-jqgrid-view") + " role='grid'></div>"); V.p.direction = $.trim(V.p.direction.toLowerCase()), V.p._ald = !1, -1 === $.inArray(V.p.direction, ["ltr", "rtl"]) && (V.p.direction = "ltr"), m = V.p.direction, $(n).insertBefore(this), $(this).appendTo(n); var l = $("<div " + Q(X, "entrieBox", !1, "ui-jqgrid") + "></div>"); $(l).attr({ id: "gbox_" + this.id, dir: m }).insertBefore(n), $(n).attr("id", "gview_" + this.id).appendTo(l), $("<div " + Q(V.p.styleUI + ".common", "overlay", !1, "jqgrid-overlay") + " id='lui_" + this.id + "'></div>").insertBefore(n), $("<div " + Q(X, "loadingBox", !1, "loading") + " id='load_" + this.id + "'>" + $.jgrid.getRegional(V, "defaults.loadtext", this.p.loadtext) + "</div>").insertBefore(n), $(this).attr({ role: "presentation", "aria-multiselectable": !!this.p.multiselect, "aria-labelledby": "gbox_" + this.id }); var s, d = $.jgrid.getFont(V), K = function (e, t) { return e = parseInt(e, 10), isNaN(e) ? t || 0 : e }, p = function (e, t, r, i, o, a) { var n, l = V.p.colModel[e], s = l.align, d = 'style="', p = l.classes, c = l.name, u = []; return s && (d += "text-align:" + s + ";"), !0 === l.hidden && (d += "display:none;"), 0 === t ? d += "width: " + g.headers[e].width + "px;" : ($.isFunction(l.cellattr) || "string" == typeof l.cellattr && null != $.jgrid.cellattr && $.isFunction($.jgrid.cellattr[l.cellattr])) && (n = ($.isFunction(l.cellattr) ? l.cellattr : $.jgrid.cellattr[l.cellattr]).call(V, o, r, i, l, a)) && "string" == typeof n && (-1 < n.indexOf("title") && (l.title = !1), -1 < n.indexOf("class") && (p = void 0), 2 === (u = (n = String(n).replace(/\s+\=/g, "=")).split("style=")).length ? (u[1] = $.trim(u[1]), 0 !== u[1].indexOf("'") && 0 !== u[1].indexOf('"') || (u[1] = u[1].substring(1)), d += u[1].replace(/'/gi, '"')) : d += '"'), u.length ? 2 < u.length && (u[0] = "") : (u[0] = "", d += '"'), d += (void 0 !== p ? ' class="' + p + '"' : "") + (l.title && r ? ' title="' + $.jgrid.stripHtml(r) + '"' : ""), (d += ' aria-describedby="' + V.p.id + "_" + c + '"') + u[0] }, c = function (e) { return null == e || "" === e ? "&#160;" : V.p.autoencode ? $.jgrid.htmlEncode(e) : String(e) }, h = function (e, t, r, i, o) { var a = V.p.colModel[r]; return t = void 0 !== a.formatter ? (r = { rowId: e = "" !== String(V.p.idPrefix) ? $.jgrid.stripPref(V.p.idPrefix, e) : e, colModel: a, gid: V.p.id, pos: r, styleUI: V.p.styleUI }, $.isFunction(a.formatter) ? a.formatter.call(V, t, r, i, o) : $.fmatter ? $.fn.fmatter.call(V, a.formatter, t, r, i, o) : c(t)) : c(t), a.autosize && (a._maxsize || (a._maxsize = 0), a._maxsize = Math.max($.jgrid.getTextWidth(t, d), a._maxsize)), t }, J = function (e, t, r, i, o, a) { t = h(e, t, r, o, "add"); return '<td role="gridcell" ' + p(r, i, t, o, e, a) + ">" + t + "</td>" }, Z = function (e, t, r, i, o) { i = '<input role="checkbox" type="checkbox" id="jqg_' + V.p.id + "_" + e + '" ' + o + ' name="jqg_' + V.p.id + "_" + e + '"' + (i ? 'checked="checked"' : "") + "/>"; return '<td role="gridcell" ' + p(t, r, "", null, e, !0) + ">" + i + "</td>" }, ee = function (e, t, r, i, o) { i = (parseInt(r, 10) - 1) * parseInt(i, 10) + 1 + t; return '<td role="gridcell" ' + o + " " + p(e, t, i, null, t, !0) + ">" + i + "</td>" }, te = function (e) { for (var t, r = [], i = 0, o = 0; o < V.p.colModel.length; o++)"cb" !== (t = V.p.colModel[o]).name && "subgrid" !== t.name && "rn" !== t.name && (r[i] = "local" === e ? t.name : "xml" === e || "xmlstring" === e ? t.xmlmap || t.name : t.jsonmap || t.name, !1 !== V.p.keyName && !0 === t.key && (V.p.keyName = r[i], V.p.keyIndex = i), i++); return r }, re = function (t) { var e = V.p.remapColumns; return e && e.length || (e = $.map(V.p.colModel, function (e, t) { return t })), t && (e = $.map(e, function (e) { return e < t ? null : e - t })), e }, ie = function (e, t) { var r; this.p.deepempty ? $(this.rows).slice(1).remove() : (r = 0 < this.rows.length ? this.rows[0] : null, $(this.firstChild).empty().append(r)), e && this.p.scroll && ($(this.grid.bDiv.firstChild).css({ height: "auto" }), $(this.grid.bDiv.firstChild.firstChild).css({ height: "0px", display: "none" }), 0 !== this.grid.bDiv.scrollTop && (this.grid.bDiv.scrollTop = 0)), !0 === t && (this.p.data = [], this.p._index = {}) }, f = function () { var e, t, r, i, o, a, n, l, s, d, p, c = V.p, u = c.data, h = u.length, g = c.localReader, f = c.colModel, m = g.cell, v = (!0 === c.multiselect ? 1 : 0) + (!0 === c.subGrid ? 1 : 0) + (!0 === c.rownumbers ? 1 : 0), b = c.scroll ? $.jgrid.randId() : 1; if ("local" === c.datatype && !0 === g.repeatitems) for (s = re(v), d = te("local"), i = !1 === c.keyName ? $.isFunction(g.id) ? g.id.call(V, u) : g.id : c.keyName, e = 0; e < h; e++) { for (r = u[e], void 0 === (o = $.jgrid.getAccessor(r, i)) && ("number" == typeof i && null != f[i + v] && (o = $.jgrid.getAccessor(r, f[i + v].name)), void 0 === o && (o = b + e, m && (o = null != (a = $.jgrid.getAccessor(r, m) || r) && void 0 !== a[i] ? a[i] : o, a = null))), (l = {})[g.id] = o, m && (r = $.jgrid.getAccessor(r, m) || r), p = $.isArray(r) ? s : d, t = 0; t < p.length; t++)n = $.jgrid.getAccessor(r, p[t]), l[f[t + v].name] = n; u[e] = l } }, oe = function () { var e, t, r = V.p.data.length, i = !1 !== V.p.keyName ? V.p.keyName : i = V.p.localReader.id; for (V.p._index = {}, e = 0; e < r; e++)void 0 === (t = $.jgrid.getAccessor(V.p.data[e], i)) && (t = String(e + 1)), V.p._index[t] = e }, ae = function (e, t, r, i, o) { var a, n = "-1", l = "", t = t ? "display:none;" : "", s = $(V).triggerHandler("jqGridRowAttr", [i, o, e]); if ("object" != typeof s && (s = $.isFunction(V.p.rowattr) ? V.p.rowattr.call(V, i, o, e) : "string" == typeof V.p.rowattr && null != $.jgrid.rowattr && $.isFunction($.jgrid.rowattr[V.p.rowattr]) ? $.jgrid.rowattr[V.p.rowattr].call(V, i, o, e) : {}), !$.isEmptyObject(s)) { s.hasOwnProperty("id") && (e = s.id, delete s.id), s.hasOwnProperty("tabindex") && (n = s.tabindex, delete s.tabindex), s.hasOwnProperty("style") && (t += s.style, delete s.style), s.hasOwnProperty("class") && (r += " " + s.class, delete s.class); try { delete s.role } catch (e) { } for (a in s) s.hasOwnProperty(a) && (l += " " + a + "=" + s[a]) } return '<tr role="row" id="' + e + '" tabindex="' + n + '" class="' + r + '"' + ("" === t ? "" : ' style="' + t + '"') + l + ">" }, b = function (e, r, t, i) { var o = new Date, a = "local" !== V.p.datatype && V.p.loadonce || "xmlstring" === V.p.datatype, n = "_id_", l = V.p.xmlReader, s = [], d = "local" === V.p.datatype ? "local" : "xml"; if (a && (V.p.data = [], V.p._index = {}, V.p.localReader.id = n), V.p.reccount = 0, $.isXMLDoc(e)) { r = -1 !== V.p.treeANode || V.p.scroll ? 1 < r ? r : 1 : (ie.call(V, !1, !1), 1); var p, c, u, h, g, f, m, v, b, j = $(V), y = 0, w = !0 === V.p.multiselect ? 1 : 0, x = 0, _ = !0 === V.p.rownumbers ? 1 : 0, q = [], I = {}, D = [], C = Q(X, "rowBox", !0, "jqgrow ui-row-" + V.p.direction); !0 === V.p.subGrid && (x = 1, h = $.jgrid.getMethod("addSubGridCell")), l.repeatitems || (q = te(d)), g = !1 === V.p.keyName ? $.isFunction(l.id) ? l.id.call(V, e) : l.id : V.p.keyName, l.repeatitems && V.p.keyName && isNaN(g) && (g = V.p.keyIndex), f = -1 === String(g).indexOf("[") ? q.length ? function (e, t) { return $(g, e).text() || t } : function (e, t) { return $(l.cell, e).eq(g).text() || t } : function (e, t) { return e.getAttribute(g.replace(/[\[\]]/g, "")) || t }, V.p.userData = {}, V.p.page = K($.jgrid.getXmlData(e, l.page), V.p.page), V.p.lastpage = K($.jgrid.getXmlData(e, l.total), 1), V.p.records = K($.jgrid.getXmlData(e, l.records)), $.isFunction(l.userdata) ? V.p.userData = l.userdata.call(V, e) || {} : $.jgrid.getXmlData(e, l.userdata, !0).each(function () { V.p.userData[this.getAttribute("name")] = $(this).text() }); var F, G, k = $.jgrid.getXmlData(e, l.root, !0), S = (k = (k = $.jgrid.getXmlData(k, l.row, !0)) || []).length, R = 0, M = [], N = parseInt(V.p.rowNum, 10), O = V.p.scroll ? $.jgrid.randId() : 1, T = $(V).find("tbody:first"), A = !1; if (V.p.grouping && (A = !0 === V.p.groupingView.groupCollapse, F = $.jgrid.getMethod("groupingPrepare")), 0 < S && V.p.page <= 0 && (V.p.page = 1), k && S) { i && (N *= i + 1); for (var P = $.isFunction(V.p.afterInsertRow), E = _ ? Q(X, "rownumBox", !1, "jqgrid-rownum") : "", B = w ? Q(X, "multiBox", !1, "cbox") : ""; R < S;) { v = k[R], b = f(v, O + R), b = V.p.idPrefix + b, V.p.preserveSelection && (V.p.multiselect ? (G = -1 !== V.p.selarrrow.indexOf(b), W = G ? W + 1 : W) : G = b === V.p.selrow); var H = D.length; if (D.push(""), _ && D.push(ee(0, R, V.p.page, V.p.rowNum, E)), w && D.push(Z(b, _, R, G, B)), x && D.push(h.call(j, w + _, R + r)), l.repeatitems) { m = m || re(w + x + _); var z = $.jgrid.getXmlData(v, l.cell, !0); $.each(m, function (e) { var t = z[this]; if (!t) return !1; u = t.textContent || t.text || "", I[V.p.colModel[e + w + x + _].name] = u, D.push(J(b, u, e + w + x + _, R + r, v, I)) }) } else for (p = 0; p < q.length; p++)u = $.jgrid.getXmlData(v, q[p]), I[V.p.colModel[p + w + x + _].name] = u, D.push(J(b, u, p + w + x + _, R + r, v, I)); if (D[H] = ae(b, A, C, I, v), D.push("</tr>"), V.p.grouping && (M.push(D), V.p.groupingView._locgr || F.call(j, I, R), D = []), (a || !0 === V.p.treeGrid && !V.p._ald) && (I[n] = $.jgrid.stripPref(V.p.idPrefix, b), V.p.data.push(I), V.p._index[I[n]] = V.p.data.length - 1, -1 < V.p.treeANode && "adjacency" === V.p.treeGridModel && s.push(I)), !1 === V.p.gridview && (T.append(D.join("")), j.triggerHandler("jqGridAfterInsertRow", [b, I, v]), P && V.p.afterInsertRow.call(V, b, I, v), D = []), I = {}, R++, ++y === N) break } } if (W = V.p.multiselect && V.p.preserveSelection && y === W, !0 === V.p.gridview && (c = -1 < V.p.treeANode ? V.p.treeANode : 0, V.p.grouping ? a || (j.jqGrid("groupingRender", M, V.p.colModel.length, V.p.page, N), M = null) : !0 === V.p.treeGrid && 0 < c ? $(V.rows[c]).after(D.join("")) : (T.append(D.join("")), V.grid.cols = V.rows[0].cells)), V.p.totaltime = new Date - o, D = null, 0 < y && 0 === V.p.records && (V.p.records = S), !0 === V.p.treeGrid) { try { j.jqGrid("setTreeNode", c + 1, y + c + 1) } catch (e) { } if (-1 < V.p.treeANode && "adjacency" === V.p.treeGridModel && (u = V.rows[V.p.treeANode].id, 1 <= (u = V.p._index[u] + 1))) { for (V.p.data.splice(-S, S), p = 0; p < S; p++)V.p.data.splice(u + p, 0, s[p]); oe() } } if (V.p.reccount = y, V.p.treeANode = -1, V.p.userDataOnFooter && j.jqGrid("footerData", "set", V.p.userData, V.p.formatFooterData), V.p.userDataOnHeader && j.jqGrid("headerData", "set", V.p.userData, V.p.formatHeaderData), a && (V.p.records = S, V.p.lastpage = Math.ceil(S / N)), t || V.updatepager(!1, !0), W && ne(!0), a) { for (; y < S;) { if (v = k[y], b = f(v, y + O), b = V.p.idPrefix + b, l.repeatitems) { m = m || re(w + x + _); var U = $.jgrid.getXmlData(v, l.cell, !0); $.each(m, function (e) { var t = U[this]; if (!t) return !1; u = t.textContent || t.text || "", I[V.p.colModel[e + w + x + _].name] = u }) } else for (p = 0; p < q.length; p++)u = $.jgrid.getXmlData(v, q[p]), I[V.p.colModel[p + w + x + _].name] = u; I[n] = $.jgrid.stripPref(V.p.idPrefix, b), V.p.grouping && F.call(j, I, y), V.p.data.push(I), V.p._index[I[n]] = V.p.data.length - 1, I = {}, y++ } V.p.grouping && (V.p.groupingView._locgr = !0, j.jqGrid("groupingRender", M, V.p.colModel.length, V.p.page, N), M = null) } if (!0 === V.p.subGrid) try { j.jqGrid("addSubGrid", w + _) } catch (e) { } } }, j = function (e, t, r, i) { var o, a, n = new Date; if (e) { t = -1 !== V.p.treeANode || V.p.scroll ? 1 < t ? t : 1 : (ie.call(V, !1, !1), 1), a = "local" === V.p.datatype ? (o = V.p.localReader, "local") : (o = V.p.jsonReader, "json"); var l, s, d, p, c, u, h, g, f, m, v, b, j = "_id_", y = "local" !== V.p.datatype && V.p.loadonce || "jsonstring" === V.p.datatype, w = $(V), x = 0, _ = [], q = V.p.multiselect ? 1 : 0, I = !0 === V.p.subGrid ? 1 : 0, D = !0 === V.p.rownumbers ? 1 : 0, C = V.p.scroll && "local" !== V.p.datatype ? $.jgrid.randId() : 1, F = parseInt(V.p.rowNum, 10), G = !1, k = re(q + I + D), S = te(a), R = {}, M = [], N = [], O = Q(X, "rowBox", !0, "jqgrow ui-row-" + V.p.direction), T = $.isFunction(V.p.afterInsertRow), A = [], P = !1, E = $(V).find("tbody:first"), B = D ? Q(X, "rownumBox", !1, "jqgrid-rownum") : "", H = q ? Q(X, "multiBox", !1, "cbox") : ""; for (y && (V.p.data = [], V.p._index = {}, V.p.localReader.id = j), V.p.reccount = 0, V.p.page = K($.jgrid.getAccessor(e, o.page), V.p.page), V.p.lastpage = K($.jgrid.getAccessor(e, o.total), 1), V.p.records = K($.jgrid.getAccessor(e, o.records)), V.p.userData = $.jgrid.getAccessor(e, o.userdata) || {}, I && (p = $.jgrid.getMethod("addSubGridCell")), f = !1 === V.p.keyName ? $.isFunction(o.id) ? o.id.call(V, e) : o.id : V.p.keyName, o.repeatitems && V.p.keyName && isNaN(f) && (f = V.p.keyIndex), null == (g = $.jgrid.getAccessor(e, o.root)) && $.isArray(e) && (g = e), (s = 0) < (h = (g = g || []).length) && V.p.page <= 0 && (V.p.page = 1), i && (F *= i + 1), "local" !== V.p.datatype || V.p.deselectAfterSort || (G = !0), V.p.grouping && (P = !0 === V.p.groupingView.groupCollapse, v = $.jgrid.getMethod("groupingPrepare")); s < h;) { var z, U = g[s]; void 0 === (z = $.jgrid.getAccessor(U, f)) && ("number" == typeof f && null != V.p.colModel[f + q + I + D] && (z = $.jgrid.getAccessor(U, V.p.colModel[f + q + I + D].name)), void 0 === z && (z = C + s, 0 === _.length && o.cell && (z = null != (L = $.jgrid.getAccessor(U, o.cell) || U) && void 0 !== L[f] ? L[f] : z, L = null))), z = V.p.idPrefix + z, (G || V.p.preserveSelection) && (V.p.multiselect ? (c = -1 !== V.p.selarrrow.indexOf(z), W = c ? W + 1 : W) : c = z === V.p.selrow); var L = M.length; for (M.push(""), D && M.push(ee(0, s, V.p.page, V.p.rowNum, B)), q && M.push(Z(z, D, s, c, H)), I && M.push(p.call(w, q + D, s + t)), u = S, o.repeatitems && (o.cell && (U = $.jgrid.getAccessor(U, o.cell) || U), $.isArray(U) && (u = k)), d = 0; d < u.length; d++)l = $.jgrid.getAccessor(U, u[d]), R[V.p.colModel[d + q + I + D].name] = l, M.push(J(z, l, d + q + I + D, s + t, U, R)); if (M[L] = ae(z, P, c ? O + " " + Y : O, R, U), M.push("</tr>"), V.p.grouping && (A.push(M), V.p.groupingView._locgr || v.call(w, R, s), M = []), (y || !0 === V.p.treeGrid && !V.p._ald) && (R[j] = $.jgrid.stripPref(V.p.idPrefix, z), V.p.data.push(R), V.p._index[R[j]] = V.p.data.length - 1, -1 < V.p.treeANode && "adjacency" === V.p.treeGridModel && N.push(R)), !1 === V.p.gridview && (E.append(M.join("")), w.triggerHandler("jqGridAfterInsertRow", [z, R, U]), T && V.p.afterInsertRow.call(V, z, R, U), M = []), R = {}, s++, ++x === F) break } if (W = V.p.multiselect && (V.p.preserveSelection || G) && x === W, !0 === V.p.gridview && (m = -1 < V.p.treeANode ? V.p.treeANode : 0, V.p.grouping ? y || (w.jqGrid("groupingRender", A, V.p.colModel.length, V.p.page, F), A = null) : !0 === V.p.treeGrid && 0 < m ? $(V.rows[m]).after(M.join("")) : (E.append(M.join("")), V.grid.cols = V.rows[0].cells)), V.p.totaltime = new Date - n, M = null, 0 < x && 0 === V.p.records && (V.p.records = h), !0 === V.p.treeGrid) { try { w.jqGrid("setTreeNode", m + 1, x + m + 1) } catch (e) { } if (-1 < V.p.treeANode && "adjacency" === V.p.treeGridModel && (l = V.rows[V.p.treeANode].id, 1 <= (l = V.p._index[l] + 1))) { for (V.p.data.splice(-h, h), s = 0; s < h; s++)V.p.data.splice(l + s, 0, N[s]); oe() } } if (V.p.reccount = x, V.p.treeANode = -1, V.p.userDataOnFooter && w.jqGrid("footerData", "set", V.p.userData, V.p.formatFooterData), V.p.userDataOnHeader && w.jqGrid("headerData", "set", V.p.userData, V.p.formatHeaderData), y && (V.p.records = h, V.p.lastpage = Math.ceil(h / F)), r || V.updatepager(!1, !0), W && ne(!0), y) { for (; x < h && g[x];) { if (U = g[x], void 0 === (z = $.jgrid.getAccessor(U, f)) && ("number" == typeof f && null != V.p.colModel[f + q + I + D] && (z = $.jgrid.getAccessor(U, V.p.colModel[f + q + I + D].name)), void 0 === z && (z = C + x, 0 === _.length && o.cell && (z = null != (b = $.jgrid.getAccessor(U, o.cell) || U) && void 0 !== b[f] ? b[f] : z, b = null))), U) { for (z = V.p.idPrefix + z, u = S, o.repeatitems && (o.cell && (U = $.jgrid.getAccessor(U, o.cell) || U), $.isArray(U) && (u = k)), d = 0; d < u.length; d++)R[V.p.colModel[d + q + I + D].name] = $.jgrid.getAccessor(U, u[d]); R[j] = $.jgrid.stripPref(V.p.idPrefix, z), V.p.grouping && v.call(w, R, x), V.p.data.push(R), V.p._index[R[j]] = V.p.data.length - 1, R = {} } x++ } V.p.grouping && (V.p.groupingView._locgr = !0, w.jqGrid("groupingRender", A, V.p.colModel.length, V.p.page, F), A = null) } if (!0 === V.p.subGrid) try { w.jqGrid("addSubGrid", q + D) } catch (e) { } } }, _ = function (e) { var t, r, i, o, a = V.p.multiSort ? [] : "", n = [], l = !1, p = {}, s = [], d = []; if ($.isArray(V.p.data)) { var c, u, h, g = !!V.p.grouping && V.p.groupingView; if ($.each(V.p.colModel, function () { if ("cb" === this.name || "subgrid" === this.name || "rn" === this.name) return !0; if (r = this.sorttype || "text", h = this.index || this.name, "date" === r || "datetime" === r ? (this.formatter && "string" == typeof this.formatter && "date" === this.formatter ? (t = this.formatoptions && this.formatoptions.srcformat ? this.formatoptions.srcformat : $.jgrid.getRegional(V, "formatter.date.srcformat"), i = this.formatoptions && this.formatoptions.newformat ? this.formatoptions.newformat : $.jgrid.getRegional(V, "formatter.date.newformat")) : t = i = this.datefmt || "Y-m-d", p[h] = { stype: r, srcfmt: t, newfmt: i, sfunc: this.sortfunc || null, name: this.name }) : p[h] = { stype: r, srcfmt: "", newfmt: "", sfunc: this.sortfunc || null, name: this.name }, V.p.grouping) for (u = 0, c = g.groupField.length; u < c; u++)this.name === g.groupField[u] && (s[u] = p[h], d[u] = h); V.p.multiSort || l || h !== V.p.sortname || (a = h, l = !0) }), V.p.multiSort && (a = C, n = F), !V.p.treeGrid || !V.p._sort) { var f = { eq: function (e) { return e.equals }, ne: function (e) { return e.notEquals }, lt: function (e) { return e.less }, le: function (e) { return e.lessOrEquals }, gt: function (e) { return e.greater }, ge: function (e) { return e.greaterOrEquals }, cn: function (e) { return e.contains }, nc: function (e, t) { return ("OR" === t ? e.orNot() : e.andNot()).contains }, bw: function (e) { return e.startsWith }, bn: function (e, t) { return ("OR" === t ? e.orNot() : e.andNot()).startsWith }, en: function (e, t) { return ("OR" === t ? e.orNot() : e.andNot()).endsWith }, ew: function (e) { return e.endsWith }, ni: function (e, t) { return ("OR" === t ? e.orNot() : e.andNot()).inData }, in: function (e) { return e.inData }, nu: function (e) { return e.isNull }, nn: function (e, t) { return ("OR" === t ? e.orNot() : e.andNot()).isNull } }, m = $.jgrid.from.call(V, V.p.data); if (V.p.ignoreCase && (m = m.ignoreCase()), !0 === V.p.search) { var v = V.p.postData.filters; if (v) "string" == typeof v && (v = $.jgrid.parse(v)), function e(t) { var r, i, o, a, n, l, s, d = 0; if (null != t.groups) { for ((i = t.groups.length && "OR" === t.groupOp.toString().toUpperCase()) && m.orBegin(), r = 0; r < t.groups.length; r++) { 0 < d && i && m.or(); try { e(t.groups[r]) } catch (e) { alert(e) } d++ } i && m.orEnd() } if (null != t.rules) try { for ((s = t.rules.length && "OR" === t.groupOp.toString().toUpperCase()) && m.orBegin(), r = 0; r < t.rules.length; r++) { if (a = t.rules[r], o = t.groupOp.toString().toUpperCase(), f[a.op] && a.field) { 0 < d && o && "OR" === o && (m = m.or()), l = a.field, V.p.useNameForSearch && p.hasOwnProperty(a.field) && (l = p[a.field].name); try { "date" === (n = p[a.field]).stype && "string" == typeof n.srcfmt && "string" == typeof n.newfmt && (a.data = $.jgrid.parseDate.call(V, n.newfmt, a.data, n.srcfmt)), m = f[a.op](m, o)(l, a.data, n) } catch (e) { } } else void 0 !== V.p.customFilterDef && void 0 !== V.p.customFilterDef[a.op] && $.isFunction(V.p.customFilterDef[a.op].action) && (m = m.user.call(V, a.op, a.field, a.data)); d++ } s && m.orEnd() } catch (e) { alert(e) } }(v); else try { "date" === (o = p[V.p.postData.searchField]).stype && o.srcfmt && o.newfmt && o.srcfmt !== o.newfmt && (V.p.postData.searchString = $.jgrid.parseDate.call(V, o.newfmt, V.p.postData.searchString, o.srcfmt)), f[V.p.postData.searchOper] ? m = f[V.p.postData.searchOper](m)(V.p.postData.searchField, V.p.postData.searchString, p[V.p.postData.searchField]) : void 0 !== V.p.customFilterDef && void 0 !== V.p.customFilterDef[V.p.postData.searchOper] && $.isFunction(V.p.customFilterDef[V.p.postData.searchOper].action) && (m = m.user.call(V, V.p.postData.searchOper, V.p.postData.searchField, V.p.postData.searchString)) } catch (e) { } } if (V.p.treeGrid && "nested" === V.p.treeGridModel && m.orderBy(V.p.treeReader.left_field, "asc", "integer", "", null), V.p.treeGrid && "adjacency" === V.p.treeGridModel && (c = 0, a = null), V.p.grouping) for (u = 0; u < c; u++)m.orderBy(d[u], g.groupOrder[u], s[u].stype, s[u].srcfmt); V.p.multiSort ? $.each(a, function (e) { m.orderBy(this, n[e], p[this].stype, p[this].srcfmt, p[this].sfunc) }) : a && V.p.sortorder && l && ("DESC" === V.p.sortorder.toUpperCase() ? m.orderBy(V.p.sortname, "d", p[a].stype, p[a].srcfmt, p[a].sfunc) : m.orderBy(V.p.sortname, "a", p[a].stype, p[a].srcfmt, p[a].sfunc)); var b = m.select(), j = parseInt(V.p.rowNum, 10), y = b.length, w = parseInt(V.p.page, 10), x = Math.ceil(y / j), v = {}; if ((V.p.search || V.p.resetsearch) && V.p.grouping && V.p.groupingView._locgr) { V.p.groupingView.groups = []; var _, q, I, D = $.jgrid.getMethod("groupingPrepare"); if (V.p.footerrow && V.p.userDataOnFooter) { for (q in V.p.userData) V.p.userData.hasOwnProperty(q) && (V.p.userData[q] = 0); I = !0 } for (_ = 0; _ < y; _++) { if (I) for (q in V.p.userData) V.p.userData.hasOwnProperty(q) && (V.p.userData[q] += parseFloat(b[_][q] || 0)); D.call($(V), b[_], _, j) } } return e ? b : (b = V.p.treeGrid && V.p.search ? $(V).jqGrid("searchTree", b) : b.slice((w - 1) * j, w * j), p = m = null, v[V.p.localReader.total] = x, v[V.p.localReader.page] = w, v[V.p.localReader.records] = y, v[V.p.localReader.root] = b, v[V.p.localReader.userdata] = V.p.userData, b = null, v) } $(V).jqGrid("SortTree", a, V.p.sortorder, p[a].stype || "text", p[a].srcfmt || "") } }, q = function () { V.grid.hDiv.loading = !0, V.p.hiddengrid || $(V).jqGrid("progressBar", { method: "show", loadtype: V.p.loadui, htmlcontent: $.jgrid.getRegional(V, "defaults.loadtext", V.p.loadtext) }) }, I = function () { V.grid.hDiv.loading = !1, $(V).jqGrid("progressBar", { method: "hide", loadtype: V.p.loadui }) }, D = function (e, t, r) { var i = void 0 === (i = $(V).triggerHandler("jqGridBeforeProcessing", [e, t, r])) || "boolean" != typeof i || i; return $.isFunction(V.p.beforeProcessing) && !1 === V.p.beforeProcessing.call(V, e, t, r) && (i = !1), i }, G = function (e, t) { $(V).triggerHandler("jqGridLoadComplete", [e]), t && V.p.loadComplete.call(V, e), $(V).triggerHandler("jqGridAfterLoadComplete", [e]), V.p.datatype = "local", V.p.datastr = null, I() }, k = function (i) { if (!V.grid.hDiv.loading) { var o, a = V.p.scroll && !1 === i, e = {}, t = V.p.prmNames; W = 0, V.p.page <= 0 && (V.p.page = Math.min(1, V.p.lastpage)), null !== t.search && (e[t.search] = V.p.search), null !== t.nd && (e[t.nd] = (new Date).getTime()), null !== t.rows && (e[t.rows] = V.p.rowNum), null !== t.page && (e[t.page] = V.p.page), null !== t.sort && (e[t.sort] = V.p.sortname), null !== t.order && (e[t.order] = V.p.sortorder), null !== V.p.rowTotal && null !== t.totalrows && (e[t.totalrows] = V.p.rowTotal); var r = $.isFunction(V.p.loadComplete), n = r ? V.p.loadComplete : null, l = 0; if (1 < (i = i || 1) ? null !== t.npage ? (e[t.npage] = i, l = i - 1, i = 1) : n = function (e) { V.p.page++, V.grid.hDiv.loading = !1, r && V.p.loadComplete.call(V, e), k(i - 1) } : null !== t.npage && delete V.p.postData[t.npage], V.p.grouping) { $(V).jqGrid("groupingSetup"); for (var s, d = V.p.groupingView, p = [], c = 0; c < d.groupField.length; c++) { var u = d.groupField[c]; $.each(V.p.colModel, function (e, t) { t.name === u && t.index && (u = t.index) }), p.push(u + " " + d.groupOrder[c]) } s = p.join(), "" !== $.trim(e[t.sort]) ? e[t.sort] = s + " ," + e[t.sort] : (e[t.sort] = s, e[t.order] = "") } $.extend(V.p.postData, e); var h = V.p.scroll ? V.rows.length - 1 : 1; if ($.isFunction(V.p.datatype)) V.p.datatype.call(V, V.p.postData, "load_" + V.p.id, h, i, l); else { e = $(V).triggerHandler("jqGridBeforeRequest"); if (!1 !== e && "stop" !== e && (!$.isFunction(V.p.beforeRequest) || !1 !== (e = V.p.beforeRequest.call(V)) && "stop" !== e)) { switch ($.isFunction(V.treeGrid_beforeRequest) && V.treeGrid_beforeRequest.call(V), o = V.p.datatype.toLowerCase()) { case "json": case "jsonp": case "xml": case "script": $.ajax($.extend({ url: V.p.url, type: V.p.mtype, dataType: o, data: $.isFunction(V.p.serializeGridData) ? V.p.serializeGridData.call(V, V.p.postData) : V.p.postData, success: function (e, t, r) { D(e, t, r) ? (("xml" === o ? b : j)(e, h, 1 < i, l), $(V).triggerHandler("jqGridLoadComplete", [e]), n && n.call(V, e), $(V).triggerHandler("jqGridAfterLoadComplete", [e]), a && V.grid.populateVisible(), V.p.treeGrid_bigData ? V.p.loadonce && (V.p.datatype = "local") : (V.p.loadonce || V.p.treeGrid) && (V.p.datatype = "local"), e = null, 1 === i && I(), $.isFunction(V.treeGrid_afterLoadComplete) && V.treeGrid_afterLoadComplete.call(V)) : I() }, error: function (e, t, r) { $(V).triggerHandler("jqGridLoadError", [e, t, r]), $.isFunction(V.p.loadError) && V.p.loadError.call(V, e, t, r), 1 === i && I(), e = null }, beforeSend: function (e, t) { var r = !0, r = $(V).triggerHandler("jqGridLoadBeforeSend", [e, t]); if ($.isFunction(V.p.loadBeforeSend) && (r = V.p.loadBeforeSend.call(V, e, t)), void 0 === r && (r = !0), !1 === r) return !1; q() } }, $.jgrid.ajaxOptions, V.p.ajaxGridOptions)); break; case "xmlstring": if (q(), g = "string" != typeof V.p.datastr ? V.p.datastr : $.parseXML(V.p.datastr), !D(g, 200, null)) return void I(); b(g), G(g, r); break; case "jsonstring": if (q(), g = "string" == typeof V.p.datastr ? $.jgrid.parse(V.p.datastr) : V.p.datastr, !D(g, 200, null)) return void I(); j(g), G(g, r); break; case "local": case "clientside": q(), V.p.datatype = "local", V.p._ald = !0; var g = _(!1); if (!D(g, 200, null)) return void I(); j(g, h, 1 < i, l), $(V).triggerHandler("jqGridLoadComplete", [g]), n && n.call(V, g), $(V).triggerHandler("jqGridAfterLoadComplete", [g]), a && V.grid.populateVisible(), I(), V.p._ald = !1 }V.p._sort = !1 } } } }, ne = function (e) { $("#cb_" + $.jgrid.jqID(V.p.id), V.grid.hDiv)[V.p.useProp ? "prop" : "attr"]("checked", e), (V.p.frozenColumns ? V.p.id + "_frozen" : "") && $("#cb_" + $.jgrid.jqID(V.p.id), V.grid.fhDiv)[V.p.useProp ? "prop" : "attr"]("checked", e) }, S = function (e, l) { function s(e, t) { var r = $(V).triggerHandler("jqGridPaging", [e, t]); return "stop" !== r && ($.isFunction(V.p.onPaging) && (r = V.p.onPaging.call(V, e, t)), "stop" !== r && (V.p.selrow = null, V.p.multiselect && (V.p.preserveSelection || (V.p.selarrrow = []), ne(!1)), V.p.savedRow = [])) } var t, r, i, o, a, n, d, p, c = "<td class='ui-pg-button " + v + "'><span class='ui-separator'></span></td>", u = "", h = "<table class='ui-pg-table ui-common-table ui-paging-pager'><tbody><tr>", g = ""; if (l += "_" + e, t = "pg_" + e, r = e + "_left", i = e + "_center", d = e + "_right", $("#" + $.jgrid.jqID(e)).append("<div id='" + t + "' class='ui-pager-control' role='group'><table " + Q(X, "pagerTable", !1, "ui-pg-table ui-common-table ui-pager-table") + "><tbody><tr><td id='" + r + "' align='left'></td><td id='" + i + "' align='center' style='white-space:pre;'></td><td id='" + d + "' align='right'></td></tr></tbody></table></div>").attr("dir", "ltr"), 0 < V.p.rowList.length) { var f, g = '<td dir="' + m + '">'; for (g += "<select " + Q(X, "pgSelectBox", !1, "ui-pg-selbox") + ' size="1" role="listbox" title="' + ($.jgrid.getRegional(V, "defaults.pgrecs", V.p.pgrecs) || "") + '">', o = 0; o < V.p.rowList.length; o++)1 === (f = V.p.rowList[o].toString().split(":")).length && (f[1] = f[0]), g += '<option role="option" value="' + f[0] + '"' + (K(V.p.rowNum, 0) === K(f[0], 0) ? ' selected="selected"' : "") + ">" + f[1] + "</option>"; g += "</select></td>" } "rtl" === m && (h += g), !0 === V.p.pginput && (u = "<td id='input" + l + "' dir='" + m + "'>" + $.jgrid.template($.jgrid.getRegional(V, "defaults.pgtext", V.p.pgtext) || "", "<input class='ui-pg-input' type='text' size='2' maxlength='7' value='0' role='textbox'/>", "<span id='sp_1_" + $.jgrid.jqID(e) + "'></span>") + "</td>"), !0 === V.p.pgbuttons ? (n = ["first" + l, "prev" + l, "next" + l, "last" + l], d = Q(X, "pgButtonBox", !0, "ui-pg-button"), p = [$.jgrid.getRegional(V, "defaults.pgfirst", V.p.pgfirst) || "", $.jgrid.getRegional(V, "defaults.pgprev", V.p.pgprev) || "", $.jgrid.getRegional(V, "defaults.pgnext", V.p.pgnext) || "", $.jgrid.getRegional(V, "defaults.pglast", V.p.pglast) || ""], "rtl" === m && (n.reverse(), p.reverse()), h += "<td id='" + n[0] + "' class='" + d + "' title='" + p[0] + "'><span " + Q(X, "icon_first", !1, w) + "></span></td>", h += "<td id='" + n[1] + "' class='" + d + "'  title='" + p[1] + "'><span " + Q(X, "icon_prev", !1, w) + "></span></td>", h += "" !== u ? c + u + c : "", h += "<td id='" + n[2] + "' class='" + d + "' title='" + p[2] + "'><span " + Q(X, "icon_next", !1, w) + "></span></td>", h += "<td id='" + n[3] + "' class='" + d + "' title='" + p[3] + "'><span " + Q(X, "icon_end", !1, w) + "></span></td>") : "" !== u && (h += u), "ltr" === m && (h += g), h += "</tr></tbody></table>", e = $.jgrid.jqID(e), t = $.jgrid.jqID(t), !0 === V.p.viewrecords && $("td#" + e + "_" + V.p.recordpos, "#" + t).append("<div dir='" + m + "' style='text-align:" + V.p.recordpos + "' class='ui-paging-info'></div>"), $("td#" + e + "_" + V.p.pagerpos, "#" + t).append(h), p = $("#gbox_" + $.jgrid.jqID(V.p.id)).css("font-size") || "11px", $("#gbox_" + $.jgrid.jqID(V.p.id)).append("<div id='testpg' " + Q(X, "entrieBox", !1, "ui-jqgrid") + " style='font-size:" + p + ";visibility:hidden;' ></div>"), p = $(h).clone().appendTo("#testpg").width(), $("#testpg").remove(), 0 < p && ("" !== u && (p += 50), a = p > $("td#" + e + "_" + V.p.pagerpos, "#" + t).innerWidth(), $("td#" + e + "_" + V.p.pagerpos, "#" + t).width(p)), V.p._nvtd = [], V.p._nvtd[0] = p ? Math.floor((V.p.width - p) / 2) : Math.floor(V.p.width / 3), V.p._nvtd[1] = 0, h = null, $(".ui-pg-selbox", "#" + t).on("change", function () { return s("records", this) && (V.p.page = Math.round(V.p.rowNum * (V.p.page - 1) / this.value - .5) + 1, V.p.rowNum = this.value, V.p.pager && $(".ui-pg-selbox", V.p.pager).val(this.value), V.p.toppager && $(".ui-pg-selbox", V.p.toppager).val(this.value), k()), !1 }), !0 === V.p.pgbuttons && ($(".ui-pg-button", "#" + t).hover(function () { $(this).hasClass(v) ? this.style.cursor = "default" : ($(this).addClass(y), this.style.cursor = "pointer") }, function () { $(this).hasClass(v) || ($(this).removeClass(y), this.style.cursor = "default") }), $("#first" + $.jgrid.jqID(l) + ", #prev" + $.jgrid.jqID(l) + ", #next" + $.jgrid.jqID(l) + ", #last" + $.jgrid.jqID(l)).click(function () { if ($(this).hasClass(v)) return !1; var e = K(V.p.page, 1), t = K(V.p.lastpage, 1), r = !1, i = !0, o = !0, a = !0, n = !0; return 0 === t || 1 === t ? n = a = o = i = !1 : 1 < t && 1 <= e ? 1 === e ? o = i = !1 : e === t && (n = a = !1) : 1 < t && 0 === e && (n = a = !1, e = t - 1), s(this.id.split("_")[0], this) && (this.id === "first" + l && i && (V.p.page = 1, r = !0), this.id === "prev" + l && o && (V.p.page = e - 1, r = !0), this.id === "next" + l && a && (V.p.page = e + 1, r = !0), this.id === "last" + l && n && (V.p.page = t, r = !0), r && k(), $.jgrid.setSelNavIndex(V, this)), !1 })), !0 === V.p.pginput && $("#" + t).on("keypress", "input.ui-pg-input", function (e) { return 13 === (e.charCode || e.keyCode || 0) ? (s("user", this) && ($(this).val(K($(this).val(), 1)), V.p.page = 0 < $(this).val() ? $(this).val() : V.p.page, k()), !1) : this }), a && V.p.responsive && !V.p.forcePgButtons && ($("#" + n[0] + ",#" + n[3] + ",#input" + $.jgrid.jqID(l)).hide(), $(".ui-paging-info", "td#" + e + "_" + V.p.recordpos).hide(), $(".ui-pg-selbox", "td#" + e + "_" + V.p.pagerpos).hide()) }, R = function (e, t, r, i, o) { if (V.p.colModel[t].sortable && !(0 < V.p.savedRow.length)) { if (r || (V.p.lastsort === t && "" !== V.p.sortname ? "asc" === V.p.sortorder ? V.p.sortorder = "desc" : "desc" === V.p.sortorder && (V.p.sortorder = "asc") : V.p.sortorder = V.p.colModel[t].firstsortorder || "asc", V.p.page = 1), V.p.multiSort) !function (e, t, r) { var i = V.p.colModel, o = V.p.frozenColumns ? t : V.grid.headers[e].el, a = ""; $("span.ui-grid-ico-sort", o).addClass(v), $(o).attr({ "aria-selected": "false", "aria-sort": "none" }), t = i[e].index || i[e].name, void 0 === r ? i[e].lso ? "asc" === i[e].lso ? (i[e].lso += "-desc", a = "desc") : "desc" === i[e].lso ? (i[e].lso += "-asc", a = "asc") : "asc-desc" !== i[e].lso && "desc-asc" !== i[e].lso || (i[e].lso = "") : i[e].lso = a = i[e].firstsortorder || "asc" : i[e].lso = a = r, a ? ($("span.s-ico", o).show(), $("span.ui-icon-" + a, o).removeClass(v), $(o).attr({ "aria-selected": "true", "aria-sort": a + "ending" })) : V.p.viewsortcols[0] || $("span.s-ico", o).hide(), -1 === (o = C.indexOf(t)) ? (C.push(t), F.push(a)) : a ? F[o] = a : (F.splice(o, 1), C.splice(o, 1)), V.p.sortorder = "", V.p.sortname = ""; for (var n = 0, l = C.length; n < l; n++)0 < n && (V.p.sortname += ", "), V.p.sortname += C[n], n !== l - 1 && (V.p.sortname += " " + F[n]); V.p.sortorder = F[l - 1] }(t, o, i); else { if (i) { if (V.p.lastsort === t && V.p.sortorder === i && !r) return; V.p.sortorder = i } var r = V.grid.headers[V.p.lastsort] ? V.grid.headers[V.p.lastsort].el : null, a = V.p.frozenColumns ? o : V.grid.headers[t].el, i = "single" === V.p.viewsortcols[1], o = $(r).find("span.ui-grid-ico-sort"); o.addClass(v), i && $(o).css("display", "none"), $(r).attr({ "aria-selected": "false", "aria-sort": "none" }), V.p.frozenColumns && ((o = V.grid.fhDiv.find("span.ui-grid-ico-sort")).addClass(v), i && o.css("display", "none"), V.grid.fhDiv.find("th").attr({ "aria-selected": "false", "aria-sort": "none" })), (o = $(a).find("span.ui-icon-" + V.p.sortorder)).removeClass(v), i && o.css("display", ""), $(a).attr({ "aria-selected": "true", "aria-sort": V.p.sortorder + "ending" }), V.p.viewsortcols[0] || (V.p.lastsort !== t ? (V.p.frozenColumns && V.grid.fhDiv.find("span.s-ico").hide(), $("span.s-ico", r).hide(), $("span.s-ico", a).show()) : "" === V.p.sortname && $("span.s-ico", a).show()), e = e.substring(5 + V.p.id.length + 1), V.p.sortname = V.p.colModel[t].index || e } "stop" === $(V).triggerHandler("jqGridSortCol", [V.p.sortname, t, V.p.sortorder]) || $.isFunction(V.p.onSortCol) && "stop" === V.p.onSortCol.call(V, V.p.sortname, t, V.p.sortorder) ? V.p.lastsort = t : (ne(!1), "local" === V.p.datatype ? V.p.deselectAfterSort && !V.p.preserveSelection && $(V).jqGrid("resetSelection") : (V.p.selrow = null, V.p.multiselect && (V.p.preserveSelection || (V.p.selarrrow = [])), V.p.savedRow = []), V.p.scroll && (a = V.grid.bDiv.scrollLeft, ie.call(V, !0, !1), V.grid.hDiv.scrollLeft = a), V.p.subGrid && "local" === V.p.datatype && $("td.sgexpanded", "#" + $.jgrid.jqID(V.p.id)).each(function () { $(this).trigger("click") }), V.p._sort = !0, k(), V.p.lastsort = t, V.p.sortname !== e && t && (V.p.lastsort = t)) } }, M = function (e) { for (var t = V.grid.headers, r = $.jgrid.getCellIndex(e), i = 0; i < t.length; i++)if (e === t[i].el) { r = i; break } return r }, N = function () { var e, t, r = '{"groupOp":"AND","rules":[], "groups" : [', i = 0; for (e in V.p.colFilters) V.p.colFilters.hasOwnProperty(e) && (t = V.p.colFilters[e], $.isEmptyObject(t) || (0 < i && (r += ","), r += '{"groupOp": "' + t.rule + '", "rules" : [', r += '{"field":"' + e + '",', r += '"op":"' + t.oper1 + '",', t.value1 += "", r += '"data":"' + t.value1.replace(/\\/g, "\\\\").replace(/\"/g, '\\"') + '"}', t.value2 && (r += ',{"field":"' + e + '",', r += '"op":"' + t.oper2 + '",', t.value2 += "", r += '"data":"' + t.value2.replace(/\\/g, "\\\\").replace(/\"/g, '\\"') + '"}'), r += "]}", i++)); return r += "]}" }, O = function (b, e, t) { var r = $(g.hDiv).height(); $(".ui-search-toolbar", g.hDiv)[0] && !isNaN($(".ui-search-toolbar", g.hDiv).height()) && (r -= $(".ui-search-toolbar", g.hDiv).height()), $(g.cDiv).is(":hidden") || (r += $(g.cDiv).outerHeight()), V.p.toolbar[1] && "bottom" !== V.p.toolbar[2] && null !== $(g.uDiv) && (r += $(g.uDiv).outerHeight()), V.p.toppager && (r += $("#" + $.jgrid.jqID(V.p.id) + "_toppager").outerHeight()), e = parseInt(e, 10), t = r; var i, o, a, n, l, s, d = "", p = V.p.colModel[b], j = $.extend({ sorting: !0, columns: !0, filtering: !0, seraching: !0, grouping: !0, freeze: !0 }, p.coloptions), c = $.jgrid.getRegional(V, "colmenu"), r = V.p.colNames[b], u = [], h = $.trim(p.name); for (n in u.push(d), p.sortable && j.sorting && (d = '<li class="ui-menu-item" role="presentation"><a class="g-menu-item" tabindex="0" role="menuitem" data-value="sortasc"><table class="ui-common-table"><tr><td class="menu_icon"><span class="' + w + " " + x.icon_sort_asc + '"></span></td><td class="menu_text">' + c.sortasc + "</td></tr></table></a></li>", d += '<li class="ui-menu-item" role="presentation"><a class="g-menu-item" tabindex="0" role="menuitem" data-value="sortdesc"><table class="ui-common-table"><tr><td class="menu_icon"><span class="' + w + " " + x.icon_sort_desc + '"></span></td><td class="menu_text">' + c.sortdesc + "</td></tr></table></a></li>", u.push(d)), j.columns && (d = '<li class="ui-menu-item divider" role="separator"></li>', d += '<li class="ui-menu-item" role="presentation"><a class="g-menu-item" tabindex="0" role="menuitem" data-value="columns"><table class="ui-common-table"><tr><td class="menu_icon"><span class="' + w + " " + x.icon_columns + '"></span></td><td class="menu_text">' + c.columns + "</td></tr></table></a></li>", u.push(d)), j.filtering && (d = '<li class="ui-menu-item divider" role="separator"></li>', d += '<li class="ui-menu-item" role="presentation"><a class="g-menu-item" tabindex="0" role="menuitem" data-value="filtering"><table class="ui-common-table"><tr><td class="menu_icon"><span class="' + w + " " + x.icon_filter + '"></span></td><td class="menu_text">' + c.filter + " " + r + "</td></tr></table></a></li>", u.push(d)), j.grouping && (o = $.inArray(p.name, V.p.groupingView.groupField), d = '<li class="ui-menu-item divider" role="separator"></li>', d += '<li class="ui-menu-item" role="presentation"><a class="g-menu-item" tabindex="0" role="menuitem" data-value="grouping"><table class="ui-common-table"><tr><td class="menu_icon"><span class="' + w + " " + x.icon_group + '"></span></td><td class="menu_text">' + (-1 !== o ? c.ungrouping : c.grouping + " " + r) + "</td></tr></table></a></li>", u.push(d)), j.freeze && (V.p.subGrid || V.p.treeGrid || V.p.cellEdit || (a = !p.frozen || !V.p.frozenColumns, d = '<li class="ui-menu-item divider" role="separator"></li>', d += '<li class="ui-menu-item" role="presentation"><a class="g-menu-item" tabindex="0" role="menuitem" data-value="freeze"><table class="ui-common-table"><tr><td class="menu_icon"><span class="' + w + " " + x.icon_freeze + '"></span></td><td class="menu_text">' + (a ? c.freeze + " " + r : c.unfreeze) + "</td></tr></table></a></li>", u.push(d))), V.p.colMenuCustom) V.p.colMenuCustom.hasOwnProperty(n) && (s = (l = V.p.colMenuCustom[n]).exclude.split(","), s = $.map(s, function (e) { return $.trim(e) }), (l.colname === h || "_all_" === l.colname && -1 === $.inArray(h, s)) && (i = '<li class="ui-menu-item divider" role="separator"></li>', d = '<li class="ui-menu-item" role="presentation"><a class="g-menu-item" tabindex="0" role="menuitem" data-value="' + l.id + '"><table class="ui-common-table"><tr><td class="menu_icon"><span class="' + w + " " + l.icon + '"></span></td><td class="menu_text">' + l.title + "</td></tr></table></a></li>", "last" === l.position ? (u.push(i), u.push(d)) : "first" === l.position && (u.unshift(i), u.unshift(d)))); u.unshift('<ul id="column_menu" role="menu" tabindex="0">'), u.push("</ul>"), $("#gbox_" + V.p.id).append(u.join("")), $("#column_menu").addClass("ui-search-menu modal-content column-menu jqgrid-column-menu ui-menu " + x.menu_widget).css({ left: e, top: t }), "ltr" === V.p.direction && (t = $("#column_menu").width() + 26, $("#column_menu").css("left", e - t + "px")), $("#column_menu > li > a").hover(function () { var e, t, r, i, o, a, n, l, s, d, p, c, u, h, g, f, m, v; $("#col_menu").remove(), $("#search_menu").remove(), "columns" === $(this).attr("data-value") && (n = $(this).parent().width() + 8, $(this).parent().position().top, function (e, t, r) { var i, o = V.p.colModel, a = o.length, n = [], l = !0, s = [], d = $.jgrid.getRegional(V, "colmenu"), p = '<ul id="col_menu" class="ui-search-menu  ui-col-menu modal-content" role="menu" tabindex="0" style="left:' + e + 'px;">'; for (r.columns_selectAll && (p += '<li class="ui-menu-item disabled" role="presentation" draggable="false"><a class="g-menu-item" tabindex="0" role="menuitem" ><table class="ui-common-table" ><tr><td class="menu_icon" title="' + d.reorder + '"><span class="' + w + " " + x.icon_move + ' notclick" style="visibility:hidden"></span></td><td class="menu_icon"><input id="chk_all" class="' + x.input_checkbox + '" type="checkbox" name="check_all"></td><td class="menu_text">Check/Uncheck</td></tr></table></a></li>'), i = 0; i < a; i++) { var c, u = o[i].hidden ? "" : "checked", h = o[i].name, g = V.p.colNames[i]; p += "<li " + (c = "cb" === h || "subgrid" === h || "rn" === h || o[i].hidedlg ? "style='display:none'" : "") + ' class="ui-menu-item" role="presentation" draggable="true"><a class="g-menu-item" tabindex="0" role="menuitem" ><table class="ui-common-table" ><tr><td class="menu_icon" title="' + d.reorder + '"><span class="' + w + " " + x.icon_move + ' notclick"></span></td><td class="menu_icon"><input class="' + x.input_checkbox + ' chk_selected" type="checkbox" name="' + h + '" ' + u + '></td><td class="menu_text">' + g + "</td></tr></table></a></li>", n.push(i), c || s.push(h), l && !u && (l = !1) } p += "</ul>", $(t).append(p), $("#col_menu").addClass("ui-menu " + x.menu_widget), $("#chk_all", "#col_menu").prop("checked", l), $.jgrid.isElementInViewport($("#col_menu")[0]) || $("#col_menu").css("left", -parseInt($("#column_menu").innerWidth(), 10) + "px"), $.fn.html5sortable() && $("#col_menu").html5sortable({ handle: "span", items: ":not(.disabled)", forcePlaceholderSize: !0 }).on("sortupdate", function (e, t) { for (n.splice(t.startindex, 1), n.splice(t.endindex, 0, t.startindex), $(V).jqGrid("destroyFrozenColumns"), $(V).jqGrid("remapColumns", n, !0), $(V).triggerHandler("jqGridColMenuColumnDone", [n, null, null]), $.isFunction(V.p.colMenuColumnDone) && V.p.colMenuColumnDone.call(V, n, null, null), $(V).jqGrid("setFrozenColumns"), i = 0; i < a; i++)n[i] = i }), $("#col_menu > li > a").on("click", function (e) { var t; $(e.target).hasClass("notclick") || ($(e.target).is(":input") ? t = $(e.target).is(":checked") : (t = !$("input", this).is(":checked"), $("input", this).prop("checked", t)), "check_all" === (e = $("input", this).attr("name")) ? t ? ($("input", "#col_menu").prop("checked", !0), $(V).jqGrid("showCol", s)) : ($("input", "#col_menu").prop("checked", !1), $(V).jqGrid("hideCol", s)) : ($(V).triggerHandler("jqGridColMenuColumnDone", [n, e, t]), $.isFunction(V.p.colMenuColumnDone) && V.p.colMenuColumnDone.call(V, n, e, t), t ? ($(V).jqGrid("showCol", e), $(this).parent().attr("draggable", "true")) : ($(V).jqGrid("hideCol", e), $(this).parent().attr("draggable", "false")), r.columns_selectAll && $("#chk_all", "#col_menu").prop("checked", $(".chk_selected:checked", "#col_menu").length === $(".chk_selected", "#col_menu").length))) }).hover(function () { $(this).addClass(y) }, function () { $(this).removeClass(y) }) }(n, $(this).parent(), j)), "filtering" === $(this).attr("data-value") && (n = $(this).parent().width() + 8, $(this).parent().position().top, e = b, t = n, r = $(this).parent(), d = V.p.colModel[e], f = g = h = u = c = p = "", m = $.jgrid.getRegional(V, "search"), v = $.jgrid.styleUI[V.p.styleUI || "jQueryUI"].common, d && ((s = !(!V.p.colFilters || !V.p.colFilters[d.name]) && V.p.colFilters[d.name]) && !$.isEmptyObject(s) && (p = s.oper1, c = s.value1, u = s.rule, h = s.oper2, g = s.value2), d.searchoptions || (d.searchoptions = {}), i = d.searchoptions.sopt || ("text" === d.sorttype ? ["eq", "ne", "bw", "bn", "ew", "en", "cn", "nc", "nu", "nn", "in", "ni"] : ["eq", "ne", "lt", "le", "gt", "ge", "nu", "nn", "in", "ni"]), o = d.searchoptions.groupOps || m.groupOps, n = $("<form></form>"), l = "<div>" + $.jgrid.getRegional(V, "colmenu.searchTitle") + "</div>", l += '<div><select size="1" id="oper1" class="' + x.filter_select + '">', $.each(m.odata, function (e, t) { a = t.oper === p ? 'selected="selected"' : "", -1 !== $.inArray(t.oper, i) && (f += '<option value="' + t.oper + '" ' + a + ">" + t.text + "</option>") }), l += f, l += "</select></div>", n.append(l), e = "", d.searchoptions.defaultValue && (e = $.isFunction(d.searchoptions.defaultValue) ? d.searchoptions.defaultValue.call(V) : d.searchoptions.defaultValue), c && (e = c), s = $.extend(d.searchoptions, { name: d.index || d.name, id: "sval1_" + V.p.idPrefix + d.name, oper: "search" }), c = $.jgrid.createEl.call(V, d.stype, s, e, !1, $.extend({}, $.jgrid.ajaxOptions, V.p.ajaxSelectOptions || {})), $(c).addClass(x.filter_input), l = $("<div></div>").append(c), n.append(l), l = '<div><select size="1" id="operand" class="' + x.filter_select + '">', $.each(o, function (e, t) { a = t.op === u ? 'selected="selected"' : "", l += "<option value='" + t.op + "' " + a + ">" + t.text + "</option>" }), l += "</select></div>", n.append(l), f = "", $.each(m.odata, function (e, t) { a = t.oper === h ? 'selected="selected"' : "", -1 !== $.inArray(t.oper, i) && (f += '<option value="' + t.oper + '" ' + a + ">" + t.text + "</option>") }), l = '<div><select size="1" id="oper2" class="' + x.filter_select + '">' + f + "</select></div>", n.append(l), e = g || "", s = $.extend(d.searchoptions, { name: d.index || d.name, id: "sval2_" + V.p.idPrefix + d.name, oper: "search" }), c = $.jgrid.createEl.call(V, d.stype, s, e, !1, $.extend({}, $.jgrid.ajaxOptions, V.p.ajaxSelectOptions || {})), $(c).addClass(x.filter_input), l = $("<div></div>").append(c), n.append(l), l = "<div>", l += "<div class='search_buttons'><a tabindex='0' id='bs_reset' class='fm-button " + v.button + " ui-reset'>" + m.Reset + "</a></div>", l += "<div class='search_buttons'><a tabindex='0' id='bs_search' class='fm-button " + v.button + " ui-search'>" + m.Find + "</a></div>", l += "</div>", n.append(l), n = $('<li class="ui-menu-item" role="presentation"></li>').append(n), n = $('<ul id="search_menu" class="ui-search-menu modal-content" role="menu" tabindex="0" style="left:' + t + 'px;"></ul>').append(n), $(r).append(n), $("#search_menu").addClass("ui-menu " + x.menu_widget), $.jgrid.isElementInViewport($("#search_menu")[0]) || $("#search_menu").css("left", -parseInt($("#column_menu").innerWidth(), 10) + "px"), $("#bs_reset, #bs_search", "#search_menu").hover(function () { $(this).addClass(y) }, function () { $(this).removeClass(y) }), $("#bs_reset", n).on("click", function (e) { V.p.colFilters[d.name] = {}, V.p.postData.filters = N(), V.p.search = !1, $(V).trigger("reloadGrid"), $("#column_menu").remove() }), $("#bs_search", n).on("click", function (e) { V.p.colFilters[d.name] = { oper1: $("#oper1", "#search_menu").val(), value1: $("#sval1_" + V.p.idPrefix + d.name, "#search_menu").val(), rule: $("#operand", "#search_menu").val(), oper2: $("#oper2", "#search_menu").val(), value2: $("#sval2_" + V.p.idPrefix + d.name, "#search_menu").val() }, V.p.postData.filters = N(), V.p.search = !0, $(V).trigger("reloadGrid"), $("#column_menu").remove() }))), $(this).addClass(y) }, function () { $(this).removeClass(y) }).click(function () { var e, t, r = $(this).attr("data-value"), i = V.grid.headers[b].el; "sortasc" === r ? R("jqgh_" + V.p.id + "_" + p.name, b, !0, "asc", i) : "sortdesc" === r ? R("jqgh_" + V.p.id + "_" + p.name, b, !0, "desc", i) : "grouping" === r ? (e = b, t = o, i = V.p.colModel[e], e = V.p.groupingView, -1 !== t ? e.groupField.splice(t, 1) : e.groupField.push(i.name), $(V).jqGrid("groupingGroupBy", e.groupField), V.p.frozenColumns && ($(V).jqGrid("destroyFrozenColumns"), $(V).jqGrid("setFrozenColumns"))) : "freeze" === r && function (e, t) { for (var r = [], i = V.p.colModel.length, o = -1, a = V.p.colModel, n = 0; n < i; n++)a[n].frozen && (o = n), r.push(n); r.splice(e, 1), r.splice(o + (t ? 1 : 0), 0, e), a[e].frozen = t, $(V).jqGrid("destroyFrozenColumns"), $(V).jqGrid("remapColumns", r, !0), $(V).jqGrid("setFrozenColumns") }(b, a), -1 === r.indexOf("sort") && "grouping" !== r && "freeze" !== r || $(this).remove(), V.p.colMenuCustom.hasOwnProperty(r) && (r = V.p.colMenuCustom[r], $.isFunction(r.funcname) && (r.funcname.call(V, h), r.closeOnRun && $(this).remove())) }), parseFloat($("#column_menu").css("left")) < 0 && $("#column_menu").css("left", $(V).css("left")) }; for ((V.p.colMenu || V.p.menubar) && $("body").on("click", function (e) { if (!$(e.target).closest("#column_menu").length) try { $("#column_menu").remove() } catch (e) { } if (!$(e.target).closest(".ui-jqgrid-menubar").length) try { $("#" + V.p.id + "_menubar").hide() } catch (e) { } }), this.p.id = this.id, -1 === $.inArray(V.p.multikey, ["shiftKey", "altKey", "ctrlKey"]) && (V.p.multikey = !1), V.p.keyName = !1, r = 0; r < V.p.colModel.length; r++)s = "string" == typeof V.p.colModel[r].template ? null != $.jgrid.cmTemplate && "object" == typeof $.jgrid.cmTemplate[V.p.colModel[r].template] ? $.jgrid.cmTemplate[V.p.colModel[r].template] : {} : V.p.colModel[r].template, V.p.colModel[r] = $.extend(!0, {}, V.p.cmTemplate, s || {}, V.p.colModel[r]), !1 === V.p.keyName && !0 === V.p.colModel[r].key && (V.p.keyName = V.p.colModel[r].name, V.p.keyIndex = r); V.p.sortorder = V.p.sortorder.toLowerCase(), $.jgrid.cell_width = $.jgrid.cellWidth(); var T = $("<table style='visibility:hidden'><tr class='jqgrow'><td>1</td></tr></table)").addClass(Q(X, "rowTable", !0, "ui-jqgrid-btable ui-common-table")); if ($(l).append(T), V.p.cellLayout = parseInt($("td", T).css("padding-left"), 10) + parseInt($("td", T).css("padding-right"), 10) + 1, V.p.cellLayout <= 0 && (V.p.cellLayout = 5), $(T).remove(), !null === V.p.grouping && (V.p.scroll = !1, V.p.rownumbers = !1, V.p.treeGrid = !1, V.p.gridview = !0), !0 === this.p.treeGrid) { try { $(this).jqGrid("setTreeGrid") } catch (e) { } "local" !== V.p.datatype ? V.p.localReader = { id: "_id_" } : !1 !== V.p.keyName && (V.p.localReader = { id: V.p.keyName }) } if (this.p.subGrid) try { $(V).jqGrid("setSubGrid") } catch (e) { } this.p.multiselect && (this.p.colNames.unshift("<input role='checkbox' id='cb_" + this.p.id + "' class='cbox' type='checkbox'/>"), this.p.colModel.unshift({ name: "cb", width: $.jgrid.cell_width ? V.p.multiselectWidth + V.p.cellLayout : V.p.multiselectWidth, sortable: !1, resizable: !1, hidedlg: !0, search: !1, align: "center", fixed: !0, frozen: !0, classes: "jqgrid-multibox" })), this.p.rownumbers && (this.p.colNames.unshift(""), this.p.colModel.unshift({ name: "rn", width: V.p.rownumWidth, sortable: !1, resizable: !1, hidedlg: !0, search: !1, align: "center", fixed: !0, frozen: !0 })), V.p.xmlReader = $.extend(!0, { root: "rows", row: "row", page: "rows>page", total: "rows>total", records: "rows>records", repeatitems: !0, cell: "cell", id: "[id]", userdata: "userdata", subgrid: { root: "rows", row: "row", repeatitems: !0, cell: "cell" } }, V.p.xmlReader), V.p.jsonReader = $.extend(!0, { root: "rows", page: "page", total: "total", records: "records", repeatitems: !0, cell: "cell", id: "id", userdata: "userdata", subgrid: { root: "rows", repeatitems: !0, cell: "cell" } }, V.p.jsonReader), V.p.localReader = $.extend(!0, { root: "rows", page: "page", total: "total", records: "records", repeatitems: !1, cell: "cell", id: "id", userdata: "userdata", subgrid: { root: "rows", repeatitems: !0, cell: "cell" } }, V.p.localReader), V.p.scroll && (V.p.pgbuttons = !1, V.p.pginput = !1, V.p.rowList = []), V.p.data.length && (f(), oe()); var A, P, E, B, H, z, U, L, le = "<thead><tr class='ui-jqgrid-labels' role='row'>", se = "", de = "", pe = ""; if (!0 === V.p.shrinkToFit && !0 === V.p.forceFit) for (r = V.p.colModel.length - 1; 0 <= r; r--)if (!V.p.colModel[r].hidden) { V.p.colModel[r].resizable = !1; break } if ("horizontal" === V.p.viewsortcols[1] ? (de = " ui-i-asc", pe = " ui-i-desc") : "single" === V.p.viewsortcols[1] && (de = " ui-single-sort-asc", pe = " ui-single-sort-desc", se = " style='display:none'", V.p.viewsortcols[0] = !1), A = o ? "class='ui-th-div-ie'" : "", z = "<span class='s-ico' style='display:none'>", z += "<span sort='asc'  class='ui-grid-ico-sort ui-icon-asc" + de + " ui-sort-" + m + " " + v + " " + w + " " + Q(X, "icon_asc", !0) + "'" + se + "></span>", z += "<span sort='desc' class='ui-grid-ico-sort ui-icon-desc" + pe + " ui-sort-" + m + " " + v + " " + w + " " + Q(X, "icon_desc", !0) + "'" + se + "></span></span>", V.p.multiSort && V.p.sortname) for (C = V.p.sortname.split(","), r = 0; r < C.length; r++)a = $.trim(C[r]).split(" "), C[r] = $.trim(a[0]), F[r] = a[1] ? $.trim(a[1]) : V.p.sortorder || "asc"; for (r = 0; r < this.p.colNames.length; r++) { var ce, ue = V.p.headertitles ? ' title="' + (V.p.colModel[r].tooltip || $.jgrid.stripHtml(V.p.colNames[r])) + '"' : ""; (ce = V.p.colModel[r]).hasOwnProperty("colmenu") || (ce.colmenu = "rn" !== ce.name && "cb" !== ce.name && "subgrid" !== ce.name), le += "<th id='" + V.p.id + "_" + ce.name + "' role='columnheader' " + Q(X, "headerBox", !1, "ui-th-column ui-th-" + m + ("cb" === ce.name ? " jqgrid-multibox" : "")) + " " + ue + ">", ue = ce.index || ce.name, le += "<div class='ui-th-div' id='jqgh_" + V.p.id + "_" + ce.name + "' " + A + ">" + V.p.colNames[r], ce.width ? ce.width = parseInt(ce.width, 10) : ce.width = 150, "boolean" != typeof ce.title && (ce.title = !0), ce.lso = "", ue === V.p.sortname && (V.p.lastsort = r), V.p.multiSort && -1 !== (a = $.inArray(ue, C)) && (ce.lso = F[a]), le += z, V.p.colMenu && ce.colmenu && (le += "<a class='" + ("ltr" === V.p.direction ? "colmenu" : "colmenu-rtl") + "'><span class='colmenuspan " + w + " " + x.icon_menu + "'></span></a>"), le += "</div></th>" } le += "</tr></thead>", ce = z = null, $(this).append(le), $("thead tr:first th", this).hover(function () { $(this).addClass(y) }, function () { $(this).removeClass(y) }), this.p.multiselect && (U = [], $("#cb_" + $.jgrid.jqID(V.p.id), this).on("click", function () { V.p.preserveSelection || (V.p.selarrrow = []); var t = !0 === V.p.frozenColumns ? V.p.id + "_frozen" : ""; this.checked ? ($(V.rows).each(function (e) { 0 < e && ($(this).hasClass("ui-subgrid") || $(this).hasClass("jqgroup") || $(this).hasClass(v) || $(this).hasClass("jqfoot") || ($("#jqg_" + $.jgrid.jqID(V.p.id) + "_" + $.jgrid.jqID(this.id))[V.p.useProp ? "prop" : "attr"]("checked", !0), $(this).addClass(Y).attr("aria-selected", "true"), V.p.preserveSelection && -1 !== V.p.selarrrow.indexOf(this.id) || V.p.selarrrow.push(this.id), V.p.selrow = this.id, t && ($("#jqg_" + $.jgrid.jqID(V.p.id) + "_" + $.jgrid.jqID(this.id), V.grid.fbDiv)[V.p.useProp ? "prop" : "attr"]("checked", !0), $("#" + $.jgrid.jqID(this.id), V.grid.fbDiv).addClass(Y)))) }), L = !0, U = []) : ($(V.rows).each(function (e) { 0 < e && ($(this).hasClass("ui-subgrid") || $(this).hasClass("jqgroup") || $(this).hasClass(v) || $(this).hasClass("jqfoot") || ($("#jqg_" + $.jgrid.jqID(V.p.id) + "_" + $.jgrid.jqID(this.id))[V.p.useProp ? "prop" : "attr"]("checked", !1), $(this).removeClass(Y).attr("aria-selected", "false"), U.push(this.id), !V.p.preserveSelection || -1 < (e = V.p.selarrrow.indexOf(this.id)) && V.p.selarrrow.splice(e, 1), t && ($("#jqg_" + $.jgrid.jqID(V.p.id) + "_" + $.jgrid.jqID(this.id), V.grid.fbDiv)[V.p.useProp ? "prop" : "attr"]("checked", !1), $("#" + $.jgrid.jqID(this.id), V.grid.fbDiv).removeClass(Y)))) }), V.p.selrow = null, L = !1), $(V).triggerHandler("jqGridSelectAll", [L ? V.p.selarrrow : U, L]), $.isFunction(V.p.onSelectAll) && V.p.onSelectAll.call(V, L ? V.p.selarrrow : U, L) })), !0 === V.p.autowidth && (Me = $(l).parent().width(), ce = $(window).width(), V.p.width = 3 < ce - Me ? Me : ce); var he, ge, fe, me, $e, ve, be, je, ye, we, xe, _e = "", qe = "", Ie = -1 === V.p.styleUI.search("Bootstrap") || isNaN(V.p.height) ? 0 : 2; ve = 0, be = $.jgrid.cell_width ? 0 : K(V.p.cellLayout, 0), je = 0, ye = K(V.p.scrollOffset, 0), we = !1, xe = 0, $.each(V.p.colModel, function () { var e; void 0 === this.hidden && (this.hidden = !1), V.p.grouping && V.p.autowidth && (0 <= (e = $.inArray(this.name, V.p.groupingView.groupField)) && V.p.groupingView.groupColumnShow.length > e && (this.hidden = !V.p.groupingView.groupColumnShow[e])), this.widthOrg = ge = K(this.width, 0), !1 === this.hidden && (ve += ge + be, this.fixed ? xe += ge + be : je++) }), isNaN(V.p.width) && (V.p.width = ve + (!1 !== V.p.shrinkToFit || isNaN(V.p.height) ? 0 : ye)), g.width = parseInt(V.p.width, 10), V.p.tblwidth = ve, !1 === V.p.shrinkToFit && !0 === V.p.forceFit && (V.p.forceFit = !1), !0 === V.p.shrinkToFit && 0 < je && (fe = g.width - be * je - xe, isNaN(V.p.height) || (fe -= ye, we = !0), ve = 0, $.each(V.p.colModel, function (e) { !1 !== this.hidden || this.fixed || (ge = Math.round(fe * this.width / (V.p.tblwidth - be * je - xe)), this.width = ge, ve += ge, he = e) }), $e = (me = 0) === Ie ? -1 : 0, we ? g.width - xe - (ve + be * je) !== ye && (me = g.width - xe - (ve + be * je) - ye) : we || 0 === Math.abs(g.width - xe - (ve + be * je)) || (me = g.width - xe - (ve + be * je) - Ie), V.p.colModel[he].width += me + $e, V.p.tblwidth = ve + me + be * je + xe, V.p.tblwidth > V.p.width && (V.p.colModel[he].width -= V.p.tblwidth - parseInt(V.p.width, 10), V.p.tblwidth = V.p.width)), T = -1 !== V.p.styleUI.search("Bootstrap"), $(l).css("width", g.width + "px").append("<div class='ui-jqgrid-resize-mark' id='rs_m" + V.p.id + "'>&#160;</div>"), V.p.scrollPopUp && $(l).append("<div " + Q(X, "scrollBox", !1, "loading ui-scroll-popup") + " id='scroll_g" + V.p.id + "'></div>"), $(n).css("width", g.width + "px"), le = $("thead:first", V).get(0), V.p.footerrow && (_e += "<table role='presentation' style='width:" + V.p.tblwidth + "px' " + Q(X, "footerTable", !1, "ui-jqgrid-ftable ui-common-table") + "><tbody><tr role='row' " + Q(X, "footerBox", !1, "footrow footrow-" + m) + ">"), V.p.headerrow && (qe += "<table role='presentation' style='width:" + V.p.tblwidth + "px' " + Q(X, "headerRowTable", !1, "ui-jqgrid-hrtable ui-common-table") + "><tbody><tr role='row' " + Q(X, "headerRowBox", !1, "hrheadrow hrheadrow-" + m) + ">"); var De = $("tr:first", le), Ce = "<tr class='jqgfirstrow' role='row'>", Fe = 0; if (V.p.disableClick = !1, $("th", De).each(function (e) { ce = V.p.colModel[e], P = ce.width, void 0 === ce.resizable && (ce.resizable = !0), ce.resizable ? (E = document.createElement("span"), $(E).html("&#160;").addClass("ui-jqgrid-resize ui-jqgrid-resize-" + m).css("cursor", "col-resize"), $(this).addClass(V.p.resizeclass)) : E = "", $(this).css("width", P + "px").prepend(E), E = null; var t = ""; ce.hidden && ($(this).css("display", "none"), t = "display:none;"), Ce += "<td role='gridcell' style='height:0px;width:" + P + "px;" + t + "'></td>", g.headers[e] = { width: P, el: this }, "boolean" != typeof (se = ce.sortable) && (ce.sortable = !0, se = !0); t = ce.name; "cb" !== t && "subgrid" !== t && "rn" !== t && V.p.viewsortcols[2] && $(">div", this).addClass("ui-jqgrid-sortable"), se && (V.p.multiSort ? V.p.viewsortcols[0] ? ($("div span.s-ico", this).show(), ce.lso && $("div span.ui-icon-" + ce.lso, this).removeClass(v).css("display", "")) : ce.lso && ($("div span.s-ico", this).show(), $("div span.ui-icon-" + ce.lso, this).removeClass(v).css("display", "")) : V.p.viewsortcols[0] ? ($("div span.s-ico", this).show(), e === V.p.lastsort && $("div span.ui-icon-" + V.p.sortorder, this).removeClass(v).css("display", "")) : e === V.p.lastsort && "" !== V.p.sortname && ($("div span.s-ico", this).show(), $("div span.ui-icon-" + V.p.sortorder, this).removeClass(v).css("display", ""))), V.p.footerrow && (_e += "<td role='gridcell' " + p(e, 0, "", null, "", !1) + ">&#160;</td>"), V.p.headerrow && (qe += "<td role='gridcell' " + p(e, 0, "", null, "", !1) + ">&#160;</td>") }).mousedown(function (e) { if (1 === $(e.target).closest("th>span.ui-jqgrid-resize").length) { var t, r = M(this); if (e.preventDefault(), Fe++, setTimeout(function () { Fe = 0 }, 400), 2 !== Fe) return !0 === V.p.forceFit && (V.p.nv = function (e) { for (var t = e, r = e, i = e + 1; i < V.p.colModel.length; i++)if (!0 !== V.p.colModel[i].hidden) { r = i; break } return r - t }(r)), g.dragStart(r, e, function (e) { e = $(V.grid.headers[e].el), e = [e.position().left + e.outerWidth()]; return "rtl" === V.p.direction && (e[0] = V.p.width - e[0]), e[0] -= V.grid.bDiv.scrollLeft, e.push($(V.grid.hDiv).position().top), e.push($(V.grid.bDiv).offset().top - $(V.grid.hDiv).offset().top + $(V.grid.bDiv).height()), e }(r)), !1; try { !0 === V.p.colModel[r].autosize && (t = $(V).jqGrid("getCol", r, !1, "maxwidth"), $(V).jqGrid("resizeColumn", r, t + (T ? V.p.cellLayout : 0)).jqGrid("refreshGroupHeaders")) } catch (e) { } finally { Fe = 0 } } }).click(function (e) { if (V.p.disableClick) return V.p.disableClick = !1; var t, r, i = "th>div.ui-jqgrid-sortable"; V.p.viewsortcols[2] || (i = "th>div>span>span.ui-grid-ico-sort"); var o, a, n = $(e.target).closest(i); if (1 === n.length) { if (V.p.frozenColumns ? (a = $(this)[0].id.substring(V.p.id.length + 1), $(V.p.colModel).each(function (e) { if (this.name === a) return o = e, !1 })) : o = M(this), $(e.target).hasClass("colmenuspan")) { if (null != $("#column_menu")[0] && $("#column_menu").remove(), void 0 === o) return; i = $("#gbox_" + V.p.id).offset(), i = $(this).offset().left - i.left; return "ltr" === V.p.direction && (i += $(this).outerWidth()), O(o, i, 0), !0 === V.p.menubar && $("#" + V.p.id + "_menubar").hide(), void e.stopPropagation() } return V.p.viewsortcols[2] || (t = !0, r = n.attr("sort")), null != o && R($("div", this)[0].id, o, t, r, this), void 0 !== V.p.selHeadInd && $(g.headers[V.p.selHeadInd].el).attr("tabindex", "-1"), V.p.selHeadInd = o, $(this).attr("tabindex", "0"), !1 } }), ce = null, V.p.sortable && $.fn.sortable) try { $(V).jqGrid("sortableColumns", De) } catch (e) { } V.p.footerrow && (_e += "</tr></tbody></table>"), V.p.headerrow && (qe += "</tr></tbody></table>"), Ce += "</tr>", Me = document.createElement("tbody"), this.appendChild(Me), $(this).addClass(Q(X, "rowTable", !0, "ui-jqgrid-btable ui-common-table")).append(Ce), V.p.altRows && $(this).addClass(Q(X, "stripedTable", !0, "")), Ce = null; var Ge, ke, Se, n = $("<table " + Q(X, "headerTable", !1, "ui-jqgrid-htable ui-common-table") + " style='width:" + V.p.tblwidth + "px' role='presentation' aria-labelledby='gbox_" + this.id + "'></table>").append(le), Re = !(!V.p.caption || !0 !== V.p.hiddengrid), Me = $("<div class='ui-jqgrid-hbox" + ("rtl" === m ? "-rtl" : "") + "'></div>"), le = null; g.hDiv = document.createElement("div"), g.hDiv.style.width = g.width - Ie + "px", g.hDiv.className = Q(X, "headerDiv", !0, "ui-jqgrid-hdiv"), $(g.hDiv).append(Me), $(Me).append(n), Re && $(g.hDiv).hide(), V.p.pager && ("string" == typeof V.p.pager ? "#" === V.p.pager.substr(0, 1) && (V.p.pager = V.p.pager.substring(1)) : V.p.pager = $(V.p.pager).attr("id"), $("#" + $.jgrid.jqID(V.p.pager)).css({ width: g.width - Ie + "px" }).addClass(Q(X, "pagerBox", !0, "ui-jqgrid-pager")).appendTo(l), Re && $("#" + $.jgrid.jqID(V.p.pager)).hide(), S(V.p.pager, ""), V.p.pager = "#" + $.jgrid.jqID(V.p.pager)), !1 === V.p.cellEdit && !0 === V.p.hoverrows && $(V).on({ mouseover: function (e) { H = $(e.target).closest("tr.jqgrow"), "ui-subgrid" !== $(H).attr("class") && $(H).addClass(y) }, mouseout: function (e) { H = $(e.target).closest("tr.jqgrow"), $(H).removeClass(y) } }), $(V).before(g.hDiv).on({ click: function (e) { if (B = e.target, H = $(B, V.rows).closest("tr.jqgrow"), 0 === $(H).length || -1 < H[0].className.indexOf(v) || ($(B, V).closest("table.ui-jqgrid-btable").attr("id") || "").replace("_frozen", "") !== V.id) return this; var t = $(B).filter(":enabled").hasClass("cbox"), r = !1 !== (r = $(V).triggerHandler("jqGridBeforeSelectRow", [H[0].id, e])) && "stop" !== r; if ($.isFunction(V.p.beforeSelectRow) && (!1 !== (a = V.p.beforeSelectRow.call(V, H[0].id, e)) && "stop" !== a || (r = !1)), "A" !== B.tagName && ("INPUT" !== B.tagName && "TEXTAREA" !== B.tagName && "OPTION" !== B.tagName && "SELECT" !== B.tagName || t)) if (Ge = H[0].id, 0 < (B = $(B).closest("tr.jqgrow>td")).length && (ke = $.jgrid.getCellIndex(B)), !0 !== V.p.cellEdit) { if (0 < B.length && (Se = $(B).closest("td,th").html(), $(V).triggerHandler("jqGridCellSelect", [Ge, ke, Se, e]), $.isFunction(V.p.onCellSelect) && V.p.onCellSelect.call(V, Ge, ke, Se, e)), r) if (V.p.multimail && V.p.multiselect) { if (e.shiftKey) { if (t) { var i = $(V).jqGrid("getGridParam", "selrow"), o = $(V).jqGrid("getInd", Ge), a = $(V).jqGrid("getInd", i), n = "", l = "", l = a < o ? (n = i, Ge) : (n = Ge, i), s = !1, d = !1, i = !0; return -1 < $.inArray(Ge, V.p.selarrrow) && (i = !1), $.each($(this).getDataIDs(), function (e, t) { return (d = t === n || d) && $(V).jqGrid("resetSelection", t), t !== l }), i && $.each($(this).getDataIDs(), function (e, t) { return (s = t === n || s) && $(V).jqGrid("setSelection", t, !1), t !== l }), void (V.p.selrow = a < o ? l : n) } window.getSelection().removeAllRanges() } Ee(Ge, t, e, !1) } else V.p.multikey ? e[V.p.multikey] ? $(V).jqGrid("setSelection", Ge, !0, e) : V.p.multiselect && t && (t = $("#jqg_" + $.jgrid.jqID(V.p.id) + "_" + Ge).is(":checked"), $("#jqg_" + $.jgrid.jqID(V.p.id) + "_" + Ge)[V.p.useProp ? "prop" : "attr"]("checked", !t)) : Ee(Ge, t, e, !0) } else if (V.p.multiselect && t && r) $(V).jqGrid("setSelection", Ge, !0, e); else if (0 < B.length) try { $(V).jqGrid("editCell", H[0].rowIndex, ke, !0, e) } catch (e) { } }, reloadGrid: function (e, t) { var r; return !0 === V.p.treeGrid && (V.p.datatype = V.p.treedatatype), (t = t || {}).current && V.grid.selectionPreserver(V), "local" === V.p.datatype ? ($(V).jqGrid("resetSelection"), V.p.data.length && (f(), oe())) : V.p.treeGrid || (V.p.selrow = null, V.p.multiselect && (V.p.preserveSelection || (V.p.selarrrow = [], ne(!1))), V.p.savedRow = []), V.p.scroll && ie.call(V, !0, !1), t.page && ((r = t.page) > V.p.lastpage && (r = V.p.lastpage), r < 1 && (r = 1), V.p.page = r, V.grid.prevRowHeight ? V.grid.bDiv.scrollTop = (r - 1) * V.grid.prevRowHeight * V.p.rowNum : V.grid.bDiv.scrollTop = 0), V.grid.prevRowHeight && V.p.scroll && void 0 === t.page ? (delete V.p.lastpage, V.grid.populateVisible()) : V.grid.populate(), !0 === V.p.inlineNav && $(V).jqGrid("showAddEditButtons"), !1 }, dblclick: function (e) { if (B = e.target, H = $(B, V.rows).closest("tr.jqgrow"), 0 !== $(H).length) { Ge = H[0].rowIndex, ke = $.jgrid.getCellIndex(B); var t = $(V).triggerHandler("jqGridDblClickRow", [$(H).attr("id"), Ge, ke, e]); return null != t || $.isFunction(V.p.ondblClickRow) && null != (t = V.p.ondblClickRow.call(V, $(H).attr("id"), Ge, ke, e)) ? t : void 0 } }, contextmenu: function (e) { if (B = e.target, H = $(B, V.rows).closest("tr.jqgrow"), 0 !== $(H).length) { V.p.multiselect || $(V).jqGrid("setSelection", H[0].id, !0, e), Ge = H[0].rowIndex, ke = $.jgrid.getCellIndex(B); var t = $(V).triggerHandler("jqGridRightClickRow", [$(H).attr("id"), Ge, ke, e]); return null != t || $.isFunction(V.p.onRightClickRow) && null != (t = V.p.onRightClickRow.call(V, $(H).attr("id"), Ge, ke, e)) ? t : void 0 } } }), g.bDiv = document.createElement("div"), o && "auto" === String(V.p.height).toLowerCase() && (V.p.height = "100%"), $(g.bDiv).append($('<div style="position:relative;"></div>').append("<div></div>").append(this)).addClass("ui-jqgrid-bdiv").css({ height: V.p.height + (isNaN(V.p.height) ? "" : "px"), width: g.width - Ie + "px" }).on("scroll", g.scrollGrid), $("table:first", g.bDiv).css({ width: V.p.tblwidth + "px" }), $.support.tbody || 2 === $("tbody", this).length && $("tbody:gt(0)", this).remove(), V.p.multikey && ($.jgrid.msie() ? $(g.bDiv).on("selectstart", function () { return !1 }) : $(g.bDiv).on("mousedown", function () { return !1 })), Re && $(g.bDiv).hide(); var Ne = w + " " + Q(X, "icon_caption_open", !0), Oe = w + " " + Q(X, "icon_caption_close", !0); g.cDiv = document.createElement("div"); var Te, Ae, Pe = !0 === V.p.hidegrid ? $("<a role='link' class='ui-jqgrid-titlebar-close HeaderButton " + i + "' title='" + ($.jgrid.getRegional(V, "defaults.showhide", V.p.showhide) || "") + "' />").hover(function () { Pe.addClass(y) }, function () { Pe.removeClass(y) }).append("<span class='ui-jqgrid-headlink " + Ne + "'></span>").css("rtl" === m ? "left" : "right", "0px") : ""; $(g.cDiv).append(Pe).append("<span class='ui-jqgrid-title'>" + V.p.caption + "</span>").addClass("ui-jqgrid-titlebar ui-jqgrid-caption" + ("rtl" === m ? "-rtl" : "") + " " + Q(X, "gridtitleBox", !0)), !0 === V.p.menubar && (Te = '<ul id="' + V.p.id + '_menubar" class="ui-search-menu modal-content column-menu ui-menu jqgrid-caption-menu ' + x.menu_widget + '" role="menubar" tabindex="0"></ul>', $("#gbox_" + V.p.id).append(Te), $(g.cDiv).append("<a role='link' class='ui-jqgrid-menubar menubar-" + ("rtl" === m ? "rtl" : "ltr") + "' style=''><span class='colmenuspan " + w + " " + x.icon_toolbar_menu + "'></span></a>"), $(".ui-jqgrid-menubar", g.cDiv).hover(function () { $(this).addClass(y) }, function () { $(this).removeClass(y) }).on("click", function (e) { e = $(e.target).position(); $("#" + V.p.id + "_menubar").show(), "rtl" === V.p.direction && $("#" + V.p.id + "_menubar").css({ left: e.left - $("#" + V.p.id + "_menubar").width() - 20 }) })), $(g.cDiv).insertBefore(g.hDiv), V.p.toolbar[0] && (Te = Q(X, "customtoolbarBox", !0, "ui-userdata"), g.uDiv = document.createElement("div"), "top" === V.p.toolbar[1] ? $(g.uDiv).insertBefore(g.hDiv) : "bottom" === V.p.toolbar[1] && $(g.uDiv).insertAfter(g.hDiv), "both" === V.p.toolbar[1] ? (g.ubDiv = document.createElement("div"), $(g.uDiv).addClass(Te + " ui-userdata-top").attr("id", "t_" + this.id).insertBefore(g.hDiv).width(g.width - Ie), $(g.ubDiv).addClass(Te + " ui-userdata-bottom").attr("id", "tb_" + this.id).insertAfter(g.hDiv).width(g.width - Ie), Re && $(g.ubDiv).hide()) : $(g.uDiv).width(g.width - Ie).addClass(Te + " ui-userdata-top").attr("id", "t_" + this.id), Re && $(g.uDiv).hide()), V.p.toppager && (V.p.toppager = $.jgrid.jqID(V.p.id) + "_toppager", g.topDiv = $("<div id='" + V.p.toppager + "'></div>")[0], $(g.topDiv).addClass(Q(X, "toppagerBox", !0, "ui-jqgrid-toppager")).width(g.width - Ie).insertBefore(g.hDiv), S(V.p.toppager, "_t"), V.p.toppager = "#" + V.p.toppager), V.p.footerrow && (g.sDiv = $("<div class='ui-jqgrid-sdiv'></div>")[0], Me = $("<div class='ui-jqgrid-hbox" + ("rtl" === m ? "-rtl" : "") + "'></div>"), $(g.sDiv).append(Me).width(g.width - Ie).insertAfter(g.hDiv), $(Me).append(_e), g.footers = $(".ui-jqgrid-ftable", g.sDiv)[0].rows[0].cells, V.p.rownumbers && (g.footers[0].className = Q(X, "rownumBox", !0, "jqgrid-rownum")), Re && $(g.sDiv).hide()), V.p.headerrow && (g.hrDiv = $("<div class='ui-jqgrid-hrdiv'></div>")[0], Me = $("<div class='ui-jqgrid-hbox" + ("rtl" === m ? "-rtl" : "") + "'></div>"), $(g.hrDiv).append(Me).width(g.width - Ie).insertAfter(g.hDiv), $(Me).append(qe), g.hrheaders = $(".ui-jqgrid-hrtable", g.hrDiv)[0].rows[0].cells, V.p.rownumbers && (g.hrheaders[0].className = Q(X, "rownumBox", !0, "jqgrid-rownum")), Re && $(g.nDiv).hide()), Me = null, V.p.caption ? (Ae = V.p.datatype, !0 === V.p.hidegrid && ($(".ui-jqgrid-titlebar-close", g.cDiv).click(function (e) { var t, r = $.isFunction(V.p.onHeaderClick), i = ".ui-jqgrid-bdiv, .ui-jqgrid-hdiv, .ui-jqgrid-toppager, .ui-jqgrid-pager, .ui-jqgrid-sdiv, .ui-jqgrid-hrdiv", o = this; return !0 === V.p.toolbar[0] && ("both" === V.p.toolbar[1] && (i += ", #" + $(g.ubDiv).attr("id")), i += ", #" + $(g.uDiv).attr("id")), t = $(i, "#gview_" + $.jgrid.jqID(V.p.id)).length, "visible" === V.p.gridstate ? $(i, "#gbox_" + $.jgrid.jqID(V.p.id)).slideUp("fast", function () { 0 === --t && ($("span", o).removeClass(Ne).addClass(Oe), V.p.gridstate = "hidden", $("#gbox_" + $.jgrid.jqID(V.p.id)).hasClass("ui-resizable") && $(".ui-resizable-handle", "#gbox_" + $.jgrid.jqID(V.p.id)).hide(), $(V).triggerHandler("jqGridHeaderClick", [V.p.gridstate, e]), r && (Re || V.p.onHeaderClick.call(V, V.p.gridstate, e))) }) : "hidden" === V.p.gridstate && $(i, "#gbox_" + $.jgrid.jqID(V.p.id)).slideDown("fast", function () { 0 === --t && ($("span", o).removeClass(Oe).addClass(Ne), Re && (V.p.datatype = Ae, k(), Re = !1), V.p.gridstate = "visible", $("#gbox_" + $.jgrid.jqID(V.p.id)).hasClass("ui-resizable") && $(".ui-resizable-handle", "#gbox_" + $.jgrid.jqID(V.p.id)).show(), $(V).triggerHandler("jqGridHeaderClick", [V.p.gridstate, e]), r && (Re || V.p.onHeaderClick.call(V, V.p.gridstate, e))) }), !1 }), Re && (V.p.datatype = "local", $(".ui-jqgrid-titlebar-close", g.cDiv).trigger("click")))) : ($(g.cDiv).hide(), V.p.toppager || $(g.hDiv).addClass(Q(V.p.styleUI + ".common", "cornertop", !0))), (V.p.headerrow ? $(g.hrDiv) : $(g.hDiv)).after(g.bDiv), $(g.hDiv).mousemove(function (e) { if (g.resizing) return g.dragMove(e), !1 }), $(".ui-jqgrid-labels", g.hDiv).on("selectstart", function () { return !1 }), $(document).on("mouseup.jqGrid" + V.p.id, function () { return !g.resizing || (g.dragEnd(!0), !1) }), "rtl" === V.p.direction && $(V).on("jqGridAfterGridComplete.setRTLPadding", function () { var e = g.bDiv.offsetWidth - g.bDiv.clientWidth; 0 < e && (e += 2), $("div:first", g.hDiv).hasClass("ui-jqgrid-hbox-rtl") && $("div:first", g.hDiv).css({ paddingLeft: e + "px" }), g.hDiv.scrollLeft = g.bDiv.scrollLeft }), V.p.autoResizing && $(V).on("jqGridAfterGridComplete.setAutoSizeColumns", function () { $(V.p.colModel).each(function (e) { this.autosize && this._maxsize && 0 < this._maxsize && ($(V).jqGrid("resizeColumn", e, this._maxsize + (T ? V.p.cellLayout : 0)), this._maxsize = 0) }), $(V).jqGrid("refreshGroupHeaders") }), V.formatCol = p, V.sortData = R, V.updatepager = function (e, t) { var r, i, o, a, n, l = "", s = V.p.pager ? V.p.pager.substring(1) : "", d = s ? "_" + s : "", p = V.p.toppager ? "_" + V.p.toppager.substr(1) : "", c = parseInt(V.p.page, 10) - 1; c < 0 && (c = 0), r = (c *= parseInt(V.p.rowNum, 10)) + V.p.reccount, V.p.scroll && (n = $("tbody:first > tr:gt(0)", V.grid.bDiv), r > V.p.records && (r = V.p.records), c = r - n.length, V.p.reccount = n.length, (n = n.outerHeight() || V.grid.prevRowHeight) && (a = c * n, o = parseInt(V.p.records, 10) * n, $(">div:first", V.grid.bDiv).css({ height: o }).children("div:first").css({ height: a, display: a ? "" : "none" }), 0 === V.grid.bDiv.scrollTop && 1 < V.p.page && (V.grid.bDiv.scrollTop = V.p.rowNum * (V.p.page - 1) * n)), V.grid.bDiv.scrollLeft = V.grid.hDiv.scrollLeft), l = V.p.pager || "", (l += V.p.toppager ? l ? "," + V.p.toppager : V.p.toppager : "") && (o = $.jgrid.getRegional(V, "formatter.integer"), a = K(V.p.page), n = K(V.p.lastpage), $(".selbox", l)[this.p.useProp ? "prop" : "attr"]("disabled", !1), !0 === V.p.pginput && ($("#input" + d).html($.jgrid.template($.jgrid.getRegional(V, "defaults.pgtext", V.p.pgtext) || "", "<input " + Q(X, "pgInput", !1, "ui-pg-input") + " type='text' size='2' maxlength='7' value='0' role='textbox'/>", "<span id='sp_1_" + s + "'></span>")), V.p.toppager && $("#input_t" + p).html($.jgrid.template($.jgrid.getRegional(V, "defaults.pgtext", V.p.pgtext) || "", "<input " + Q(X, "pgInput", !1, "ui-pg-input") + " type='text' size='2' maxlength='7' value='0' role='textbox'/>", "<span id='sp_1_" + s + "_toppager'></span>")), $(".ui-pg-input", l).val(V.p.page), i = V.p.toppager ? "#sp_1" + d + ",#sp_1" + d + "_toppager" : "#sp_1" + d, $(i).html($.fmatter ? $.fmatter.util.NumberFormat(V.p.lastpage, o) : V.p.lastpage)), V.p.viewrecords && (0 === V.p.reccount ? $(".ui-paging-info", l).html($.jgrid.getRegional(V, "defaults.emptyrecords", V.p.emptyrecords)) : (s = c + 1, i = V.p.records, $.fmatter && (s = $.fmatter.util.NumberFormat(s, o), r = $.fmatter.util.NumberFormat(r, o), i = $.fmatter.util.NumberFormat(i, o)), o = $.jgrid.getRegional(V, "defaults.recordtext", V.p.recordtext), $(".ui-paging-info", l).html($.jgrid.template(o, s, r, i)))), !0 === V.p.pgbuttons && (a <= 0 && (a = n = 0), 1 === a || 0 === a ? ($("#first" + d + ", #prev" + d).addClass(v).removeClass(y), V.p.toppager && $("#first_t" + p + ", #prev_t" + p).addClass(v).removeClass(y)) : ($("#first" + d + ", #prev" + d).removeClass(v), V.p.toppager && $("#first_t" + p + ", #prev_t" + p).removeClass(v)), a === n || 0 === a ? ($("#next" + d + ", #last" + d).addClass(v).removeClass(y), V.p.toppager && $("#next_t" + p + ", #last_t" + p).addClass(v).removeClass(y)) : ($("#next" + d + ", #last" + d).removeClass(v), V.p.toppager && $("#next_t" + p + ", #last_t" + p).removeClass(v)))), !0 === e && !0 === V.p.rownumbers && $(">td.jqgrid-rownum", V.rows).each(function (e) { $(this).html(c + 1 + e) }), 0 === V.p.reccount && (e = Q(X, "rowBox", !0, "jqgrow ui-row-" + V.p.direction), e = ae("norecs", !1, e, {}, ""), e += "<td style='text-align:center' colspan='" + g.headers.length + "'>" + $.jgrid.getRegional(V, "defaults.emptyrecords", V.p.emptyrecords) + "</td>", e += "</tr>", $("table:first", g.bDiv).append(e)), t && V.p.jqgdnd && $(V).jqGrid("gridDnD", "updateDnD"), $(V).triggerHandler("jqGridGridComplete"), $.isFunction(V.p.gridComplete) && V.p.gridComplete.call(V), $(V).triggerHandler("jqGridAfterGridComplete") }, V.refreshIndex = oe, V.setHeadCheckBox = ne, V.constructTr = ae, V.formatter = h, $.extend(g, { populate: k, emptyRows: ie, beginReq: q, endReq: I }), this.grid = g, V.addXmlData = function (e) { b(e) }, V.addJSONData = function (e) { j(e) }, V.addLocalData = _, V.treeGrid_beforeRequest = function () { V.p.treeGrid && V.p.treeGrid_bigData && void 0 !== V.p.postData.nodeid && "string" == typeof V.p.postData.nodeid && ("" !== V.p.postData.nodeid || 0 < parseInt(V.p.postData.nodeid, 10)) && (V.p.postData.rows = 1e4, V.p.postData.page = 1, V.p.treeGrid_rootParams.otherData.nodeid = V.p.postData.nodeid) }, V.treeGrid_afterLoadComplete = function () { V.p.treeGrid && V.p.treeGrid_bigData && (void 0 !== V.p.treeGrid_rootParams.otherData.nodeid && "string" == typeof V.p.treeGrid_rootParams.otherData.nodeid && ("" !== V.p.treeGrid_rootParams.otherData.nodeid || 0 < parseInt(V.p.treeGrid_rootParams.otherData.nodeid, 10)) ? void 0 !== V.p.treeGrid_rootParams && null != V.p.treeGrid_rootParams && (V.p.page = V.p.treeGrid_rootParams.page, V.p.lastpage = V.p.treeGrid_rootParams.lastpage, V.p.postData.rows = V.p.treeGrid_rootParams.postData.rows, V.p.postData.totalrows = V.p.treeGrid_rootParams.postData.totalrows, V.p.treeGrid_rootParams.otherData.nodeid = "", V.updatepager(!1, !0)) : V.p.treeGrid_rootParams = { page: V.p.page, lastpage: V.p.lastpage, postData: { rows: V.p.postData.rows, totalrows: V.p.postData.totalrows }, rowNum: V.p.rowNum, rowTotal: V.p.rowTotal, otherData: { nodeid: "" } }) }, this.grid.cols = this.rows[0].cells, $.isFunction(V.p.onInitGrid) && V.p.onInitGrid.call(V), $(V).triggerHandler("jqGridInitGrid"), k(), V.p.hiddengrid = !1, V.p.responsive && (Me = "onorientationchange" in window ? "orientationchange" : "resize", $(window).on(Me, function () { $(V).jqGrid("resizeGrid") })) } else alert($.jgrid.getRegional(this, "errors.model")) } else alert("Element is not a table or has no id!") } function Ee(e, t, r, i) { var o; !(V.p.multiselect && V.p.multiboxonly || V.p.multimail) || t ? $(V).jqGrid("setSelection", e, i, r) : V.p.multiboxonly && V.p.multimail ? ($(V).triggerHandler("jqGridSelectRow", [e, !1, r]), V.p.onSelectRow && V.p.onSelectRow.call(V, e, !1, r)) : (o = V.p.frozenColumns ? V.p.id + "_frozen" : "", $(V.p.selarrrow).each(function (e, t) { var r = $(V).jqGrid("getGridRowById", t); r && $(r).removeClass(Y), $("#jqg_" + $.jgrid.jqID(V.p.id) + "_" + $.jgrid.jqID(t))[V.p.useProp ? "prop" : "attr"]("checked", !1), o && ($("#" + $.jgrid.jqID(t), "#" + $.jgrid.jqID(o)).removeClass(Y), $("#jqg_" + $.jgrid.jqID(V.p.id) + "_" + $.jgrid.jqID(t), "#" + $.jgrid.jqID(o))[V.p.useProp ? "prop" : "attr"]("checked", !1)) }), V.p.selarrrow = [], $(V).jqGrid("setSelection", e, i, r)) } }); var e = $.jgrid.getMethod(Be); if (!e) throw "jqGrid - No such method: " + Be; var t = $.makeArray(arguments).slice(1); return e.apply(this, t) }, $.jgrid.extend({ getGridParam: function (e, t) { var r, i = this[0]; if (i && i.grid) { if (void 0 === t && "string" != typeof t && (t = "jqGrid"), r = i.p, "jqGrid" !== t) try { r = $(i).data(t) } catch (e) { r = i.p } return e ? void 0 !== r[e] ? r[e] : null : r } }, setGridParam: function (t, r) { return this.each(function () { var e; null == r && (r = !1), this.grid && "object" == typeof t && (!0 === r ? (e = $.extend({}, this.p, t), this.p = e) : $.extend(!0, this.p, t)) }) }, getGridRowById: function (t) { var r; return this.each(function () { try { for (var e = this.rows.length; e--;)if (t.toString() === this.rows[e].id) { r = this.rows[e]; break } } catch (e) { r = $(this.grid.bDiv).find("#" + $.jgrid.jqID(t))[0] } }), r }, getDataIDs: function () { var e, t = [], r = 0, i = 0; return this.each(function () { if ((e = this.rows.length) && 0 < e) for (; r < e;)$(this.rows[r]).hasClass("jqgrow") && "norecs" !== this.rows[r].id && (t[i] = this.rows[r].id, i++), r++ }), t }, setSelection: function (u, h, g, f) { return this.each(function () { var e, t, r, i, o, a, n, l, s = this, d = $.jgrid.getMethod("getStyleUI"), p = d(s.p.styleUI + ".common", "highlight", !0), c = d(s.p.styleUI + ".common", "disabled", !0); void 0 !== u && (void 0 === f && (f = !0), f = !1 !== f, h = !1 !== h, !(d = $(s).jqGrid("getGridRowById", u)) || !d.className || -1 < d.className.indexOf(c) || (!0 === s.p.scrollrows && 0 <= (t = $(s).jqGrid("getGridRowById", u).rowIndex) && (o = t, a = $(s.grid.bDiv)[0].clientHeight, n = $(s.grid.bDiv)[0].scrollTop, l = $(s.rows[o]).position().top, o = s.rows[o].clientHeight, a + n <= l + o ? $(s.grid.bDiv)[0].scrollTop = l - (a + n) + o + n : l < a + n && l < n && ($(s.grid.bDiv)[0].scrollTop = l)), !0 === s.p.frozenColumns && (r = s.p.id + "_frozen"), s.p.multiselect ? (s.setHeadCheckBox(!1), s.p.selrow = d.id, -1 === (i = $.inArray(s.p.selrow, s.p.selarrrow)) ? ("ui-subgrid" !== d.className && $(d).addClass(p).attr("aria-selected", "true"), e = !0, s.p.selarrrow.push(s.p.selrow)) : -1 !== i && "_sp_" === g ? ("ui-subgrid" !== d.className && $(d).addClass(p).attr("aria-selected", "true"), e = !0) : ("ui-subgrid" !== d.className && $(d).removeClass(p).attr("aria-selected", "false"), e = !1, s.p.selarrrow.splice(i, 1), t = s.p.selarrrow[0], s.p.selrow = void 0 === t ? null : t), $("#jqg_" + $.jgrid.jqID(s.p.id) + "_" + $.jgrid.jqID(d.id))[s.p.useProp ? "prop" : "attr"]("checked", e), r && (f && (-1 === i ? $("#" + $.jgrid.jqID(u), "#" + $.jgrid.jqID(r)).addClass(p) : $("#" + $.jgrid.jqID(u), "#" + $.jgrid.jqID(r)).removeClass(p)), $("#jqg_" + $.jgrid.jqID(s.p.id) + "_" + $.jgrid.jqID(u), "#" + $.jgrid.jqID(r))[s.p.useProp ? "prop" : "attr"]("checked", e)), h && ($(s).triggerHandler("jqGridSelectRow", [d.id, e, g]), s.p.onSelectRow && s.p.onSelectRow.call(s, d.id, e, g))) : "ui-subgrid" !== d.className && (e = s.p.selrow !== d.id && (f && ((i = $(s).jqGrid("getGridRowById", s.p.selrow)) && $(i).removeClass(p).attr({ "aria-selected": "false", tabindex: "-1" }), $(d).addClass(p).attr({ "aria-selected": "true", tabindex: "0" }), r && ($("#" + $.jgrid.jqID(s.p.selrow), "#" + $.jgrid.jqID(r)).removeClass(p), $("#" + $.jgrid.jqID(u), "#" + $.jgrid.jqID(r)).addClass(p))), !0), s.p.selrow = d.id, h && ($(s).triggerHandler("jqGridSelectRow", [d.id, e, g]), s.p.onSelectRow && s.p.onSelectRow.call(s, d.id, e, g))))) }) }, resetSelection: function (n) { return this.each(function () { var r, e, i = this, t = $.jgrid.getMethod("getStyleUI"), o = t(i.p.styleUI + ".common", "highlight", !0), a = t(i.p.styleUI + ".common", "hover", !0); !0 === i.p.frozenColumns && (r = i.p.id + "_frozen"), void 0 !== n ? (e = n === i.p.selrow ? i.p.selrow : n, $("#" + $.jgrid.jqID(i.p.id) + " tbody:first tr#" + $.jgrid.jqID(e)).removeClass(o).attr("aria-selected", "false"), r && $("#" + $.jgrid.jqID(e), "#" + $.jgrid.jqID(r)).removeClass(o), i.p.multiselect && ($("#jqg_" + $.jgrid.jqID(i.p.id) + "_" + $.jgrid.jqID(e), "#" + $.jgrid.jqID(i.p.id))[i.p.useProp ? "prop" : "attr"]("checked", !1), r && $("#jqg_" + $.jgrid.jqID(i.p.id) + "_" + $.jgrid.jqID(e), "#" + $.jgrid.jqID(r))[i.p.useProp ? "prop" : "attr"]("checked", !1), i.setHeadCheckBox(!1), -1 !== (t = $.inArray($.jgrid.jqID(e), i.p.selarrrow)) && i.p.selarrrow.splice(t, 1)), i.p.onUnSelectRow && i.p.onUnSelectRow.call(i, e), e = null) : i.p.multiselect ? ($(i.p.selarrrow).each(function (e, t) { $($(i).jqGrid("getGridRowById", t)).removeClass(o).attr("aria-selected", "false"), $("#jqg_" + $.jgrid.jqID(i.p.id) + "_" + $.jgrid.jqID(t))[i.p.useProp ? "prop" : "attr"]("checked", !1), r && ($("#" + $.jgrid.jqID(t), "#" + $.jgrid.jqID(r)).removeClass(o), $("#jqg_" + $.jgrid.jqID(i.p.id) + "_" + $.jgrid.jqID(t), "#" + $.jgrid.jqID(r))[i.p.useProp ? "prop" : "attr"]("checked", !1)), i.p.onUnSelectRow && i.p.onUnSelectRow.call(i, t) }), i.setHeadCheckBox(!1), i.p.selarrrow = [], i.p.selrow = null) : i.p.selrow && ($("#" + $.jgrid.jqID(i.p.id) + " tbody:first tr#" + $.jgrid.jqID(i.p.selrow)).removeClass(o).attr("aria-selected", "false"), r && $("#" + $.jgrid.jqID(i.p.selrow), "#" + $.jgrid.jqID(r)).removeClass(o), i.p.onUnSelectRow && i.p.onUnSelectRow.call(i, i.p.selrow), i.p.selrow = null), !0 === i.p.cellEdit && 0 <= parseInt(i.p.iCol, 10) && 0 <= parseInt(i.p.iRow, 10) && ($("td:eq(" + i.p.iCol + ")", i.rows[i.p.iRow]).removeClass("edit-cell " + o), $(i.rows[i.p.iRow]).removeClass("selected-row " + a)) }) }, getRowData: function (e, a, n) { var l, s, d = {}, p = !1, c = 0; return this.each(function () { var t, r, i = this; if (null == e) p = !0, l = [], s = i.rows.length; else { if (!(r = $(i).jqGrid("getGridRowById", e))) return d; s = 1 } for (a && !0 === a && 0 < i.p.data.length || (a = !1), null == n && (n = !1); c < s;) { if (p && (r = i.rows[c]), $(r).hasClass("jqgrow")) { if (a ? d = $.extend({}, i.p.data[i.p._index[$.jgrid.stripPref(i.p.idPrefix, r.id)]]) : $(r).children('td[role="gridcell"]').each(function (e) { if ("cb" !== (t = i.p.colModel[e].name) && "subgrid" !== t && "rn" !== t) if (!0 === i.p.treeGrid && t === i.p.ExpandColumn) d[t] = $.jgrid.htmlDecode($("span:first", this).html()); else try { d[t] = $.unformat.call(i, this, { rowId: r.id, colModel: i.p.colModel[e] }, e) } catch (e) { d[t] = $.jgrid.htmlDecode($(this).html()) } }), !0 === i.p.treeGrid && n) { var o = i.p.treeReader.level_field; n += ""; try { o = parseInt(d[o], 10) } catch (e) { o = 0 } d[i.p.ExpandColumn] = n.repeat(o) + d[i.p.ExpandColumn] } p && (l.push(d), d = {}) } c++ } }), l || d }, delRowData: function (r) { var i, o, a, n = !1; return this.each(function () { var e, t = this; if (!(i = $(t).jqGrid("getGridRowById", r))) return !1; r = i.id, t.p.subGrid && (a = $(i).next()).hasClass("ui-subgrid") && a.remove(), $(i).remove(), t.p.records--, t.p.reccount--, t.updatepager(!0, !1), n = !0, t.p.multiselect && -1 !== (o = $.inArray(r, t.p.selarrrow)) && t.p.selarrrow.splice(o, 1), t.p.multiselect && 0 < t.p.selarrrow.length ? t.p.selrow = t.p.selarrrow[t.p.selarrrow.length - 1] : t.p.selrow === r && (t.p.selrow = null), "local" === t.p.datatype && (e = $.jgrid.stripPref(t.p.idPrefix, r), void 0 !== (e = t.p._index[e]) && (t.p.data.splice(e, 1), t.refreshIndex())) }), n }, setRowData: function (s, d, p, c) { var u, h = !0; return this.each(function () { if (!this.grid) return !1; var r, i, e, o = this, a = {}, n = $(this).jqGrid("getGridRowById", s); if (!n) return !1; if (!0 === c && (e = $(o).jqGrid("getRowData", s, "local" === o.p.datatype)), d) { c && (d = $.extend(e, d)); try { if ($(this.p.colModel).each(function (e) { u = this.name; var t = $.jgrid.getAccessor(d, u); void 0 !== t && (a[u] = this.formatter && "string" == typeof this.formatter && "date" === this.formatter ? $.unformat.date.call(o, t, this) : t, i = o.formatter(s, a[u], e, d, "edit"), r = o.formatCol(e, n.rowIndex, i, d, s, d), r = $('<td role="gridcell" ' + r + ">" + i + "</td>")[0], i = $(n).children("td[role='gridcell']:eq(" + e + ")"), $(i).after(r).remove(), o.p.treeGrid && o.p.ExpandColumn === u && $(o).jqGrid("setTreeNode", n.rowIndex, n.rowIndex + 1)) }), "local" === o.p.datatype) { var t, l = $.jgrid.stripPref(o.p.idPrefix, s), l = o.p._index[l]; if (o.p.treeGrid) for (t in o.p.treeReader) o.p.treeReader.hasOwnProperty(t) && delete a[o.p.treeReader[t]]; void 0 !== l && (o.p.data[l] = $.extend(!0, o.p.data[l], a)), a = null } } catch (e) { h = !1 } } h && ("string" == typeof p ? $(n).addClass(p) : null !== p && "object" == typeof p && $(n).css(p), $(o).triggerHandler("jqGridAfterGridComplete")) }), h }, addRowData: function (n, l, s, d) { -1 === $.inArray(s, ["first", "last", "before", "after"]) && (s = "last"); var p, c, u, h, g, f, m, v, b, j, y, w, x = !1, _ = "", q = "", I = ""; return l && ($.isArray(l) ? (v = !0, b = n) : v = !(l = [l]), this.each(function () { var e = this, t = l.length; h = !0 === e.p.rownumbers ? 1 : 0, c = !0 === e.p.multiselect ? 1 : 0, u = !0 === e.p.subGrid ? 1 : 0, v || (void 0 !== n ? n = String(n) : (n = $.jgrid.randId(), !1 !== e.p.keyName && (b = e.p.keyName, void 0 !== l[0][b] && (n = l[0][b])))); var r = 0, i = $(e).jqGrid("getStyleUI", e.p.styleUI + ".base", "rowBox", !0, "jqgrow ui-row-" + e.p.direction), o = {}, a = !!$.isFunction(e.p.afterInsertRow); for (h && (_ = $(e).jqGrid("getStyleUI", e.p.styleUI + ".base", "rownumBox", !1, "jqgrid-rownum")), c && (q = $(e).jqGrid("getStyleUI", e.p.styleUI + ".base", "multiBox", !1, "cbox")); r < t;) { if (j = l[r], p = [], v) try { void 0 === (n = j[b]) && (n = $.jgrid.randId()) } catch (e) { n = $.jgrid.randId() } for (w = n, n = e.p.idPrefix + n, h && (I = e.formatCol(0, 1, "", null, n, !0), p[p.length] = '<td role="gridcell" ' + _ + " " + I + ">0</td>"), c && (m = '<input role="checkbox" type="checkbox" id="jqg_' + e.p.id + "_" + n + '" ' + q + "/>", I = e.formatCol(h, 1, "", null, n, !0), p[p.length] = '<td role="gridcell" ' + I + ">" + m + "</td>"), u && (p[p.length] = $(e).jqGrid("addSubGridCell", c + h, 1)), f = c + u + h; f < e.p.colModel.length; f++)y = e.p.colModel[f], o[y = y.name] = j[y], m = e.formatter(n, $.jgrid.getAccessor(j, y), f, j), I = e.formatCol(f, 1, m, j, n, o), p[p.length] = '<td role="gridcell" ' + I + ">" + m + "</td>"; if (p.unshift(e.constructTr(n, !1, i, o, j)), p[p.length] = "</tr>", 0 === e.rows.length) $("table:first", e.grid.bDiv).append(p.join("")); else switch (s) { case "last": $(e.rows[e.rows.length - 1]).after(p.join("")), g = e.rows.length - 1; break; case "first": $(e.rows[0]).after(p.join("")), g = 1; break; case "after": (g = $(e).jqGrid("getGridRowById", d)) && ($(e.rows[g.rowIndex + 1]).hasClass("ui-subgrid") ? $(e.rows[g.rowIndex + 1]).after(p) : $(g).after(p.join("")), g = g.rowIndex + 1); break; case "before": (g = $(e).jqGrid("getGridRowById", d)) && ($(g).before(p.join("")), g = g.rowIndex - 1) }if (!0 === e.p.subGrid && $(e).jqGrid("addSubGrid", c + h, g), e.p.records++, e.p.reccount++, $(e).triggerHandler("jqGridAfterInsertRow", [n, j, j]), a && e.p.afterInsertRow.call(e, n, j, j), r++, "local" === e.p.datatype) switch (o[e.p.localReader.id] = w, s) { case "first": e.p.data.unshift(o); break; case "last": e.p.data.push(o); break; case "before": case "after": e.p.data.splice(g - 1, 0, o) }o = {}, 1 === e.p.reccount && (g = $(e).jqGrid("getGridRowById", "norecs")).rowIndex && 0 < g.rowIndex && $(e.rows[g.rowIndex]).remove() } "local" === e.p.datatype && e.refreshIndex(), e.updatepager(!0, !0), x = !0 })), x }, footerData: function (i, o, a) { var n, l, s = !1, d = {}; return void 0 === i && (i = "get"), "boolean" != typeof a && (a = !0), i = i.toLowerCase(), this.each(function () { var t, r = this; return !(!r.grid || !r.p.footerrow) && (("set" !== i || !function (e) { for (var t in e) if (e.hasOwnProperty(t)) return; return 1 }(o)) && (s = !0, void $(this.p.colModel).each(function (e) { n = this.name, "set" === i ? void 0 !== o[n] && (t = a ? r.formatter("", o[n], e, o, "edit") : o[n], l = this.title ? { title: $.jgrid.stripHtml(t) } : {}, $("tr.footrow td:eq(" + e + ")", r.grid.sDiv).html(t).attr(l), s = !0) : "get" === i && (d[n] = $("tr.footrow td:eq(" + e + ")", r.grid.sDiv).html()) }))) }), "get" === i ? d : s }, headerData: function (i, o, a) { var n, l, s = !1, d = {}; return void 0 === i && (i = "get"), "boolean" != typeof a && (a = !0), i = i.toLowerCase(), this.each(function () { var t, r = this; return !(!r.grid || !r.p.headerrow) && (("set" !== i || !function (e) { for (var t in e) if (e.hasOwnProperty(t)) return; return 1 }(o)) && (s = !0, void $(this.p.colModel).each(function (e) { n = this.name, "set" === i ? void 0 !== o[n] && (t = a ? r.formatter("", o[n], e, o, "edit") : o[n], l = this.title ? { title: $.jgrid.stripHtml(t) } : {}, $("tr.hrheadrow td:eq(" + e + ")", r.grid.hrDiv).html(t).attr(l), s = !0) : "get" === i && (d[n] = $("tr.hrheadrow td:eq(" + e + ")", r.grid.hrDiv).html()) }))) }), "get" === i ? d : s }, showHideCol: function (d, p) { return this.each(function () { var t, r = this, i = !1, o = $.jgrid.cell_width ? 0 : r.p.cellLayout, e = !1; if (r.grid) { "string" == typeof d && (d = [d]); var a = "" === (p = "none" !== p ? "" : "none"), n = null, l = $(r).jqGrid("isGroupHeaderOn"); if (r.p.frozenColumns && ($(r).jqGrid("destroyFrozenColumns"), e = !0), l && ($(r).jqGrid("destroyGroupHeader", !1), n = $.extend([], r.p.groupHeader), r.p.groupHeader = null), $(this.p.colModel).each(function (e) { -1 !== $.inArray(this.name, d) && this.hidden === a && ($("tr[role=row]", r.grid.hDiv).each(function () { $(this.cells[e]).css("display", p) }), $(r.rows).each(function () { $(this).hasClass("jqgroup") || $(this.cells[e]).css("display", p) }), r.p.footerrow && $("tr.footrow td:eq(" + e + ")", r.grid.sDiv).css("display", p), r.p.headerrow && $("tr.hrheadrow td:eq(" + e + ")", r.grid.hrDiv).css("display", p), t = parseInt(this.width, 10), "none" === p ? r.p.tblwidth -= t + o : r.p.tblwidth += t + o, this.hidden = !a, i = !0, $(r).triggerHandler("jqGridShowHideCol", [a, this.name, e])) }), !0 === i && (!0 !== r.p.shrinkToFit || isNaN(r.p.height) || (r.p.tblwidth += parseInt(r.p.scrollOffset, 10)), $(r).jqGrid("setGridWidth", !0 === r.p.shrinkToFit ? r.p.tblwidth : r.p.width)), l && n) for (var s = 0; s < n.length; s++)$(r).jqGrid("setGroupHeaders", n[s]); e && $(r).jqGrid("setFrozenColumns") } }) }, hideCol: function (e) { return this.each(function () { $(this).jqGrid("showHideCol", e, "none") }) }, showCol: function (e) { return this.each(function () { $(this).jqGrid("showHideCol", e, "") }) }, remapColumns: function (i, e, t) { function r(t) { var r = t.length ? $.makeArray(t) : $.extend({}, t); $.each(i, function (e) { t[e] = r[this] }) } var o = this.get(0); function a(e, t) { $(">tr" + (t || ""), e).each(function () { var t = this, r = $.makeArray(t.cells); $.each(i, function () { var e = r[this]; e && t.appendChild(e) }) }) } r(o.p.colModel), r(o.p.colNames), r(o.grid.headers), a($("thead:first", o.grid.hDiv), t && ":not(.ui-jqgrid-labels)"), e && a($("#" + $.jgrid.jqID(o.p.id) + " tbody:first"), ".jqgfirstrow, tr.jqgrow, tr.jqfoot"), o.p.footerrow && a($("tbody:first", o.grid.sDiv)), o.p.headerrow && a($("tbody:first", o.grid.hrDiv)), o.p.remapColumns && (o.p.remapColumns.length ? r(o.p.remapColumns) : o.p.remapColumns = $.makeArray(i)), o.p.lastsort = $.inArray(o.p.lastsort, i), o.p.treeGrid && (o.p.expColInd = $.inArray(o.p.expColInd, i)), $(o).triggerHandler("jqGridRemapColumns", [i, e, t]) }, setGridWidth: function (v, b) { return this.each(function () { if (this.grid) { var e, t, r, i = this, o = !1, a = 0, n = $.jgrid.cell_width ? 0 : i.p.cellLayout, l = 0, s = !1, d = i.p.scrollOffset, p = 0, c = -1 === i.p.styleUI.search("Bootstrap") || isNaN(i.p.height) ? 0 : 2; if ("boolean" != typeof b && (b = i.p.shrinkToFit), !isNaN(v)) { if (v = parseInt(v, 10), i.grid.width = i.p.width = v, $("#gbox_" + $.jgrid.jqID(i.p.id)).css("width", v + "px"), $("#gview_" + $.jgrid.jqID(i.p.id)).css("width", v + "px"), $(i.grid.bDiv).css("width", v - c + "px"), $(i.grid.hDiv).css("width", v - c + "px"), i.p.pager && $(i.p.pager).css("width", v - c + "px"), i.p.toppager && $(i.p.toppager).css("width", v - c + "px"), !0 === i.p.toolbar[0] && ($(i.grid.uDiv).css("width", v - c + "px"), "both" === i.p.toolbar[1] && $(i.grid.ubDiv).css("width", v - c + "px")), i.p.footerrow && $(i.grid.sDiv).css("width", v - c + "px"), i.p.headerrow && $(i.grid.hrDiv).css("width", v - c + "px"), (e = $(i).jqGrid("isGroupHeaderOn")) && $(i).jqGrid("destroyGroupHeader", !1), i.p.frozenColumns && ($(i).jqGrid("destroyFrozenColumns"), o = !0), !1 === b && !0 === i.p.forceFit && (i.p.forceFit = !1), !0 === b) { if ($.each(i.p.colModel, function () { !1 === this.hidden && (g = this.widthOrg, a += g + n, this.fixed ? p += g + n : l++) }), 0 === l) return; i.p.tblwidth = a, r = v - n * l - p, isNaN(i.p.height) || ($(i.grid.bDiv)[0].clientHeight < $(i.grid.bDiv)[0].scrollHeight || 1 === i.rows.length || "scroll" === $(i.grid.bDiv).css("overflow-y")) && (s = !0, r -= d); var u, h = (a = 0) < i.grid.cols.length; if ($.each(i.p.colModel, function (e) { !1 !== this.hidden || this.fixed || (g = this.widthOrg, (g = Math.round(r * g / (i.p.tblwidth - n * l - p))) < 0 || (this.width = g, a += g, i.grid.headers[e].width = g, i.grid.headers[e].el.style.width = g + "px", i.p.footerrow && (i.grid.footers[e].style.width = g + "px"), i.p.headerrow && (i.grid.hrheaders[e].style.width = g + "px"), h && (i.grid.cols[e].style.width = g + "px"), t = e)) }), !t) return; u = 0, s ? v - p - (a + n * l) !== d && (u = v - p - (a + n * l) - d) : s || 0 === Math.abs(v - p - (a + n * l)) || (u = v - p - (a + n * l) - c), i.p.colModel[t].width += u, i.p.tblwidth = a + u + n * l + p, i.p.tblwidth > v ? (u = i.p.tblwidth - parseInt(v, 10), i.p.tblwidth = v, g = i.p.colModel[t].width = i.p.colModel[t].width - u) : i.p.tblwidth === v ? (g = i.p.colModel[t].width = i.p.colModel[t].width - c, i.p.tblwidth = v - c) : g = i.p.colModel[t].width; var c = $(i.grid.bDiv)[0].scrollWidth > $(i.grid.bDiv).width() && 0 != c ? -1 : 0, g = i.p.colModel[t].width += c; i.grid.headers[t].width = g, i.grid.headers[t].el.style.width = g + "px", h && (i.grid.cols[t].style.width = g + "px"), i.p.footerrow && (i.grid.footers[t].style.width = g + "px"), i.p.headerrow && (i.grid.hrheaders[t].style.width = g + "px") } if ($("table:first", i.grid.bDiv).css("width", i.p.tblwidth + "px"), $("table:first", i.grid.hDiv).css("width", i.p.tblwidth + "px"), i.grid.hDiv.scrollLeft = i.grid.bDiv.scrollLeft, i.p.footerrow && $("table:first", i.grid.sDiv).css("width", i.p.tblwidth + "px"), i.p.headerrow && $("table:first", i.grid.hrDiv).css("width", i.p.tblwidth + "px"), e) { var f = $.extend([], i.p.groupHeader); i.p.groupHeader = null; for (var m = 0; m < f.length; m++)$(i).jqGrid("setGroupHeaders", f[m]); i.grid.hDiv.scrollLeft = i.grid.bDiv.scrollLeft } o && $(i).jqGrid("setFrozenColumns") } } }) }, setGridHeight: function (i, o) { return this.each(function () { var e, t, r = this; r.grid && (o = o || !1, e = $(r.grid.bDiv), t = $(r.grid.hDiv).outerHeight(), !0 === o && (r.p.pager && (t += $(r.p.pager).outerHeight()), r.p.toppager && (t += $(r.p.toppager).outerHeight()), !0 === r.p.toolbar[0] && (t += $(r.grid.uDiv).outerHeight(), "both" === r.p.toolbar[1] && (t += $(r.grid.ubDiv).outerHeight())), r.p.footerrow && (t += $(r.grid.sDiv).outerHeight()), r.p.headerrow && (t += $(r.grid.hrDiv).outerHeight()), r.p.caption && (t += $(r.grid.cDiv).outerHeight()), t < i && (i -= t)), e.css({ height: i + (isNaN(i) ? "" : "px") }), !0 === r.p.frozenColumns && $("#" + $.jgrid.jqID(r.p.id) + "_frozen").parent().height(e.height() - 16), r.p.height = i, r.p.scroll && r.grid.populateVisible()) }) }, maxGridHeight: function (e, o) { return this.each(function () { var i = this; i.grid && ("set" === e && 25 < o ? $(i).on("jqGridAfterGridComplete.setMaxHeght", function (e) { $(i.grid.bDiv); var t = $.jgrid.jqID(i.p.id), r = $("#gbox_" + t).outerHeight(), t = $(i.grid.hDiv).outerHeight(); i.p.pager && (t += $(i.p.pager).outerHeight()), i.p.toppager && (t += $(i.p.toppager).outerHeight()), !0 === i.p.toolbar[0] && (t += $(i.grid.uDiv).outerHeight(), "both" === i.p.toolbar[1] && (t += $(i.grid.ubDiv).outerHeight())), i.p.footerrow && (t += $(i.grid.sDiv).outerHeight()), i.p.headerrow && (t += $(i.grid.hrDiv).outerHeight()), i.p.caption && (t += $(i.grid.cDiv).outerHeight()), t < r && $(i.grid.bDiv).css("max-height", o - 2) }) : "remove" === e && ($(i).off("jqGridAfterGridComplete.setMaxHeght"), $(i.grid.bDiv).css("max-height", ""))) }) }, setCaption: function (t) { return this.each(function () { var e = $(this).jqGrid("getStyleUI", this.p.styleUI + ".common", "cornertop", !0); this.p.caption = t, $(".ui-jqgrid-title, .ui-jqgrid-title-rtl", this.grid.cDiv).html(t), $(this.grid.cDiv).show(), $(this.grid.hDiv).removeClass(e) }) }, setLabel: function (i, o, a, n) { return this.each(function () { var e, t, r = -1; this.grid && null != i && (isNaN(i) ? $(this.p.colModel).each(function (e) { if (this.name === i) return r = e, !1 }) : r = parseInt(i, 10), 0 <= r && (e = $("tr.ui-jqgrid-labels th:eq(" + r + ")", this.grid.hDiv), o && (t = $(".s-ico", e), $("[id^=jqgh_]", e).empty().html(o).append(t), this.p.colNames[r] = o), a && ("string" == typeof a ? $(e).addClass(a) : $(e).css(a)), "object" == typeof n && $(e).attr(n))) }) }, setSortIcon: function (l, s) { return this.each(function () { var e, t, r, i = this, o = -1, a = 1; if (i.grid) { null != s ? isNaN(s) ? $(i.p.colModel).each(function (e) { if (this.name === s) return o = e, !1 }) : o = parseInt(s, 10) : a = i.p.colNames.length; for (var n = 0; n < a; n++)0 <= o && (n = o), "cb" !== (r = i.p.colModel[n].name) && "subgrid" !== r && "rn" !== r && (e = $("tr.ui-jqgrid-labels th:eq(" + n + ")", i.grid.hDiv), t = i.p.colNames[n], r = e.find(".s-ico"), "left" === l ? e.find("div.ui-th-div:first").empty().addClass("ui-icon-left").append(r).append(t) : "right" === l && e.find("div.ui-th-div:first").empty().removeClass("ui-icon-left").append(t).append(r)) } }) }, setCell: function (l, s, d, p, c, u) { return this.each(function () { var e, t, r = this, i = -1; if (r.grid && (isNaN(s) ? $(r.p.colModel).each(function (e) { if (this.name === s) return i = e, !1 }) : i = parseInt(s, 10), 0 <= i && (t = $(r).jqGrid("getGridRowById", l)))) { var o, a, n = {}; try { o = t.cells[i] } catch (e) { } o && ("" === d && !0 !== u || ((n = $(r).jqGrid("getRowData", l, "local" === r.p.datatype))[r.p.colModel[i].name] = d, a = r.formatter(l, d, i, n, "edit"), n = r.formatCol(i, t.rowIndex, a, n, l, n), e = $('<td role="gridcell" ' + n + ">" + a + "</td>")[0], $(o).after(e).remove(), r.p.treeGrid && r.p.ExpandColumn === s && $(r).jqGrid("setTreeNode", t.rowIndex, t.rowIndex + 1), "local" === r.p.datatype && (n = r.p.colModel[i], d = n.formatter && "string" == typeof n.formatter && "date" === n.formatter ? $.unformat.date.call(r, d, n) : d, void 0 !== (a = r.p._index[$.jgrid.stripPref(r.p.idPrefix, l)]) && (r.p.data[a][n.name] = d))), "string" == typeof p ? $(e).addClass(p) : p && $(e).css(p), "object" == typeof c && $(e).attr(c)) } }) }, getCell: function (o, a, n) { var l, s = !1; return void 0 === n && (n = !1), this.each(function () { var t, e, r = this, i = -1; if (r.grid && (t = a, isNaN(a) ? $(r.p.colModel).each(function (e) { if (this.name === a) return t = this.name, i = e, !1 }) : i = parseInt(a, 10), 0 <= i && (e = $(r).jqGrid("getGridRowById", o)))) if (l = $("td:eq(" + i + ")", e), n) s = l; else { try { s = $.unformat.call(r, l, { rowId: e.id, colModel: r.p.colModel[i] }, i) } catch (e) { s = $.jgrid.htmlDecode(l.html()) } r.p.treeGrid && s && r.p.ExpandColumn === t && (s = $("<div>" + s + "</div>").find("span:first").html()) } }), s }, getCol: function (a, n, l) { var s, d, p, c, u = [], h = 0; n = "boolean" == typeof n && n, void 0 === l && (l = !1); var g = $.jgrid.getFont(this[0]); return this.each(function () { var t = this, r = -1; if (t.grid && (isNaN(a) ? $(t.p.colModel).each(function (e) { if (this.name === a) return r = e, !1 }) : r = parseInt(a, 10), 0 <= r)) { var e = t.rows.length, i = 0, o = 0; if (e && 0 < e) { for (; i < e; i++)if ($(t.rows[i]).hasClass("jqgrow")) if ("maxwidth" !== l) { try { s = $.unformat.call(t, $(t.rows[i].cells[r]), { rowId: t.rows[i].id, colModel: t.p.colModel[r] }, r) } catch (e) { s = $.jgrid.htmlDecode(t.rows[i].cells[r].innerHTML) } l ? (c = parseFloat(s), isNaN(c) || (h += c, void 0 === p && (p = d = c), d = Math.min(d, c), p = Math.max(p, c), o++)) : n ? u.push({ id: t.rows[i].id, value: s }) : u.push(s) } else void 0 === p && (p = 0), p = Math.max($.jgrid.getTextWidth(t.rows[i].cells[r].innerHTML, g), p); if (l) switch (l.toLowerCase()) { case "sum": u = h; break; case "avg": u = h / o; break; case "count": u = e - 1; break; case "min": u = d; break; case "max": u = p; break; case "maxwidth": u = p } } } }), u }, clearGridData: function (r, i) { return this.each(function () { var e, t = this; t.grid && ("boolean" != typeof r && (r = !1), "boolean" != typeof i && (i = !1), t.p.deepempty ? $("#" + $.jgrid.jqID(t.p.id) + " tbody:first tr:gt(0)").remove() : (e = $("#" + $.jgrid.jqID(t.p.id) + " tbody:first tr:first")[0], $("#" + $.jgrid.jqID(t.p.id) + " tbody:first").empty().append(e)), t.p.footerrow && r && $(".ui-jqgrid-ftable td", t.grid.sDiv).html("&#160;"), t.p.headerrow && i && $(".ui-jqgrid-hrtable td", t.grid.hrDiv).html("&#160;"), t.p.selrow = null, t.p.selarrrow = [], t.p.savedRow = [], t.p.records = 0, t.p.page = 1, t.p.lastpage = 0, t.p.reccount = 0, t.p.data = [], t.p._index = {}, t.p.groupingView._locgr = !1, t.updatepager(!0, !1)) }) }, getInd: function (e, t) { var r, i = !1; return this.each(function () { (r = $(this).jqGrid("getGridRowById", e)) && (i = !0 === t ? r : r.rowIndex) }), i }, bindKeys: function (e) { var s = $.extend({ onEnter: null, onSpace: null, onLeftKey: null, onRightKey: null, scrollingRows: !0 }, e || {}); return this.each(function () { var l = this; $("body").is("[role]") || $("body").attr("role", "application"), l.p.scrollrows = s.scrollingRows, $(l).on("keydown", function (e) { var t, r, i = $(l).find("tr[tabindex=0]")[0], o = l.p.treeReader.expanded_field; if (i) { var a = l.p.selrow, n = l.p._index[$.jgrid.stripPref(l.p.idPrefix, i.id)]; if (37 === e.keyCode || 38 === e.keyCode || 39 === e.keyCode || 40 === e.keyCode) { if (38 === e.keyCode) { if (t = "", (r = i.previousSibling) && $(r).hasClass("jqgrow")) { if ($(r).is(":hidden")) { for (; r;)if (r = r.previousSibling, !$(r).is(":hidden") && $(r).hasClass("jqgrow")) { t = r.id; break } } else t = r.id; $(l).jqGrid("setSelection", t, !0, e) } $(l).triggerHandler("jqGridKeyUp", [t, a, e]), $.isFunction(s.onUpKey) && s.onUpKey.call(l, t, a, e), e.preventDefault() } if (40 === e.keyCode) { if (t = "", (r = i.nextSibling) && $(r).hasClass("jqgrow")) { if ($(r).is(":hidden")) { for (; r;)if (r = r.nextSibling, !$(r).is(":hidden") && $(r).hasClass("jqgrow")) { t = r.id; break } } else t = r.id; $(l).jqGrid("setSelection", t, !0, e) } $(l).triggerHandler("jqGridKeyDown", [t, a, e]), $.isFunction(s.onDownKey) && s.onDownKey.call(l, t, a, e), e.preventDefault() } 37 === e.keyCode && (l.p.treeGrid && l.p.data[n][o] && $(i).find("div.treeclick").trigger("click"), $(l).triggerHandler("jqGridKeyLeft", [l.p.selrow, e]), $.isFunction(s.onLeftKey) && s.onLeftKey.call(l, l.p.selrow, e)), 39 === e.keyCode && (l.p.treeGrid && !l.p.data[n][o] && $(i).find("div.treeclick").trigger("click"), $(l).triggerHandler("jqGridKeyRight", [l.p.selrow, e]), $.isFunction(s.onRightKey) && s.onRightKey.call(l, l.p.selrow, e)) } else 13 === e.keyCode ? ($(l).triggerHandler("jqGridKeyEnter", [l.p.selrow, e]), $.isFunction(s.onEnter) && s.onEnter.call(l, l.p.selrow, e)) : 32 === e.keyCode && ($(l).triggerHandler("jqGridKeySpace", [l.p.selrow, e]), $.isFunction(s.onSpace) && s.onSpace.call(l, l.p.selrow, e)) } }).on("click", function (e) { $(e.target).is("input, textarea, select") || $(e.target, l.rows).closest("tr.jqgrow").focus() }) }) }, unbindKeys: function () { return this.each(function () { $(this).off("keydown") }) }, getLocalRow: function (e) { var t, r = !1; return this.each(function () { void 0 !== e && 0 <= (t = this.p._index[$.jgrid.stripPref(this.p.idPrefix, e)]) && (r = this.p.data[t]) }), r }, progressBar: function (o) { return o = $.extend({ htmlcontent: "", method: "hide", loadtype: "disable" }, o || {}), this.each(function () { var e, t = "show" === o.method, r = $("#load_" + $.jgrid.jqID(this.p.id)), i = $(window).scrollTop(); switch ("" !== o.htmlcontent && r.html(o.htmlcontent), o.loadtype) { case "disable": break; case "enable": r.toggle(t); break; case "block": $("#lui_" + $.jgrid.jqID(this.p.id)).css(t ? { top: 0, left: 0, height: $("#gbox_" + $.jgrid.jqID(this.p.id)).height(), width: $("#gbox_" + $.jgrid.jqID(this.p.id)).width(), "z-index": 1e4, position: "absolute" } : {}).toggle(t), r.toggle(t) }r.is(":visible") && (e = r.offsetParent(), r.css("top", ""), r.offset().top < i && (e = Math.min(10 + i - e.offset().top, e.height() - r.height()), r.css("top", e + "px"))) }) }, getColProp: function (e) { var t = {}, r = this[0]; if (!r.grid) return !1; for (var i = r.p.colModel, o = 0; o < i.length; o++)if (i[o].name === e) { t = i[o]; break } return t }, setColProp: function (r, i) { return this.each(function () { if (this.grid && $.isPlainObject(i)) for (var e = this.p.colModel, t = 0; t < e.length; t++)if (e[t].name === r) { $.extend(!0, this.p.colModel[t], i); break } }) }, sortGrid: function (a, n, l) { return this.each(function () { var e, t, r = this, i = -1, o = !1; if (r.grid) { for (a = a || r.p.sortname, e = 0; e < r.p.colModel.length; e++)if (r.p.colModel[e].index === a || r.p.colModel[e].name === a) { i = e, !0 === r.p.frozenColumns && !0 === r.p.colModel[e].frozen && (o = r.grid.fhDiv.find("#" + r.p.id + "_" + a)); break } -1 !== i && (t = r.p.colModel[i].sortable, o = o || r.grid.headers[i].el, "boolean" != typeof t && (t = !0), "boolean" != typeof n && (n = !1), t && r.sortData("jqgh_" + r.p.id + "_" + a, i, n, l, o)) } }) }, setGridState: function (i) { return this.each(function () { var e, t, r; this.grid && (t = $(e = this).jqGrid("getStyleUI", this.p.styleUI + ".base", "icon_caption_open", !0), r = $(this).jqGrid("getStyleUI", this.p.styleUI + ".base", "icon_caption_close", !0), "hidden" === i ? ($(".ui-jqgrid-bdiv, .ui-jqgrid-hdiv", "#gview_" + $.jgrid.jqID(e.p.id)).slideUp("fast"), e.p.pager && $(e.p.pager).slideUp("fast"), e.p.toppager && $(e.p.toppager).slideUp("fast"), !0 === e.p.toolbar[0] && ("both" === e.p.toolbar[1] && $(e.grid.ubDiv).slideUp("fast"), $(e.grid.uDiv).slideUp("fast")), e.p.footerrow && $(".ui-jqgrid-sdiv", "#gbox_" + $.jgrid.jqID(e.p.id)).slideUp("fast"), e.p.headerrow && $(".ui-jqgrid-hrdiv", "#gbox_" + $.jgrid.jqID(e.p.id)).slideUp("fast"), $(".ui-jqgrid-headlink", e.grid.cDiv).removeClass(t).addClass(r), e.p.gridstate = "hidden") : "visible" === i && ($(".ui-jqgrid-hdiv, .ui-jqgrid-bdiv", "#gview_" + $.jgrid.jqID(e.p.id)).slideDown("fast"), e.p.pager && $(e.p.pager).slideDown("fast"), e.p.toppager && $(e.p.toppager).slideDown("fast"), !0 === e.p.toolbar[0] && ("both" === e.p.toolbar[1] && $(e.grid.ubDiv).slideDown("fast"), $(e.grid.uDiv).slideDown("fast")), e.p.footerrow && $(".ui-jqgrid-sdiv", "#gbox_" + $.jgrid.jqID(e.p.id)).slideDown("fast"), e.p.headerrow && $(".ui-jqgrid-hrdiv", "#gbox_" + $.jgrid.jqID(e.p.id)).slideDown("fast"), $(".ui-jqgrid-headlink", e.grid.cDiv).removeClass(r).addClass(t), e.p.gridstate = "visible")) }) }, setFrozenColumns: function () { return this.each(function () { if (this.grid) { var e, t, r, i, o, a, n, l, s, d, p, c = this, u = c.p.colModel, h = 0, g = u.length, f = -1, m = !1, v = $(c).jqGrid("getStyleUI", c.p.styleUI + ".base", "headerDiv", !0, "ui-jqgrid-hdiv"), b = $(c).jqGrid("getStyleUI", c.p.styleUI + ".common", "hover", !0), j = "border-box" === $("#gbox_" + $.jgrid.jqID(c.p.id)).css("box-sizing") ? 1 : 0; if (!0 !== c.p.subGrid && !0 !== c.p.treeGrid && !0 !== c.p.cellEdit && !c.p.scroll) { for (; h < g && !0 === u[h].frozen;)m = !0, f = h, h++; 0 <= f && m && (e = c.p.caption ? $(c.grid.cDiv).outerHeight() : 0, d = 0, t = parseInt($(".ui-jqgrid-htable", "#gview_" + $.jgrid.jqID(c.p.id)).height(), 10), r = parseInt($(".ui-jqgrid-hdiv", "#gview_" + $.jgrid.jqID(c.p.id)).height(), 10), i = $(".ui-jqgrid-bdiv", "#gview_" + $.jgrid.jqID(c.p.id)).position(), c.p.toppager && (e += $(c.grid.topDiv).outerHeight()), !0 === c.p.toolbar[0] && "bottom" !== c.p.toolbar[1] && (e += $(c.grid.uDiv).outerHeight()), c.p.headerrow && (d = parseInt($(".ui-jqgrid-hrdiv", "#gview_" + $.jgrid.jqID(c.p.id)).height(), 10)), c.grid.fhDiv = $('<div style="position:absolute;' + ("rtl" === c.p.direction ? "right:0;" : "left:0;") + "top:" + e + "px;height:" + (r - j) + 'px;" class="frozen-div ' + v + '"></div>'), c.grid.fbDiv = $('<div style="position:absolute;' + ("rtl" === c.p.direction ? "right:0;" : "left:0;") + "top:" + i.top + 'px;overflow-y:hidden" class="frozen-bdiv ui-jqgrid-bdiv"></div>'), $("#gview_" + $.jgrid.jqID(c.p.id)).append(c.grid.fhDiv), v = $(".ui-jqgrid-htable", "#gview_" + $.jgrid.jqID(c.p.id)).clone(!0), i = null, $(c).jqGrid("isGroupHeaderOn") ? (i = $("tr.jqg-third-row-header", c.grid.hDiv).height(), $("tr.jqg-first-row-header, tr.jqg-third-row-header", v).each(function () { $("th:gt(" + f + ")", this).remove() }), a = o = -1, $("tr.jqg-second-row-header th", v).each(function () { if (n = parseInt($(this).attr("colspan"), 10), parseInt($(this).attr("rowspan"), 10) && (o++, a++), n && (o += n, a++), o === f) return a = f, !1 }), o !== f && (a = f), $("tr.jqg-second-row-header", v).each(function () { $("th:gt(" + a + ")", this).remove() })) : (l = [], $(".ui-jqgrid-htable tr", "#gview_" + $.jgrid.jqID(c.p.id)).each(function (e, t) { l.push(parseInt($(this).height(), 10)) }), $("tr", v).each(function () { $("th:gt(" + f + ")", this).remove() }), $("tr", v).each(function (e) { $(this).height(l[e]) })), 0 === $("tr.jqg-second-row-header th:eq(0)", v).text() && $("tr.jqg-second-row-header th:eq(0)", v).prepend("&nbsp;"), "" === $.trim($("tr.jqg-third-row-header th:eq(0)", v).text()) && $("tr.jqg-third-row-header th:eq(0) div", v).prepend("&nbsp;"), i && $("tr.jqg-third-row-header th:eq(0)", v).height(i), $(v).width(1), $.jgrid.msie() || $(v).css("height", "100%"), $(c.grid.fhDiv).append(v).mousemove(function (e) { if (c.grid.resizing) return c.grid.dragMove(e), !1 }), c.p.headerrow && (c.grid.fhrDiv = $('<div style="position:absolute;' + ("rtl" === c.p.direction ? "right:0;" : "left:0;") + "top:" + (parseInt(e, 10) + parseInt(r, 10) + 1 - j) + "px;height:" + (r - j) + 'px;" class="frozen-hrdiv ui-jqgrid-hrdiv "></div>'), $("#gview_" + $.jgrid.jqID(c.p.id)).append(c.grid.fhrDiv), s = $(".ui-jqgrid-hrtable", "#gview_" + $.jgrid.jqID(c.p.id)).clone(!0), $("tr", s).each(function () { $("td:gt(" + f + ")", this).remove() }), $(s).width(1), $(c.grid.fhrDiv).append(s)), c.p.footerrow && (s = $(".ui-jqgrid-bdiv", "#gview_" + $.jgrid.jqID(c.p.id)).height(), c.grid.fsDiv = $('<div style="position:absolute;left:0px;top:' + (parseInt(e, 10) + parseInt(t, 10) + parseInt(s, 10) + 1 - j + parseInt(d, 10)) + 'px;" class="frozen-sdiv ui-jqgrid-sdiv"></div>'), $("#gview_" + $.jgrid.jqID(c.p.id)).append(c.grid.fsDiv), d = $(".ui-jqgrid-ftable", "#gview_" + $.jgrid.jqID(c.p.id)).clone(!0), $("tr", d).each(function () { $("td:gt(" + f + ")", this).remove() }), $(d).width(1), $(c.grid.fsDiv).append(d)), $("#gview_" + $.jgrid.jqID(c.p.id)).append(c.grid.fbDiv), $(c.grid.fbDiv).on("mousewheel DOMMouseScroll", function (e) { var t = $(c.grid.bDiv).scrollTop(); 0 < e.originalEvent.wheelDelta || e.originalEvent.detail < 0 ? $(c.grid.bDiv).scrollTop(t - 25) : $(c.grid.bDiv).scrollTop(t + 25), e.preventDefault() }), !0 === c.p.hoverrows && $("#" + $.jgrid.jqID(c.p.id)).off("mouseover mouseout"), $(c).on("jqGridAfterGridComplete.setFrozenColumns", function () { $("#" + $.jgrid.jqID(c.p.id) + "_frozen").remove(), p = parseInt($(c.grid.bDiv)[0].scrollWidth, 10) > parseInt($(c.grid.bDiv)[0].clientWidth, 10), $(c.grid.fbDiv).height($(c.grid.bDiv)[0].clientHeight - (p ? 0 : c.p.scrollOffset - 3)); var r = []; $("#" + $.jgrid.jqID(c.p.id) + " tr[role=row].jqgrow").each(function () { r.push($(this).height()) }); var e = $("#" + $.jgrid.jqID(c.p.id)).clone(!0); $("tr[role=row]", e).each(function () { $("td[role=gridcell]:gt(" + f + ")", this).remove() }), $(e).width(1).attr("id", c.p.id + "_frozen"), $(c.grid.fbDiv).append(e), $("tr[role=row].jqgrow", e).each(function (e, t) { $(this).height(r[e]) }), "norecs" === c.rows[1].id && $("#norecs td", e).html(""), !0 === c.p.hoverrows && ($("tr.jqgrow", e).hover(function () { $(this).addClass(b), $("#" + $.jgrid.jqID(this.id), "#" + $.jgrid.jqID(c.p.id)).addClass(b) }, function () { $(this).removeClass(b), $("#" + $.jgrid.jqID(this.id), "#" + $.jgrid.jqID(c.p.id)).removeClass(b) }), $("tr.jqgrow", "#" + $.jgrid.jqID(c.p.id)).hover(function () { $(this).addClass(b), $("#" + $.jgrid.jqID(this.id), "#" + $.jgrid.jqID(c.p.id) + "_frozen").addClass(b) }, function () { $(this).removeClass(b), $("#" + $.jgrid.jqID(this.id), "#" + $.jgrid.jqID(c.p.id) + "_frozen").removeClass(b) })) }), c.grid.hDiv.loading || $(c).triggerHandler("jqGridAfterGridComplete"), c.p.frozenColumns = !0) } } }) }, destroyFrozenColumns: function () { return this.each(function () { var e, t, r; this.grid && !0 === this.p.frozenColumns && (t = $(e = this).jqGrid("getStyleUI", e.p.styleUI + ".common", "hover", !0), $(e.grid.fhDiv).remove(), $(e.grid.fbDiv).remove(), e.grid.fhDiv = null, e.grid.fbDiv = null, e.p.footerrow && ($(e.grid.fsDiv).remove(), e.grid.fsDiv = null), e.p.headerrow && ($(e.grid.fhrDiv).remove(), e.grid.fhrDiv = null), $(this).off(".setFrozenColumns"), !0 === e.p.hoverrows && $("#" + $.jgrid.jqID(e.p.id)).on({ mouseover: function (e) { r = $(e.target).closest("tr.jqgrow"), "ui-subgrid" !== $(r).attr("class") && $(r).addClass(t) }, mouseout: function (e) { r = $(e.target).closest("tr.jqgrow"), $(r).removeClass(t) } }), this.p.frozenColumns = !1) }) }, resizeColumn: function (n, l, s) { return this.each(function () { var e, t, r = this.grid, i = this.p, o = i.colModel, a = o.length; if ("string" == typeof n) { for (e = 0; e < a; e++)if (o[e].name === n) { n = e; break } } else n = parseInt(n, 10); if (void 0 === s && (s = !1), (o[n].resizable || s) && (l = parseInt(l, 10), !("number" != typeof n || n < 0 || n > o.length - 1 || "number" != typeof l || l < i.minColWidth))) { if (i.forceFit) for (i.nv = 0, e = n + 1; e < a; e++)if (!0 !== o[e].hidden) { i.nv = e - n; break } if (r.resizing = { idx: n }, t = l - r.headers[n].width, i.forceFit) { if (r.headers[n + i.nv].width - t < i.minColWidth) return; r.headers[n + i.nv].newWidth = r.headers[n + i.nv].width - t } r.newWidth = i.tblwidth + t, r.headers[n].newWidth = l, r.dragEnd(!1) } }) }, getStyleUI: function (e, t, r, i) { var o = "", a = ""; try { var n = e.split("."); switch (r || (o = "class=", a = '"'), null == i && (i = ""), n.length) { case 1: o += a + $.trim(i + " " + $.jgrid.styleUI[n[0]][t] + a); break; case 2: o += a + $.trim(i + " " + $.jgrid.styleUI[n[0]][n[1]][t] + a) } } catch (e) { o = "" } return o }, resizeGrid: function (e = 500, a = !0, n = !0) { return this.each(function () { var o = this; setTimeout(function () { try { var e, t, r, i; a && (i = o.p.height, t = $(window).width(), e = $("#gbox_" + $.jgrid.jqID(o.p.id)).parent().width(), r = o.p.width, r = 3 < t - e ? e : t, $("#" + $.jgrid.jqID(o.p.id)).jqGrid("setGridWidth", r)), n && (e = -1 === o.p.styleUI.search("Bootstrap") || isNaN(o.p.height) ? 0 : 2, i = 3 < (t = $(window).height()) - (r = $("#gbox_" + $.jgrid.jqID(o.p.id)).parent().height()) ? r : t, $("#" + $.jgrid.jqID(o.p.id)).jqGrid("setGridHeight", i - e, !0)) } catch (e) { } }, e) }) }, colMenuAdd: function (e, t) { var r = this[0].p.styleUI, r = $.jgrid.styleUI[r].colmenu; return t = $.extend({ title: "Item", icon: r.icon_new_item, funcname: null, position: "last", closeOnRun: !0, exclude: "", id: null }, t || {}), this.each(function () { t.colname = "all" === e ? "_all_" : e; t.id = null === t.id ? $.jgrid.randId() : t.id, this.p.colMenuCustom[t.id] = t }) }, colMenuDelete: function (e) { return this.each(function () { this.p.colMenuCustom.hasOwnProperty(e) && delete this.p.colMenuCustom[e] }) }, menubarAdd: function (o) { var r, a, e = this[0].p.styleUI, n = $.jgrid.styleUI[e].common; return this.each(function () { var i = this; if ($.isArray(o)) for (var e = 0; e < o.length; e++) { (r = o[e]).id || (r.id = $.jgrid.randId()); var t = ""; r.icon && (t = '<span class="' + n.icon_base + " " + r.icon + '"></span>'), r.position || (r.position = "last"), r.closeoncall || (r.closeoncall = !0), r.divider ? (a = '<li class="ui-menu-item divider" role="separator"></li>', r.cick = null) : a = '<li class="ui-menu-item" role="presentation"><a id="' + r.id + '" class="g-menu-item" tabindex="0" role="menuitem" ><table class="ui-common-table"><tr><td class="menu_icon">' + t + '</td><td class="menu_text">' + r.title + "</td></tr></table></a></li>", "last" === r.position ? $("#" + this.p.id + "_menubar").append(a) : $("#" + this.p.id + "_menubar").prepend(a) } $("li a", "#" + this.p.id + "_menubar").each(function (e, r) { $(o).each(function (e, t) { if (t.id === r.id && $.isFunction(t.click)) return $(r).on("click", function (e) { t.click.call(i, e) }), !1 }), $(this).hover(function (e) { $(this).addClass(n.hover), e.stopPropagation() }, function (e) { $(this).removeClass(n.hover) }) }) }) }, menubarDelete: function (e) { return this.each(function () { $("#" + e, "#" + this.p.id + "_menubar").remove() }) } }), $.jgrid.extend({ editCell: function (c, u, h, g) { return this.each(function () { var e, t, r, i, o, a = this, n = $(this).jqGrid("getStyleUI", a.p.styleUI + ".common", "highlight", !0), l = $(this).jqGrid("getStyleUI", a.p.styleUI + ".common", "hover", !0), s = $(this).jqGrid("getStyleUI", a.p.styleUI + ".celledit", "inputClass", !0); if (a.grid && !0 === a.p.cellEdit) { if (u = parseInt(u, 10), a.p.selrow = a.rows[c].id, a.p.knv || $(a).jqGrid("GridNav"), 0 < a.p.savedRow.length) { if (!0 === h && c == a.p.iRow && u == a.p.iCol) return; $(a).jqGrid("saveCell", a.p.savedRow[0].id, a.p.savedRow[0].ic) } else window.setTimeout(function () { $("#" + $.jgrid.jqID(a.p.knv)).attr("tabindex", "-1").focus() }, 1); if ("subgrid" !== (e = (i = a.p.colModel[u]).name) && "cb" !== e && "rn" !== e) { try { r = $(a.rows[c].cells[u]) } catch (e) { r = $("td:eq(" + u + ")", a.rows[c]) } if (0 <= parseInt(a.p.iCol, 10) && 0 <= parseInt(a.p.iRow, 10) && void 0 !== a.p.iRowId && (o = $(a).jqGrid("getGridRowById", a.p.iRowId), $(o).removeClass("selected-row " + l).find("td:eq(" + a.p.iCol + ")").removeClass("edit-cell " + n)), r.addClass("edit-cell " + n), $(a.rows[c]).addClass("selected-row " + l), !0 !== i.editable || !0 !== h || r.hasClass("not-editable-cell") || $.isFunction(a.p.isCellEditable) && !a.p.isCellEditable.call(a, e, c, u)) t = r.html().replace(/\&#160\;/gi, ""), $(a).triggerHandler("jqGridCellSelect", [a.rows[c].id, u, t, g]), $.isFunction(a.p.onCellSelect) && a.p.onCellSelect.call(a, a.rows[c].id, u, t, g); else { try { t = $.unformat.call(a, r, { rowId: a.rows[c].id, colModel: i }, u) } catch (e) { t = i.edittype && "textarea" === i.edittype ? r.text() : r.html() } a.p.autoencode && (t = $.jgrid.htmlDecode(t)), i.edittype || (i.edittype = "text"), a.p.savedRow.push({ id: c, ic: u, name: e, v: t, rowId: a.rows[c].id }), ("&nbsp;" === t || "&#160;" === t || 1 === t.length && 160 === t.charCodeAt(0)) && (t = ""), !$.isFunction(a.p.formatCell) || void 0 !== (d = a.p.formatCell.call(a, a.rows[c].id, e, t, c, u)) && (t = d), $(a).triggerHandler("jqGridBeforeEditCell", [a.rows[c].id, e, t, c, u]), $.isFunction(a.p.beforeEditCell) && a.p.beforeEditCell.call(a, a.rows[c].id, e, t, c, u); var d = $.extend({}, i.editoptions || {}, { id: c + "_" + e, name: e, rowId: a.rows[c].id, oper: "edit", module: "cell" }), p = $.jgrid.createEl.call(a, i.edittype, d, t, !0, $.extend({}, $.jgrid.ajaxOptions, a.p.ajaxSelectOptions || {})); -1 < $.inArray(i.edittype, ["text", "textarea", "password", "select"]) && $(p).addClass(s), r.html("").append(p).attr("tabindex", "0"), $.jgrid.bindEv.call(a, p, d), window.setTimeout(function () { $(p).focus() }, 1), $("input, select, textarea", r).on("keydown", function (e) { if (27 === e.keyCode && (!(0 < $("input.hasDatepicker", r).length) || $(".ui-datepicker").is(":hidden") ? $(a).jqGrid("restoreCell", c, u) : $("input.hasDatepicker", r).datepicker("hide")), 13 === e.keyCode && e.altKey && "TEXTAREA" === this.nodeName) return this.value = this.value + "\r", !0; if (13 === e.keyCode && !e.shiftKey) return $(a).jqGrid("saveCell", c, u), !1; if (9 === e.keyCode) { if (a.grid.hDiv.loading) return !1; e.shiftKey ? !$(a).jqGrid("prevCell", c, u, e) && a.p.editNextRowCell && 0 < c - 1 && a.rows[c - 1] && (c--, $(a).jqGrid("prevCell", c, a.p.colModel.length, e)) : !$(a).jqGrid("nextCell", c, u, e) && a.p.editNextRowCell && a.rows[c + 1] && (c++, $(a).jqGrid("nextCell", c, 0, e)) } e.stopPropagation() }), $(a).triggerHandler("jqGridAfterEditCell", [a.rows[c].id, e, t, c, u]), $.isFunction(a.p.afterEditCell) && a.p.afterEditCell.call(a, a.rows[c].id, e, t, c, u) } a.p.iCol = u, a.p.iRow = c, a.p.iRowId = a.rows[c].id } } }) }, saveCell: function (w, x) { return this.each(function () { var i = this, o = 1 <= i.p.savedRow.length ? 0 : null, a = $.jgrid.getRegional(this, "errors"), n = $.jgrid.getRegional(this, "edit"); if (i.grid && !0 === i.p.cellEdit) { if (null !== o) { var l = $(i).jqGrid("getGridRowById", i.p.savedRow[0].rowId), s = $("td:eq(" + x + ")", l), e = i.p.colModel[x], d = e.name, p = $.jgrid.jqID(d), c = $(s).offset(); switch (e.edittype) { case "select": var r, u, h = e.editoptions.multiple ? (t = $("#" + w + "_" + p, l), r = [], (u = $(t).val()) ? u.join(",") : u = "", $("option:selected", t).each(function (e, t) { r[e] = $(t).text() }), r.join(",")) : (u = $("#" + w + "_" + p + " option:selected", l).val(), $("#" + w + "_" + p + " option:selected", l).text()); e.formatter && (h = u); break; case "checkbox": var t = ["Yes", "No"]; e.editoptions && e.editoptions.value && (t = e.editoptions.value.split(":")), u = $("#" + w + "_" + p, l).is(":checked") ? t[0] : t[1], h = u; break; case "password": case "text": case "textarea": case "button": u = $("#" + w + "_" + p, l).val(), h = u; break; case "custom": try { if (!e.editoptions || !$.isFunction(e.editoptions.custom_value)) throw "e1"; if (void 0 === (u = e.editoptions.custom_value.call(i, $(".customelement", s), "get"))) throw "e2"; h = u } catch (e) { "e1" === e ? $.jgrid.info_dialog(a.errcap, "function 'custom_value' " + n.msg.nodefined, n.bClose, { styleUI: i.p.styleUI }) : "e2" === e ? $.jgrid.info_dialog(a.errcap, "function 'custom_value' " + n.msg.novalue, n.bClose, { styleUI: i.p.styleUI }) : $.jgrid.info_dialog(a.errcap, e.message, n.bClose, { styleUI: i.p.styleUI }) } }if (h !== i.p.savedRow[o].v) { var g = $(i).triggerHandler("jqGridBeforeSaveCell", [i.p.savedRow[o].rowId, d, u, w, x]); g && (h = u = g), !$.isFunction(i.p.beforeSaveCell) || (j = i.p.beforeSaveCell.call(i, i.p.savedRow[o].rowId, d, u, w, x)) && (h = u = j); var f = $.jgrid.checkValues.call(i, u, x), m = !1; if (!0 === f[0]) { var v = $(i).triggerHandler("jqGridBeforeSubmitCell", [i.p.savedRow[o].rowId, d, u, w, x]) || {}; $.isFunction(i.p.beforeSubmitCell) && (v = (v = i.p.beforeSubmitCell.call(i, i.p.savedRow[o].rowId, d, u, w, x)) || {}); g = $(i).triggerHandler("jqGridOnSubmitCell", [i.p.savedRow[o].rowId, d, u, w, x]); if (void 0 === g && (g = !0), $.isFunction(i.p.onSubmitCell) && void 0 === (g = i.p.onSubmitCell(i.p.savedRow[o].rowId, d, u, w, x)) && (g = !0), !1 === g) return; if (0 < $("input.hasDatepicker", s).length && $("input.hasDatepicker", s).datepicker("hide"), "remote" === i.p.cellsubmit) if (i.p.cellurl) { var b = {}; i.p.autoencode && (u = $.jgrid.htmlEncode(u)), e.editoptions && e.editoptions.NullIfEmpty && "" === u && (u = "null", m = !0), b[d] = u; var j = i.p.prmNames, y = j.id, g = j.oper; b[y] = $.jgrid.stripPref(i.p.idPrefix, i.p.savedRow[o].rowId), b[g] = j.editoper, b = $.extend(v, b), $(i).jqGrid("progressBar", { method: "show", loadtype: i.p.loadui, htmlcontent: $.jgrid.getRegional(i, "defaults.savetext") }), i.grid.hDiv.loading = !0, $.ajax($.extend({ url: i.p.cellurl, data: $.isFunction(i.p.serializeCellData) ? i.p.serializeCellData.call(i, b, d) : b, type: "POST", complete: function (e, t) { var r; $(i).jqGrid("progressBar", { method: "hide", loadtype: i.p.loadui }), i.grid.hDiv.loading = !1, "success" === t && (!0 === (r = $(i).triggerHandler("jqGridAfterSubmitCell", [i, e, b[y], d, u, w, x]) || [!0, ""])[0] && $.isFunction(i.p.afterSubmitCell) && (r = i.p.afterSubmitCell.call(i, e, b[y], d, u, w, x)), !0 === r[0] ? (m && (u = ""), $(s).empty(), $(i).jqGrid("setCell", i.p.savedRow[o].rowId, x, h, !1, !1, !0), s = $("td:eq(" + x + ")", l), $(s).addClass("dirty-cell"), $(l).addClass("edited"), $(i).triggerHandler("jqGridAfterSaveCell", [i.p.savedRow[o].rowId, d, u, w, x]), $.isFunction(i.p.afterSaveCell) && i.p.afterSaveCell.call(i, i.p.savedRow[o].rowId, d, u, w, x), i.p.savedRow.splice(0, 1)) : ($(i).triggerHandler("jqGridErrorCell", [e, t]), $.isFunction(i.p.errorCell) ? i.p.errorCell.call(i, e, t) : $.jgrid.info_dialog(a.errcap, r[1], n.bClose, { styleUI: i.p.styleUI, top: c.top + 30, left: c.left, onClose: function () { i.p.restoreCellonFail || $("#" + w + "_" + p, l).focus() } }), i.p.restoreCellonFail && $(i).jqGrid("restoreCell", w, x))) }, error: function (e, t, r) { $("#lui_" + $.jgrid.jqID(i.p.id)).hide(), i.grid.hDiv.loading = !1, $(i).triggerHandler("jqGridErrorCell", [e, t, r]), $.isFunction(i.p.errorCell) ? i.p.errorCell.call(i, e, t, r) : $.jgrid.info_dialog(a.errcap, e.status + " : " + e.statusText + "<br/>" + t, n.bClose, { styleUI: i.p.styleUI, top: c.top + 30, left: c.left, onClose: function () { i.p.restoreCellonFail || $("#" + w + "_" + p, l).focus() } }), i.p.restoreCellonFail && $(i).jqGrid("restoreCell", w, x) } }, $.jgrid.ajaxOptions, i.p.ajaxCellOptions || {})) } else try { $.jgrid.info_dialog(a.errcap, a.nourl, n.bClose, { styleUI: i.p.styleUI }), i.p.restoreCellonFail && $(i).jqGrid("restoreCell", w, x) } catch (e) { } "clientArray" === i.p.cellsubmit && ($(s).empty(), $(i).jqGrid("setCell", i.p.savedRow[o].rowId, x, h, !1, !1, !0), s = $("td:eq(" + x + ")", l), $(s).addClass("dirty-cell"), $(l).addClass("edited"), $(i).triggerHandler("jqGridAfterSaveCell", [i.p.savedRow[o].rowId, d, u, w, x]), $.isFunction(i.p.afterSaveCell) && i.p.afterSaveCell.call(i, i.p.savedRow[o].rowId, d, u, w, x), i.p.savedRow.splice(0, 1)) } else try { $.isFunction(i.p.validationCell) ? i.p.validationCell.call(i, $("#" + w + "_" + p, l), f[1], w, x) : (window.setTimeout(function () { $.jgrid.info_dialog(a.errcap, u + " " + f[1], n.bClose, { styleUI: i.p.styleUI, top: c.top + 30, left: c.left, onClose: function () { i.p.restoreCellonFail || $("#" + w + "_" + p, l).focus() } }) }, 50), i.p.restoreCellonFail && $(i).jqGrid("restoreCell", w, x)) } catch (e) { alert(f[1]) } } else $(i).jqGrid("restoreCell", w, x) } window.setTimeout(function () { $("#" + $.jgrid.jqID(i.p.knv)).attr("tabindex", "-1").focus() }, 0) } }) }, restoreCell: function (o, a) { return this.each(function () { var e = this, t = 1 <= e.p.savedRow.length ? 0 : null; if (e.grid && !0 === e.p.cellEdit) { if (null !== t) { var r = $(e).jqGrid("getGridRowById", e.p.savedRow[t].rowId), i = $("td:eq(" + a + ")", r); if ($.isFunction($.fn.datepicker)) try { $("input.hasDatepicker", i).datepicker("hide") } catch (e) { } $(i).empty().attr("tabindex", "-1"), $(e).jqGrid("setCell", e.p.savedRow[0].rowId, a, e.p.savedRow[t].v, !1, !1, !0), $(e).triggerHandler("jqGridAfterRestoreCell", [e.p.savedRow[t].rowId, e.p.savedRow[t].v, o, a]), $.isFunction(e.p.afterRestoreCell) && e.p.afterRestoreCell.call(e, e.p.savedRow[t].rowId, e.p.savedRow[t].v, o, a), e.p.savedRow.splice(0, 1) } window.setTimeout(function () { $("#" + e.p.knv).attr("tabindex", "-1").focus() }, 0) } }) }, nextCell: function (i, o, a) { var n; return this.each(function () { var e, t = this, r = !1; if (t.grid && !0 === t.p.cellEdit) { for (e = o + 1; e < t.p.colModel.length; e++)if (!0 === t.p.colModel[e].editable && (!$.isFunction(t.p.isCellEditable) || t.p.isCellEditable.call(t, t.p.colModel[e].name, i, e))) { r = e; break } !1 !== r ? (n = !0, $(t).jqGrid("editCell", i, r, !0, a)) : (n = !1, 0 < t.p.savedRow.length && $(t).jqGrid("saveCell", i, o)) } }), n }, prevCell: function (i, o, a) { var n; return this.each(function () { var e, t = this, r = !1; if (!t.grid || !0 !== t.p.cellEdit) return !1; for (e = o - 1; 0 <= e; e--)if (!0 === t.p.colModel[e].editable && (!$.isFunction(t.p.isCellEditable) || t.p.isCellEditable.call(t, t.p.colModel[e].name, i, e))) { r = e; break } !1 !== r ? (n = !0, $(t).jqGrid("editCell", i, r, !0, a)) : (n = !1, 0 < t.p.savedRow.length && $(t).jqGrid("saveCell", i, o)) }), n }, GridNav: function () { return this.each(function () { var e, t, r, l = this; function i(e, t, r) { var i, o, a, n; "v" === r.substr(0, 1) && (i = $(l.grid.bDiv)[0].clientHeight, n = $(l.grid.bDiv)[0].scrollTop, o = l.rows[e].offsetTop + l.rows[e].clientHeight, a = l.rows[e].offsetTop, "vd" === r && i <= o && ($(l.grid.bDiv)[0].scrollTop = $(l.grid.bDiv)[0].scrollTop + l.rows[e].clientHeight), "vu" === r && a < n && ($(l.grid.bDiv)[0].scrollTop = $(l.grid.bDiv)[0].scrollTop - l.rows[e].clientHeight)), "h" === r && (o = $(l.grid.bDiv)[0].clientWidth, a = $(l.grid.bDiv)[0].scrollLeft, n = l.rows[e].cells[t].offsetLeft + l.rows[e].cells[t].clientWidth, r = l.rows[e].cells[t].offsetLeft, n >= o + parseInt(a, 10) ? $(l.grid.bDiv)[0].scrollLeft = $(l.grid.bDiv)[0].scrollLeft + l.rows[e].cells[t].clientWidth : r < a && ($(l.grid.bDiv)[0].scrollLeft = $(l.grid.bDiv)[0].scrollLeft - l.rows[e].cells[t].clientWidth)) } function o(e, t) { var r, i; if ("lft" === t) for (r = e + 1, i = e; 0 <= i; i--)if (!0 !== l.p.colModel[i].hidden) { r = i; break } if ("rgt" === t) for (r = e - 1, i = e; i < l.p.colModel.length; i++)if (!0 !== l.p.colModel[i].hidden) { r = i; break } return r } l.grid && !0 === l.p.cellEdit && (l.p.knv = l.p.id + "_kn", e = $("<div style='position:fixed;top:0px;width:1px;height:1px;' tabindex='0'><div tabindex='-1' style='width:1px;height:1px;' id='" + l.p.knv + "'></div></div>"), $(e).insertBefore(l.grid.cDiv), $("#" + l.p.knv).focus().keydown(function (e) { switch (r = e.keyCode, "rtl" === l.p.direction && (37 === r ? r = 39 : 39 === r && (r = 37)), r) { case 38: 0 < l.p.iRow - 1 && (i(l.p.iRow - 1, l.p.iCol, "vu"), $(l).jqGrid("editCell", l.p.iRow - 1, l.p.iCol, !1, e)); break; case 40: l.p.iRow + 1 <= l.rows.length - 1 && (i(l.p.iRow + 1, l.p.iCol, "vd"), $(l).jqGrid("editCell", l.p.iRow + 1, l.p.iCol, !1, e)); break; case 37: 0 <= l.p.iCol - 1 && (t = o(l.p.iCol - 1, "lft"), i(l.p.iRow, t, "h"), $(l).jqGrid("editCell", l.p.iRow, t, !1, e)); break; case 39: l.p.iCol + 1 <= l.p.colModel.length - 1 && (t = o(l.p.iCol + 1, "rgt"), i(l.p.iRow, t, "h"), $(l).jqGrid("editCell", l.p.iRow, t, !1, e)); break; case 13: 0 <= parseInt(l.p.iCol, 10) && 0 <= parseInt(l.p.iRow, 10) && $(l).jqGrid("editCell", l.p.iRow, l.p.iCol, !0, e); break; default: return !0 }return !1 })) }) }, getChangedCells: function (a) { var e = []; return a = a || "all", this.each(function () { var i, o = this; o.grid && !0 === o.p.cellEdit && $(o.rows).each(function (t) { var r = {}; $(this).hasClass("edited") && ($("td", this).each(function (e) { if ("cb" !== (i = o.p.colModel[e].name) && "subgrid" !== i) if ("dirty" === a) { if ($(this).hasClass("dirty-cell")) try { r[i] = $.unformat.call(o, this, { rowId: o.rows[t].id, colModel: o.p.colModel[e] }, e) } catch (e) { r[i] = $.jgrid.htmlDecode($(this).html()) } } else try { r[i] = $.unformat.call(o, this, { rowId: o.rows[t].id, colModel: o.p.colModel[e] }, e) } catch (e) { r[i] = $.jgrid.htmlDecode($(this).html()) } }), r.id = this.id, e.push(r)) }) }), e } }), $.extend($.jgrid, { showModal: function (e) { e.w.show() }, closeModal: function (e) { e.w.hide().attr("aria-hidden", "true"), e.o && e.o.remove() }, hideModal: function (e, t) { var r, i, o, a = !(!(t = $.extend({ jqm: !0, gb: "", removemodal: !1, formprop: !1, form: "" }, t || {})).gb || "string" != typeof t.gb || "#gbox_" !== t.gb.substr(0, 6)) && $("#" + t.gb.substr(6))[0]; if (t.onClose) { var n = a ? t.onClose.call(a, e) : t.onClose(e); if ("boolean" == typeof n && !n) return } if (t.formprop && a && t.form && (r = $(e)[0].style.height, n = $(e)[0].style.width, -1 < r.indexOf("px") && (r = parseFloat(r)), -1 < n.indexOf("px") && (n = parseFloat(n)), "edit" === t.form ? (i = "#" + $.jgrid.jqID("FrmGrid_" + t.gb.substr(6)), o = "formProp") : "view" === t.form && (i = "#" + $.jgrid.jqID("ViewGrid_" + t.gb.substr(6)), o = "viewProp"), $(a).data(o, { top: parseFloat($(e).css("top")), left: parseFloat($(e).css("left")), width: n, height: r, dataheight: $(i).height(), datawidth: $(i).width() })), $.fn.jqm && !0 === t.jqm) $(e).attr("aria-hidden", "true").jqmHide(); else { if ("" !== t.gb) try { $(".jqgrid-overlay:first", t.gb).hide() } catch (e) { } try { $(".jqgrid-overlay-modal").hide() } catch (e) { } $(e).hide().attr("aria-hidden", "true") } t.removemodal && $(e).remove() }, findPos: function (e) { e = $(e).offset(); return [e.left, e.top] }, createModal: function (r, e, i, t, o, a, n) { i = $.extend(!0, {}, $.jgrid.jqModal || {}, i); var l = this, s = "rtl" === $(i.gbox).attr("dir"), d = $.jgrid.styleUI[i.styleUI || "jQueryUI"].modal, p = $.jgrid.styleUI[i.styleUI || "jQueryUI"].common, c = document.createElement("div"); n = $.extend({}, n || {}), c.className = "ui-jqdialog " + d.modal, c.id = r.themodal; var u = document.createElement("div"); u.className = "ui-jqdialog-titlebar " + d.header, u.id = r.modalhead, $(u).append("<span class='ui-jqdialog-title'>" + i.caption + "</span>"); var h = $("<a class='ui-jqdialog-titlebar-close " + p.cornerall + "'></a>").hover(function () { h.addClass(p.hover) }, function () { h.removeClass(p.hover) }).append("<span class='" + p.icon_base + " " + d.icon_close + "'></span>"); $(u).append(h), s ? (c.dir = "rtl", $(".ui-jqdialog-title", u).css("float", "right"), $(".ui-jqdialog-titlebar-close", u).css("left", "0.3em")) : (c.dir = "ltr", $(".ui-jqdialog-title", u).css("float", "left"), $(".ui-jqdialog-titlebar-close", u).css("right", "0.3em")); var g = document.createElement("div"); $(g).addClass("ui-jqdialog-content " + d.content).attr("id", r.modalcontent), $(g).append(e), c.appendChild(g), $(c).prepend(u), !0 === a ? $("body").append(c) : "string" == typeof a ? $(a).append(c) : $(c).insertBefore(t), $(c).css(n), void 0 === i.jqModal && (i.jqModal = !0); g = {}; $.fn.jqm && !0 === i.jqModal ? (0 === i.left && 0 === i.top && i.overlay && (n = [], n = $.jgrid.findPos(o), i.left = n[0] + 4, i.top = n[1] + 4), g.top = i.top + "px", g.left = i.left) : 0 === i.left && 0 === i.top || (g.left = i.left, g.top = i.top + "px"), $("a.ui-jqdialog-titlebar-close", u).click(function () { var e = $("#" + $.jgrid.jqID(r.themodal)).data("onClose") || i.onClose, t = $("#" + $.jgrid.jqID(r.themodal)).data("gbox") || i.gbox; return l.hideModal("#" + $.jgrid.jqID(r.themodal), { gb: t, jqm: i.jqModal, onClose: e, removemodal: i.removemodal || !1, formprop: !i.recreateForm || !1, form: i.form || "" }), !1 }), 0 !== i.width && i.width || (i.width = 300), 0 !== i.height && i.height || (i.height = 200), i.zIndex || (f = $(t).parents("*[role=dialog]").filter(":first").css("z-index"), i.zIndex = f ? parseInt(f, 10) + 2 : 950); var f = 0; if (s && g.hasOwnProperty("left") && !a && (f = $(i.gbox).outerWidth() - (isNaN(i.width) ? 0 : parseInt(i.width, 10)) + 12, g.left = parseInt(g.left, 10) + parseInt(f, 10)), g.hasOwnProperty("left") && (g.left += "px"), $(c).css($.extend({ width: isNaN(i.width) ? "auto" : i.width + "px", height: isNaN(i.height) ? "auto" : i.height + "px", zIndex: i.zIndex, overflow: "hidden" }, g)).attr({ tabIndex: "-1", role: "dialog", "aria-labelledby": r.modalhead, "aria-hidden": "true" }), void 0 === i.drag && (i.drag = !0), void 0 === i.resize && (i.resize = !0), i.drag) if ($(u).css("cursor", "move"), $.fn.tinyDraggable) $(c).tinyDraggable({ handle: "#" + $.jgrid.jqID(u.id) }); else try { $(c).draggable({ handle: $("#" + $.jgrid.jqID(u.id)) }) } catch (e) { } if (i.resize) if ($.fn.jqResize) $(c).append("<div class='jqResize " + d.resizable + " " + p.icon_base + " " + d.icon_resizable + "'></div>"), $("#" + $.jgrid.jqID(r.themodal)).jqResize(".jqResize", !!r.scrollelm && "#" + $.jgrid.jqID(r.scrollelm)); else try { $(c).resizable({ handles: "se, sw", alsoResize: !!r.scrollelm && "#" + $.jgrid.jqID(r.scrollelm) }) } catch (e) { } !0 === i.closeOnEscape && $(c).keydown(function (e) { 27 === e.which && (e = $("#" + $.jgrid.jqID(r.themodal)).data("onClose") || i.onClose, l.hideModal("#" + $.jgrid.jqID(r.themodal), { gb: i.gbox, jqm: i.jqModal, onClose: e, removemodal: i.removemodal || !1, formprop: !i.recreateForm || !1, form: i.form || "" })) }) }, viewModal: function (e, t) { var r, i = ""; if ((t = $.extend({ toTop: !0, overlay: 10, modal: !1, overlayClass: "ui-widget-overlay", onShow: $.jgrid.showModal, onHide: $.jgrid.closeModal, gbox: "", jqm: !0, jqM: !0 }, t || {})).gbox) { var o = $("#" + t.gbox.substring(6))[0]; try { i = $(o).jqGrid("getStyleUI", o.p.styleUI + ".common", "overlay", !1, "jqgrid-overlay-modal"), t.overlayClass = $(o).jqGrid("getStyleUI", o.p.styleUI + ".common", "overlay", !0) } catch (e) { } } if (void 0 === t.focusField && (t.focusField = 0), "number" == typeof t.focusField && 0 <= t.focusField ? t.focusField = parseInt(t.focusField, 10) : "boolean" != typeof t.focusField || t.focusField ? t.focusField = 0 : t.focusField = !1, $.fn.jqm && !0 === t.jqm) (t.jqM ? $(e).attr("aria-hidden", "false").jqm(t) : $(e).attr("aria-hidden", "false")).jqmShow(); else if ("" !== t.gbox && (r = parseInt($(e).css("z-index")) - 1, t.modal ? ($(".jqgrid-overlay-modal")[0] || $("body").prepend("<div " + i + "></div>"), $(".jqgrid-overlay-modal").css("z-index", r).show()) : ($(".jqgrid-overlay:first", t.gbox).css("z-index", r).show(), $(e).data("gbox", t.gbox))), $(e).show().attr("aria-hidden", "false"), 0 <= t.focusField) try { $(":input:visible", e)[t.focusField].focus() } catch (e) { } }, info_dialog: function (e, t, r, i) { var o = { width: 290, height: "auto", dataheight: "auto", drag: !0, resize: !1, left: 250, top: 170, zIndex: 1e3, jqModal: !0, modal: !1, closeOnEscape: !0, align: "center", buttonalign: "center", buttons: [] }; $.extend(!0, o, $.jgrid.jqModal || {}, { caption: "<b>" + e + "</b>" }, i || {}); var a = o.jqModal, n = this, e = $.jgrid.styleUI[o.styleUI || "jQueryUI"].modal, l = $.jgrid.styleUI[o.styleUI || "jQueryUI"].common; $.fn.jqm && !a && (a = !1); var s, d = ""; if (0 < o.buttons.length) for (s = 0; s < o.buttons.length; s++)void 0 === o.buttons[s].id && (o.buttons[s].id = "info_button_" + s), d += "<a id='" + o.buttons[s].id + "' class='fm-button " + l.button + "'>" + o.buttons[s].text + "</a>"; i = "<div id='info_id'>"; i += "<div id='infocnt' style='margin:0px;padding-bottom:1em;width:100%;overflow:auto;position:relative;height:" + (isNaN(o.dataheight) ? o.dataheight : o.dataheight + "px") + ";" + ("text-align:" + o.align + ";") + "'>" + t + "</div>", i += r ? "<div class='" + e.content + "' style='text-align:" + o.buttonalign + ";padding-bottom:0.8em;padding-top:0.5em;background-image: none;border-width: 1px 0 0 0;'><a id='closedialog' class='fm-button " + l.button + "'>" + r + "</a>" + d + "</div>" : "" !== d ? "<div class='" + e.content + "' style='text-align:" + o.buttonalign + ";padding-bottom:0.8em;padding-top:0.5em;background-image: none;border-width: 1px 0 0 0;'>" + d + "</div>" : "", i += "</div>"; try { "false" === $("#info_dialog").attr("aria-hidden") && $.jgrid.hideModal("#info_dialog", { jqm: a }), $("#info_dialog").remove() } catch (e) { } e = $(".ui-jqgrid").css("font-size") || "11px"; $.jgrid.createModal({ themodal: "info_dialog", modalhead: "info_head", modalcontent: "info_content", scrollelm: "infocnt" }, i, o, "", "", !0, { "font-size": e }), d && $.each(o.buttons, function (e) { $("#" + $.jgrid.jqID(this.id), "#info_id").on("click", function () { return o.buttons[e].onClick.call($("#info_dialog")), !1 }) }), $("#closedialog", "#info_id").on("click", function () { return n.hideModal("#info_dialog", { jqm: a, onClose: $("#info_dialog").data("onClose") || o.onClose, gb: $("#info_dialog").data("gbox") || o.gbox }), !1 }), $(".fm-button", "#info_dialog").hover(function () { $(this).addClass(l.hover) }, function () { $(this).removeClass(l.hover) }), $.isFunction(o.beforeOpen) && o.beforeOpen(), $.jgrid.viewModal("#info_dialog", { onHide: function (e) { e.w.hide().remove(), e.o && e.o.remove() }, modal: o.modal, jqm: a }), $.isFunction(o.afterOpen) && o.afterOpen(); try { $("#info_dialog").focus() } catch (e) { } }, bindEv: function (e, t) { $.isFunction(t.dataInit) && t.dataInit.call(this, e, t), t.dataEvents && $.each(t.dataEvents, function () { void 0 !== this.data ? $(e).on(this.type, this.data, this.fn) : $(e).on(this.type, this.fn) }) }, createEl: function (e, t, r, i, o) { var a, n = "", c = this; function u(r, e, t) { var i = (i = ["dataInit", "dataEvents", "dataUrl", "buildSelect", "sopt", "searchhidden", "defaultValue", "attr", "custom_element", "custom_value", "oper"]).concat(["cacheUrlData", "delimiter", "separator"]); void 0 !== t && $.isArray(t) && $.merge(i, t), $.each(e, function (e, t) { -1 === $.inArray(e, i) && $(r).attr(e, t) }), e.hasOwnProperty("id") || $(r).attr("id", $.jgrid.randId()) } switch (e) { case "textarea": n = document.createElement("textarea"), i ? t.cols || $(n).css({ width: "98%" }) : t.cols || (t.cols = 20), t.rows || (t.rows = 2), ("&nbsp;" === r || "&#160;" === r || 1 === r.length && 160 === r.charCodeAt(0)) && (r = ""), n.value = r, $(n).attr({ role: "textbox", multiline: "true" }), u(n, t); break; case "checkbox": (n = document.createElement("input")).type = "checkbox", t.value ? (r === (a = t.value.split(":"))[0] && (n.checked = !0, n.defaultChecked = !0), n.value = a[0], $(n).attr("offval", a[1])) : ((a = (r + "").toLowerCase()).search(/(false|f|0|no|n|off|undefined)/i) < 0 && "" !== a ? (n.checked = !0, n.defaultChecked = !0, n.value = r) : n.value = "on", $(n).attr("offval", "off")), $(n).attr("role", "checkbox"), u(n, t, ["value"]); break; case "select": (n = document.createElement("select")).setAttribute("role", "select"); var l, s, d = []; if (!0 === t.multiple ? (l = !0, n.multiple = "multiple", $(n).attr("aria-multiselectable", "true")) : l = !1, null != t.dataUrl) { var p = null, h = t.postData || o.postData; try { p = t.rowId } catch (e) { } c.p && c.p.idPrefix && (p = $.jgrid.stripPref(c.p.idPrefix, p)), $.ajax($.extend({ url: $.isFunction(t.dataUrl) ? t.dataUrl.call(c, p, r, String(t.name)) : t.dataUrl, type: "GET", dataType: "html", data: $.isFunction(h) ? h.call(c, p, r, String(t.name)) : h, context: { elem: n, options: t, vl: r }, success: function (e) { var t, r, i = [], o = this.elem, a = this.vl, n = $.extend({}, this.options), l = !0 === n.multiple, s = !0 === n.cacheUrlData, d = "", p = [], e = $.isFunction(n.buildSelect) ? n.buildSelect.call(c, e) : e; "string" == typeof e && (e = $($.trim(e)).html()), e && ($(o).append(e), u(o, n, h ? ["postData"] : void 0), void 0 === n.size && (n.size = l ? 3 : 1), l ? (i = a.split(","), i = $.map(i, function (e) { return $.trim(e) })) : i[0] = $.trim(a), $("option", o).each(function (e) { t = $(this).text(), a = $(this).val(), s && (d += (0 !== e ? ";" : "") + a + ":" + t), 0 === e && o.multiple && (this.selected = !1), $(this).attr("role", "option"), (-1 < $.inArray($.trim(t), i) || -1 < $.inArray($.trim(a), i)) && (this.selected = "selected", p.push(a)) }), n.hasOwnProperty("checkUpdate") && n.checkUpdate && (c.p.savedData[n.name] = p.join(",")), s && ("edit" === n.oper ? $(c).jqGrid("setColProp", n.name, { editoptions: { buildSelect: null, dataUrl: null, value: d } }) : "search" === n.oper ? $(c).jqGrid("setColProp", n.name, { searchoptions: { dataUrl: null, value: d } }) : "filter" === n.oper && $("#fbox_" + c.p.id)[0].p && (l = $("#fbox_" + c.p.id)[0].p.columns, $.each(l, function (e) { if (r = this.index || this.name, n.name === r) return this.searchoptions.dataUrl = null, this.searchoptions.value = d, !1 }))), $(c).triggerHandler("jqGridAddEditAfterSelectUrlComplete", [o])) } }, o || {})) } else if (t.value) { void 0 === t.size && (t.size = l ? 3 : 1), l && (d = r.split(","), d = $.map(d, function (e) { return $.trim(e) })), "function" == typeof t.value && (t.value = t.value()); var g, f, m, v, b, j, y = void 0 === t.separator ? ":" : t.separator, w = void 0 === t.delimiter ? ";" : t.delimiter; if ("string" == typeof t.value) for (g = t.value.split(w), s = 0; s < g.length; s++)2 < (f = g[s].split(y)).length && (f[1] = $.map(f, function (e, t) { if (0 < t) return e }).join(y)), (m = document.createElement("option")).setAttribute("role", "option"), m.value = f[0], m.innerHTML = f[1], n.appendChild(m), l || $.trim(f[0]) !== $.trim(r) && $.trim(f[1]) !== $.trim(r) || (m.selected = "selected"), l && (-1 < $.inArray($.trim(f[1]), d) || -1 < $.inArray($.trim(f[0]), d)) && (m.selected = "selected"); else if ("[object Array]" === Object.prototype.toString.call(t.value)) for (v = t.value, s = 0; s < v.length; s++)2 === v[s].length && (b = v[s][0], j = v[s][1], (m = document.createElement("option")).setAttribute("role", "option"), m.value = b, m.innerHTML = j, n.appendChild(m), l || $.trim(b) !== $.trim(r) && $.trim(j) !== $.trim(r) || (m.selected = "selected"), l && (-1 < $.inArray($.trim(j), d) || -1 < $.inArray($.trim(b), d)) && (m.selected = "selected")); else if ("object" == typeof t.value) for (b in v = t.value) v.hasOwnProperty(b) && ((m = document.createElement("option")).setAttribute("role", "option"), m.value = b, m.innerHTML = v[b], n.appendChild(m), l || $.trim(b) !== $.trim(r) && $.trim(v[b]) !== $.trim(r) || (m.selected = "selected"), l && (-1 < $.inArray($.trim(v[b]), d) || -1 < $.inArray($.trim(b), d)) && (m.selected = "selected")); u(n, t, ["value"]) } else u(n, t); break; case "image": case "file": (n = document.createElement("input")).type = e, u(n, t); break; case "custom": n = document.createElement("span"); try { if (!$.isFunction(t.custom_element)) throw "e1"; var x = t.custom_element.call(c, r, t); if (!x) throw "e2"; x = $(x).addClass("customelement").attr({ id: t.id, name: t.name }), $(n).empty().append(x) } catch (e) { var w = $.jgrid.getRegional(c, "errors"), _ = $.jgrid.getRegional(c, "edit"); "e1" === e ? $.jgrid.info_dialog(w.errcap, "function 'custom_element' " + _.msg.nodefined, _.bClose, { styleUI: c.p.styleUI }) : "e2" === e ? $.jgrid.info_dialog(w.errcap, "function 'custom_element' " + _.msg.novalue, _.bClose, { styleUI: c.p.styleUI }) : $.jgrid.info_dialog(w.errcap, "string" == typeof e ? e : e.message, _.bClose, { styleUI: c.p.styleUI }) } break; default: _ = "button" === e ? "button" : "textbox"; (n = document.createElement("input")).type = e, n.value = r, "button" !== e && (i ? t.size || $(n).css({ width: "96%" }) : t.size || (t.size = 20)), $(n).attr("role", _), u(n, t) }return n }, checkDate: function (e, t) { var r = {}, i = -1 !== (e = e.toLowerCase()).indexOf("/") ? "/" : -1 !== e.indexOf("-") ? "-" : -1 !== e.indexOf(".") ? "." : "/"; if (e = e.split(i), 3 !== (t = t.split(i)).length) return !1; for (var o, a = -1, n = -1, l = -1, s = 0; s < e.length; s++) { var d = isNaN(t[s]) ? 0 : parseInt(t[s], 10); r[e[s]] = d, -1 !== (o = e[s]).indexOf("y") && (a = s), -1 !== o.indexOf("m") && (l = s), -1 !== o.indexOf("d") && (n = s) } o = "y" === e[a] || "yyyy" === e[a] ? 4 : "yy" === e[a] ? 2 : -1; var p; return -1 !== a && (i = r[e[a]].toString(), 2 === o && 1 === i.length && (o = 1), i.length === o && (0 !== r[e[a]] || "00" === t[a]) && (-1 !== l && (!((i = r[e[l]].toString()).length < 1 || r[e[l]] < 1 || 12 < r[e[l]]) && (-1 !== n && !((i = r[e[n]].toString()).length < 1 || r[e[n]] < 1 || 31 < r[e[n]] || 2 === r[e[l]] && r[e[n]] > ((p = r[e[a]]) % 4 != 0 || p % 100 == 0 && p % 400 != 0 ? 28 : 29) || r[e[n]] > [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][r[e[l]]]))))) }, isEmpty: function (e) { return !(void 0 !== e && !e.match(/^\s+$/) && "" !== e) }, checkTime: function (e) { if (!$.jgrid.isEmpty(e)) { if (!(e = e.match(/^(\d{1,2}):(\d{2})([apAP][Mm])?$/))) return !1; if (e[3]) { if (e[1] < 1 || 12 < e[1]) return !1 } else if (23 < e[1]) return !1; if (59 < e[2]) return !1 } return !0 }, checkValues: function (e, t, r, i) { var o, a, n, l, s, d = this, p = d.p.colModel, c = $.jgrid.getRegional(this, "edit.msg"), u = function (e) { var t, r, e = e.toString(); if (2 <= e.length && ("-" === e[0] ? (t = e[1], e[2] && (r = e[2])) : (t = e[0], e[1] && (r = e[1])), "0" === t && "." !== r)) return !1; return "number" == typeof parseFloat(e) && isFinite(e) }; if (void 0 === r) if ("string" == typeof t) { for (a = 0, s = p.length; a < s; a++)if (p[a].name === t) { o = p[a].editrules, null != p[t = a].formoptions && (n = p[a].formoptions.label); break } } else 0 <= t && (o = p[t].editrules); else o = r, n = void 0 === i ? "_" : i; if (o) { if (n = n || (null != d.p.colNames ? d.p.colNames[t] : p[t].label), !0 === o.required && $.jgrid.isEmpty(e)) return [!1, n + ": " + c.required, ""]; i = !1 !== o.required; if (!0 === o.number && !(!1 == i && $.jgrid.isEmpty(e) || u(e))) return [!1, n + ": " + c.number, ""]; if (void 0 !== o.minValue && !isNaN(o.minValue) && parseFloat(e) < parseFloat(o.minValue)) return [!1, n + ": " + c.minValue + " " + o.minValue, ""]; if (void 0 !== o.maxValue && !isNaN(o.maxValue) && parseFloat(e) > parseFloat(o.maxValue)) return [!1, n + ": " + c.maxValue + " " + o.maxValue, ""]; if (!0 === o.email && !(!1 == i && $.jgrid.isEmpty(e) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(e))) return [!1, n + ": " + c.email, ""]; if (!0 === o.integer && (!1 != i || !$.jgrid.isEmpty(e))) { if (!u(e)) return [!1, n + ": " + c.integer, ""]; if (e % 1 != 0 || -1 !== e.indexOf(".")) return [!1, n + ": " + c.integer, ""] } if (!0 === o.date && !(!1 == i && $.jgrid.isEmpty(e) || (p[t].formatoptions && p[t].formatoptions.newformat ? (l = p[t].formatoptions.newformat, (u = $.jgrid.getRegional(d, "formatter.date.masks")) && u.hasOwnProperty(l) && (l = u[l])) : l = p[t].datefmt || "Y-m-d", $.jgrid.checkDate(l, e)))) return [!1, n + ": " + c.date + " - " + l, ""]; if (!0 === o.time && !(!1 == i && $.jgrid.isEmpty(e) || $.jgrid.checkTime(e))) return [!1, n + ": " + c.date + " - hh:mm (am/pm)", ""]; if (!0 === o.url && !(!1 == i && $.jgrid.isEmpty(e) || /^(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i.test(e))) return [!1, n + ": " + c.url, ""]; if (!0 === o.custom && (!1 != i || !$.jgrid.isEmpty(e))) { if ($.isFunction(o.custom_func)) { e = o.custom_func.call(d, e, n, t); return $.isArray(e) ? e : [!1, c.customarray, ""] } return [!1, c.customfcheck, ""] } } return [!0, "", ""] }, validateForm: function (e) { for (var t, r = !0, i = 0; i < e.elements.length; i++)if (t = e.elements[i], ("INPUT" === t.nodeName || "TEXTAREA" === t.nodeName || "SELECT" === t.nodeName) && (void 0 !== t.willValidate ? ("INPUT" === t.nodeName && t.type !== t.getAttribute("type") && t.setCustomValidity($.jgrid.LegacyValidation(t) ? "" : "error"), t.reportValidity()) : (t.validity = t.validity || {}, t.validity.valid = $.jgrid.LegacyValidation(t)), !t.validity.valid)) { r = !1; break } return r }, LegacyValidation: function (e) { var t = !0, r = e.value, i = e.getAttribute("type"), o = "checkbox" === i || "radio" === i, a = e.getAttribute("required"), n = e.getAttribute("minlength"), l = e.getAttribute("maxlength"), i = e.getAttribute("pattern"); return e.disabled || (t = (t = t && (!a || o && e.checked || !o && "" !== r)) && (o || (!n || r.length >= n) && (!l || r.length <= l))) && i && (t = (i = new RegExp(i)).test(r)), t }, buildButtons: function (e, r, i) { var o; return $.each(e, function (e, t) { t.id || (t.id = $.jgrid.randId()), t.position || (t.position = "last"), t.side || (t.side = "left"), o = t.icon ? " fm-button-icon-" + t.side + "'><span class='" + i.icon_base + " " + t.icon + "'></span>" : "'>", o = "<a  data-index='" + e + "' id='" + t.id + "' class='fm-button " + i.button + o + t.text + "</a>", "last" === t.position ? r += o : r = o + r }), r }, setSelNavIndex: function (r, i) { var e = $(".ui-pg-button", r.p.pager); $.each(e, function (e, t) { if (i === t) return r.p.navIndex = e, !1 }), $(i).attr("tabindex", "0") }, getFirstVisibleCol: function (e) { for (var t = -1, r = 0; r < e.p.colModel.length; r++)if (!0 !== e.p.colModel[r].hidden) { t = r; break } return t } }), $.fn.jqFilter = function (e) { if ("string" == typeof e) { var t = $.fn.jqFilter[e]; if (!t) throw "jqFilter - No such method: " + e; var r = $.makeArray(arguments).slice(1); return t.apply(this, r) } var q = $.extend(!0, { filter: null, columns: [], sortStrategy: null, onChange: null, afterRedraw: null, checkValues: null, error: !1, errmsg: "", errorcheck: !0, showQuery: !0, sopt: null, ops: [], operands: null, numopts: ["eq", "ne", "lt", "le", "gt", "ge", "nu", "nn", "in", "ni"], stropts: ["eq", "ne", "bw", "bn", "ew", "en", "cn", "nc", "nu", "nn", "in", "ni"], strarr: ["text", "string", "blob"], groupOps: [{ op: "AND", text: "AND" }, { op: "OR", text: "OR" }], groupButton: !0, ruleButtons: !0, uniqueSearchFields: !1, direction: "ltr", addsubgrup: "Add subgroup", addrule: "Add rule", delgroup: "Delete group", delrule: "Delete rule", autoencode: !1, unaryOperations: [] }, $.jgrid.filter, e || {}); return this.each(function () { if (!this.filter) { this.p = q, null !== this.p.filter && void 0 !== this.p.filter || (this.p.filter = { groupOp: this.p.groupOps[0].op, rules: [], groups: [] }), null != this.p.sortStrategy && $.isFunction(this.p.sortStrategy) && this.p.columns.sort(this.p.sortStrategy); var e, t, r = this.p.columns.length, y = /msie/i.test(navigator.userAgent) && !window.opera; if (this.p.initFilter = $.extend(!0, {}, this.p.filter), r) { for (e = 0; e < r; e++)(t = this.p.columns[e]).stype ? t.inputtype = t.stype : t.inputtype || (t.inputtype = "text"), t.sorttype ? t.searchtype = t.sorttype : t.searchtype || (t.searchtype = "string"), void 0 === t.hidden && (t.hidden = !1), t.label || (t.label = t.name), t.index && (t.name = t.index), t.hasOwnProperty("searchoptions") || (t.searchoptions = {}), t.hasOwnProperty("searchrules") || (t.searchrules = {}), void 0 === t.search ? t.inlist = !0 : t.inlist = t.search; var w = function () { return $("#" + $.jgrid.jqID(q.id))[0] || null }, i = w(), x = $.jgrid.styleUI[i.p.styleUI || "jQueryUI"].filter, _ = $.jgrid.styleUI[i.p.styleUI || "jQueryUI"].common; this.p.showQuery && $(this).append("<table class='queryresult " + x.table_widget + "' style='display:block;max-width:440px;border:0px none;' dir='" + this.p.direction + "'><tbody><tr><td class='query'></td></tr></tbody></table>"); var n = function (e, t) { var r = [!0, ""], i = w(); if ($.isFunction(t.searchrules)) r = t.searchrules.call(i, e, t); else if ($.jgrid && $.jgrid.checkValues) try { r = $.jgrid.checkValues.call(i, e, -1, t.searchrules, t.label) } catch (e) { } r && r.length && !1 === r[0] && (q.error = !r[0], q.errmsg = r[1]) }; this.onchange = function () { return this.p.error = !1, this.p.errmsg = "", !!$.isFunction(this.p.onChange) && this.p.onChange.call(this, this.p) }, this.reDraw = function () { $("table.group:first", this).remove(); var e = this.createTableForGroup(q.filter, null); $(this).append(e), $.isFunction(this.p.afterRedraw) && this.p.afterRedraw.call(this, this.p) }, this.createTableForGroup = function (i, e) { var o = this, t = $("<table class='group " + x.table_widget + " ui-search-table' style='border:0px none;'><tbody></tbody></table>"), r = "left"; "rtl" === this.p.direction && (r = "right", t.attr("dir", "rtl")), null === e && t.append("<tr class='error' style='display:none;'><th colspan='5' class='" + _.error + "' align='" + r + "'></th></tr>"); var a = $("<tr></tr>"); t.append(a); r = $("<th colspan='5' align='" + r + "'></th>"); if (a.append(r), !0 === this.p.ruleButtons) { var n = $("<select size='1' class='opsel " + x.srSelect + "'></select>"); r.append(n); for (var l, s = "", d = 0; d < q.groupOps.length; d++)l = i.groupOp === o.p.groupOps[d].op ? " selected='selected'" : "", s += "<option value='" + o.p.groupOps[d].op + "'" + l + ">" + o.p.groupOps[d].text + "</option>"; n.append(s).on("change", function () { i.groupOp = $(n).val(), o.onchange() }) } var p, c, a = "<span></span>"; if (this.p.groupButton && (a = $("<input type='button' value='+ {}' title='" + o.p.subgroup + "' class='add-group " + _.button + "'/>")).on("click", function () { return void 0 === i.groups && (i.groups = []), i.groups.push({ groupOp: q.groupOps[0].op, rules: [], groups: [] }), o.reDraw(), o.onchange(), !1 }), r.append(a), !0 === this.p.ruleButtons && ((c = $("<input type='button' value='+' title='" + o.p.addrule + "' class='add-rule ui-add " + _.button + "'/>")).on("click", function () { for (void 0 === i.rules && (i.rules = []), d = 0; d < o.p.columns.length; d++) { var e = void 0 === o.p.columns[d].search || o.p.columns[d].search, t = !0 === o.p.columns[d].hidden; if (!0 === o.p.columns[d].searchoptions.searchhidden && e || e && !t) { p = o.p.columns[d]; break } } if (!p) return !1; var r = p.searchoptions.sopt || o.p.sopt || (-1 !== $.inArray(p.searchtype, o.p.strarr) ? o.p.stropts : o.p.numopts); return i.rules.push({ field: p.name, op: r[0], data: "" }), o.reDraw(), !1 }), r.append(c)), null !== e && (c = $("<input type='button' value='-' title='" + o.p.delgroup + "' class='delete-group " + _.button + "'/>"), r.append(c), c.on("click", function () { for (d = 0; d < e.groups.length; d++)if (e.groups[d] === i) { e.groups.splice(d, 1); break } return o.reDraw(), o.onchange(), !1 })), void 0 !== i.groups) for (d = 0; d < i.groups.length; d++) { var u = $("<tr></tr>"); t.append(u); var h = $("<td class='first'></td>"); u.append(h); h = $("<td colspan='4'></td>"); h.append(this.createTableForGroup(i.groups[d], i)), u.append(h) } void 0 === i.groupOp && (i.groupOp = o.p.groupOps[0].op); var g = o.p.ruleButtons && o.p.uniqueSearchFields; if (g) for (m = 0; m < o.p.columns.length; m++)o.p.columns[m].inlist && (o.p.columns[m].search = !0); if (void 0 !== i.rules) for (d = 0; d < i.rules.length; d++)if (t.append(this.createTableRowForRule(i.rules[d], i)), g) for (var f = i.rules[d].field, m = 0; m < o.p.columns.length; m++)if (f === o.p.columns[m].name) { o.p.columns[m].search = !1; break } return t }, this.createTableRowForRule = function (a, e) { var n, l, s, t, d = this, p = w(), r = $("<tr></tr>"), i = ""; r.append("<td class='first'></td>"); var o = $("<td class='columns'></td>"); r.append(o); var c, u = $("<select size='1' class='" + x.srSelect + "'></select>"), h = []; o.append(u), u.on("change", function () { var e; for (d.p.ruleButtons && d.p.uniqueSearchFields && (e = parseInt($(this).data("curr"), 10), r = this.selectedIndex, 0 <= e && (d.p.columns[e].search = !0, $(this).data("curr", r), d.p.columns[r].search = !1)), a.field = $(u).val(), l = $(this).parents("tr:first"), $(".data", l).empty(), f = 0; f < d.p.columns.length; f++)if (d.p.columns[f].name === a.field) { s = d.p.columns[f]; break } if (s) { s.searchoptions.id = $.jgrid.randId(), s.searchoptions.name = a.field, s.searchoptions.oper = "filter", y && "text" === s.inputtype && (s.searchoptions.size || (s.searchoptions.size = 10)); var t = $.jgrid.createEl.call(p, s.inputtype, s.searchoptions, "", !0, d.p.ajaxSelectOptions || {}, !0); $(t).addClass("input-elm " + x.srInput), n = s.searchoptions.sopt || d.p.sopt || (-1 !== $.inArray(s.searchtype, d.p.strarr) ? d.p.stropts : d.p.numopts); var r, i = "", o = 0; for (h = [], $.each(d.p.ops, function () { h.push(this.oper) }), f = 0; f < n.length; f++)-1 !== (c = $.inArray(n[f], h)) && (0 === o && (a.op = d.p.ops[c].oper), i += "<option value='" + d.p.ops[c].oper + "'>" + d.p.ops[c].text + "</option>", o++); $(".selectopts", l).empty().append(i), $(".selectopts", l)[0].selectedIndex = 0, $.jgrid.msie() && $.jgrid.msiever() < 9 && (r = parseInt($("select.selectopts", l)[0].offsetWidth, 10) + 1, $(".selectopts", l).width(r), $(".selectopts", l).css("width", "auto")), $(".data", l).append(t), $.jgrid.bindEv.call(p, t, s.searchoptions), $(".input-elm", l).on("change", function (e) { e = e.target; "custom" === s.inputtype && $.isFunction(s.searchoptions.custom_value) ? a.data = s.searchoptions.custom_value.call(p, $(".customelement", this), "get") : a.data = $(e).val(), "select" === s.inputtype && s.searchoptions.multiple && (a.data = a.data.join(",")), d.onchange() }), setTimeout(function () { a.data = $(t).val(), ("nu" === a.op || "nn" === a.op || 0 <= $.inArray(a.op, d.p.unaryOperations)) && ($(t).attr("readonly", "true"), $(t).attr("disabled", "true")), "select" === s.inputtype && s.searchoptions.multiple && $.isArray(a.data) && (a.data = a.data.join(",")), d.onchange() }, 0) } }); for (var g = 0, f = 0; f < d.p.columns.length; f++) { var m = void 0 === d.p.columns[f].search || d.p.columns[f].search, v = !0 === d.p.columns[f].hidden; (!0 === d.p.columns[f].searchoptions.searchhidden && m || m && !v) && (t = "", a.field === d.p.columns[f].name && (t = " selected='selected'", g = f), i += "<option value='" + d.p.columns[f].name + "'" + t + ">" + d.p.columns[f].label + "</option>") } u.append(i), u.data("curr", g); var b = $("<td class='operators'></td>"); r.append(b), (s = q.columns[g]).searchoptions.id = $.jgrid.randId(), y && "text" === s.inputtype && (s.searchoptions.size || (s.searchoptions.size = 10)), s.searchoptions.name = a.field, s.searchoptions.oper = "filter"; o = $.jgrid.createEl.call(p, s.inputtype, s.searchoptions, a.data, !0, d.p.ajaxSelectOptions || {}, !0); ("nu" === a.op || "nn" === a.op || 0 <= $.inArray(a.op, d.p.unaryOperations)) && ($(o).attr("readonly", "true"), $(o).attr("disabled", "true")); var j = $("<select size='1' class='selectopts " + x.srSelect + "'></select>"); for (b.append(j), j.on("change", function () { a.op = $(j).val(), l = $(this).parents("tr:first"); var e = $(".input-elm", l)[0]; "nu" === a.op || "nn" === a.op || 0 <= $.inArray(a.op, d.p.unaryOperations) ? (a.data = "", "SELECT" !== e.tagName.toUpperCase() && (e.value = ""), e.setAttribute("readonly", "true"), e.setAttribute("disabled", "true")) : ("SELECT" === e.tagName.toUpperCase() && (a.data = e.value), e.removeAttribute("readonly"), e.removeAttribute("disabled")), d.onchange() }), n = s.searchoptions.sopt || d.p.sopt || (-1 !== $.inArray(s.searchtype, d.p.strarr) ? d.p.stropts : d.p.numopts), i = "", $.each(d.p.ops, function () { h.push(this.oper) }), f = 0; f < n.length; f++)-1 !== (c = $.inArray(n[f], h)) && (t = a.op === d.p.ops[c].oper ? " selected='selected'" : "", i += "<option value='" + d.p.ops[c].oper + "'" + t + ">" + d.p.ops[c].text + "</option>"); j.append(i); b = $("<td class='data'></td>"); r.append(b), b.append(o), $.jgrid.bindEv.call(p, o, s.searchoptions), $(o).addClass("input-elm " + x.srInput).on("change", function () { a.data = "custom" === s.inputtype ? s.searchoptions.custom_value.call(p, $(".customelement", this), "get") : $(this).val(), d.onchange() }); b = $("<td></td>"); return r.append(b), !0 === this.p.ruleButtons && (o = $("<input type='button' value='-' title='" + d.p.delrule + "' class='delete-rule ui-del " + _.button + "'/>"), b.append(o), o.on("click", function () { for (f = 0; f < e.rules.length; f++)if (e.rules[f] === a) { e.rules.splice(f, 1); break } return d.reDraw(), d.onchange(), !1 })), r }, this.getStringForGroup = function (e) { var t, r = "("; if (void 0 !== e.groups) for (t = 0; t < e.groups.length; t++) { 1 < r.length && (r += " " + e.groupOp + " "); try { r += this.getStringForGroup(e.groups[t]) } catch (e) { alert(e) } } if (void 0 !== e.rules) try { for (t = 0; t < e.rules.length; t++)1 < r.length && (r += " " + e.groupOp + " "), r += this.getStringForRule(e.rules[t]) } catch (e) { alert(e) } return "()" === (r += ")") ? "" : r }, this.getStringForRule = function (e) { for (var t, r, i = "", o = "", a = 0; a < this.p.ops.length; a++)if (this.p.ops[a].oper === e.op) { i = this.p.operands.hasOwnProperty(e.op) ? this.p.operands[e.op] : "", o = this.p.ops[a].oper; break } for (a = 0; a < this.p.columns.length; a++)if (this.p.columns[a].name === e.field) { t = this.p.columns[a]; break } return void 0 === t ? "" : (r = this.p.autoencode ? $.jgrid.htmlEncode(e.data) : e.data, "bw" !== o && "bn" !== o || (r += "%"), "ew" !== o && "en" !== o || (r = "%" + r), "cn" !== o && "nc" !== o || (r = "%" + r + "%"), "in" !== o && "ni" !== o || (r = " (" + r + ")"), q.errorcheck && n(e.data, t), -1 !== $.inArray(t.searchtype, ["int", "integer", "float", "number", "currency"]) || "nn" === o || "nu" === o || 0 <= $.inArray(e.op, this.p.unaryOperations) ? e.field + " " + i + " " + r : e.field + " " + i + ' "' + r + '"') }, this.resetFilter = function () { this.p.filter = $.extend(!0, {}, this.p.initFilter), this.reDraw(), this.onchange() }, this.hideError = function () { $("th." + _.error, this).html(""), $("tr.error", this).hide() }, this.showError = function () { $("th." + _.error, this).html(this.p.errmsg), $("tr.error", this).show() }, this.toUserFriendlyString = function () { return this.getStringForGroup(q.filter) }, this.toString = function () { var o = this; return function e(t) { var r, i = "("; if (void 0 !== t.groups) for (r = 0; r < t.groups.length; r++)1 < i.length && ("OR" === t.groupOp ? i += " || " : i += " && "), i += e(t.groups[r]); if (void 0 !== t.rules) for (r = 0; r < t.rules.length; r++)1 < i.length && ("OR" === t.groupOp ? i += " || " : i += " && "), i += function (e) { if (o.p.errorcheck) { for (var t, r = 0; r < o.p.columns.length; r++)if (o.p.columns[r].name === e.field) { t = o.p.columns[r]; break } t && n(e.data, t) } return e.op + "(item." + e.field + ",'" + e.data + "')" }(t.rules[r]); return "()" == (i += ")") ? "" : i }(this.p.filter) }, this.reDraw(), this.p.showQuery && this.onchange(), this.filter = !0 } } }) }, $.extend($.fn.jqFilter, { toSQLString: function () { var e = ""; return this.each(function () { e = this.toUserFriendlyString() }), e }, filterData: function () { var e; return this.each(function () { e = this.p.filter }), e }, getParameter: function (r) { var i = null; return void 0 !== r && this.each(function (e, t) { t.p.hasOwnProperty(r) && (i = t.p[r]) }), i || this[0].p }, resetFilter: function () { return this.each(function () { this.resetFilter() }) }, addFilter: function (e) { "string" == typeof e && (e = $.jgrid.parse(e)), this.each(function () { this.p.filter = e, this.reDraw(), this.onchange() }) } }), $.extend($.jgrid, { filterRefactor: function (e) { var t, r, i, o, a, n = {}; try { if ((n = "string" == typeof e.ruleGroup ? $.jgrid.parse(e.ruleGroup) : e.ruleGroup).rules && n.rules.length) for (t = n.rules, r = 0; r < t.length; r++)i = t[r], $.inArray(i.filed, e.ssfield) && 1 < (o = i.data.split(e.splitSelect)).length && (void 0 === n.groups && (n.groups = []), a = { groupOp: e.groupOpSelect, groups: [], rules: [] }, n.groups.push(a), $.each(o, function (e) { o[e] && a.rules.push({ data: o[e], op: i.op, field: i.field }) }), t.splice(r, 1), r--) } catch (e) { } return n } }), $.jgrid.extend({ filterToolbar: function (I) { var r = $.jgrid.getRegional(this[0], "search"); return I = $.extend({ autosearch: !0, autosearchDelay: 500, searchOnEnter: !0, beforeSearch: null, afterSearch: null, beforeClear: null, afterClear: null, onClearSearchValue: null, url: "", stringResult: !1, groupOp: "AND", defaultSearch: "bw", searchOperators: !1, resetIcon: "x", splitSelect: ",", groupOpSelect: "OR", errorcheck: !0, operands: { eq: "==", ne: "!", lt: "<", le: "<=", gt: ">", ge: ">=", bw: "^", bn: "!^", in: "=", ni: "!=", ew: "|", en: "!@", cn: "~", nc: "!~", nu: "#", nn: "!#", bt: "..." }, disabledKeys: [9, 16, 17, 18, 19, 20, 33, 34, 35, 36, 37, 38, 39, 30, 45, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 144, 145] }, r, I || {}), this.each(function () { var _ = this, q = []; if (!_.p.filterToolbar) { if ($(_).data("filterToolbar") || $(_).data("filterToolbar", I), _.p.force_regional && (I = $.extend(I, r)), void 0 !== _.p.customFilterDef) for (var e in _.p.customFilterDef) _.p.customFilterDef.hasOwnProperty(e) && !I.operands.hasOwnProperty(e) && (I.odata.push({ oper: e, text: _.p.customFilterDef[e].text }), I.operands[e] = _.p.customFilterDef[e].operand, !0 === _.p.customFilterDef[e].unary && q.push(e)); var g, f, t, m = $.jgrid.styleUI[_.p.styleUI || "jQueryUI"].filter, c = $.jgrid.styleUI[_.p.styleUI || "jQueryUI"].common, v = $.jgrid.styleUI[_.p.styleUI || "jQueryUI"].base, b = function () { var t, r, i, o, a = {}, n = 0, l = {}, s = !1, d = [], p = !1, c = [!0, "", ""], u = !1; if ($.each(_.p.colModel, function () { var e = $("#gs_" + _.p.idPrefix + $.jgrid.jqID(this.name), !0 === this.frozen && !0 === _.p.frozenColumns ? _.grid.fhDiv : _.grid.hDiv); if (r = this.index || this.name, o = this.searchoptions || {}, i = I.searchOperators && o.searchOperMenu ? e.parents("table.ui-search-table").find("td.ui-search-oper").children("a").attr("soper") || I.defaultSearch : o.sopt ? o.sopt[0] : "select" === this.stype ? "eq" : I.defaultSearch, t = "custom" === this.stype && $.isFunction(o.custom_value) && 0 < e.length ? o.custom_value.call(_, e, "get") : e.val(), "select" === this.stype && o.multiple && $.isArray(t) && (t = 0 < t.length ? (s = !0, d.push(r), 1 === t.length ? t[0] : t) : ""), this.searchrules && I.errorcheck && ($.isFunction(this.searchrules) ? c = this.searchrules.call(_, t, this) : $.jgrid && $.jgrid.checkValues && (c = $.jgrid.checkValues.call(_, t, -1, this.searchrules, this.label || this.name)), c && c.length && !1 === c[0])) return this.searchrules.hasOwnProperty("validationError") && (u = this.searchrules.validationError), !1; if ("bt" === i && (p = !0), t || "nu" === i || "nn" === i || 0 <= $.inArray(i, q)) a[r] = t, l[r] = i, n++; else try { delete _.p.postData[r] } catch (e) { } }), !1 !== c[0]) { var e, h = 0 < n; if (!0 === I.stringResult || "local" === _.p.datatype || !0 === I.searchOperators) { var g, f, m, v, b, j, y = '{"groupOp":"' + I.groupOp + '","rules":[', w = 0; if ($.each(a, function (e, t) { 0 < w && (y += ","), y += '{"field":"' + e + '",', y += '"op":"' + l[e] + '",', y += '"data":"' + (t += "").replace(/\\/g, "\\\\").replace(/\"/g, '\\"') + '"}', w++ }), y += "]}", s && (g = $.jgrid.filterRefactor({ ruleGroup: y, ssfield: d, splitSelect: I.splitSelect, groupOpSelect: I.groupOpSelect }), y = JSON.stringify(g)), p && ($.isPlainObject(g) || (g = $.jgrid.parse(y)), g.rules && g.rules.length)) for (f = g.rules, m = 0; m < f.length; m++)"bt" === (v = f[m]).op && 1 < (b = v.data.split("...")).length && (void 0 === g.groups && (g.groups = []), j = { groupOp: "AND", groups: [], rules: [] }, g.groups.push(j), $.each(b, function (e) { var t = 0 === e ? "ge" : "le"; b[e] && j.rules.push({ data: b[e], op: t, field: v.field }) }), f.splice(m, 1), m--); (p || s) && (y = JSON.stringify(g)), !0 === _.p.mergeSearch && _.p.searchModules.hasOwnProperty("filterToolbar") && !1 !== _.p.searchModules.filterToolbar ? (_.p.searchModules.filterToolbar = 0 < w ? y : null, h = !0, $.extend(_.p.postData, { filters: $.jgrid.splitSearch(_.p.searchModules) })) : $.extend(_.p.postData, { filters: y }), $.each(["searchField", "searchString", "searchOper"], function (e, t) { _.p.postData.hasOwnProperty(t) && delete _.p.postData[t] }) } else $.extend(_.p.postData, a); I.url && (e = _.p.url, $(_).jqGrid("setGridParam", { url: I.url })); var x = "stop" === $(_).triggerHandler("jqGridToolbarBeforeSearch"); !x && $.isFunction(I.beforeSearch) && (x = I.beforeSearch.call(_)), x || $(_).jqGrid("setGridParam", { search: h }).trigger("reloadGrid", [{ page: 1 }]), e && $(_).jqGrid("setGridParam", { url: e }), $(_).triggerHandler("jqGridToolbarAfterSearch"), $.isFunction(I.afterSearch) && I.afterSearch.call(_) } else $.isFunction(u) ? u.call(_, c[1]) : (e = $.jgrid.getRegional(_, "errors"), $.jgrid.info_dialog(e.errcap, c[1], "", { styleUI: _.p.styleUI })) }, j = $("<tr class='ui-search-toolbar' role='row'></tr>"); I.restoreFromFilters && (t = _.p.postData.filters) && ("string" == typeof t && (t = $.jgrid.parse(t)), f = !!t.rules.length && t.rules), I.disabledKeys = new Set(I.disabledKeys), $.each(_.p.colModel, function (e) { var t, r, i, o, a, n, l = this, s = "", d = "=", p = $("<th role='columnheader' class='" + v.headerBox + " ui-th-" + _.p.direction + "' id='gsh_" + _.p.id + "_" + l.name + "' ></th>"), c = $("<div></div>"), u = $("<table class='ui-search-table' cellspacing='0'><tr><td class='ui-search-oper' headers=''></td><td class='ui-search-input' headers=''></td><td class='ui-search-clear' headers=''></td></tr></table>"); if (!0 === this.hidden && $(p).css("display", "none"), this.search = !1 !== this.search, void 0 === this.stype && (this.stype = "text"), this.searchoptions = this.searchoptions || {}, void 0 === this.searchoptions.searchOperMenu && (this.searchoptions.searchOperMenu = !0), t = $.extend({}, this.searchoptions, { name: l.index || l.name, id: "gs_" + _.p.idPrefix + l.name, oper: "search" }), this.search) { if (I.restoreFromFilters && f) { n = !1; for (var h = 0; h < f.length; h++)if (f[h].field) if ((l.index || l.name) === f[h].field) { n = f[h]; break } } if (I.searchOperators) { for (r = t.sopt ? t.sopt[0] : "select" === l.stype ? "eq" : I.defaultSearch, I.restoreFromFilters && n && (r = n.op), i = 0; i < I.odata.length; i++)if (I.odata[i].oper === r) { d = I.operands[r] || ""; break } o = null != t.searchtitle ? t.searchtitle : I.operandTitle, s = this.searchoptions.searchOperMenu ? "<a title='" + o + "' soper='" + r + "' class='soptclass' colname='" + this.name + "'>" + d + "</a>" : "" } switch ($("td:eq(0)", u).attr("columname", l.name).append(s), void 0 === t.clearSearch && (t.clearSearch = !0), t.clearSearch ? (a = I.resetTitle || "Clear Search Value", $("td:eq(2)", u).append("<a title='" + a + "' style='padding-right: 0.3em;padding-left: 0.3em;' class='clearsearchclass'>" + I.resetIcon + "</a>")) : $("td:eq(2)", u).hide(), this.surl && (t.dataUrl = this.surl), a = "", t.defaultValue && (a = $.isFunction(t.defaultValue) ? t.defaultValue.call(_) : t.defaultValue), I.restoreFromFilters && n && (a = n.data), a = $.jgrid.createEl.call(_, this.stype, t, a, !1, $.extend({}, $.jgrid.ajaxOptions, _.p.ajaxSelectOptions || {})), $(a).addClass(m.srInput), $("td:eq(1)", u).append(a), $(c).append(u), null == t.dataEvents && (t.dataEvents = []), this.stype) { case "select": !0 === I.autosearch && t.dataEvents.push({ type: "change", fn: function () { return b(), !1 } }); break; case "text": !0 === I.autosearch && (I.searchOnEnter ? t.dataEvents.push({ type: "keypress", fn: function (e) { return 13 === (e.charCode || e.keyCode || 0) ? (b(), !1) : this } }) : t.dataEvents.push({ type: "keydown", fn: function (e) { e = e.which; if (!I.disabledKeys.has(e)) { if (13 === e) return !1; g && clearTimeout(g), g = setTimeout(function () { b() }, I.autosearchDelay) } } })) }$.jgrid.bindEv.call(_, a, t) } $(p).append(c), $(j).append(p), I.searchOperators && "" !== s || $("td:eq(0)", u).hide() }), $("table thead", _.grid.hDiv).append(j), I.searchOperators && ($(".soptclass", j).click(function (e) { var t = $(this).offset(); !function (r, e, t) { $("#sopt_menu").remove(), e = parseInt(e, 10), t = parseInt(t, 10) + 18; for (var i, o = '<ul id="sopt_menu" class="ui-search-menu modal-content" role="menu" tabindex="0" style="font-size:' + ($(".ui-jqgrid").css("font-size") || "11px") + ";left:" + e + "px;top:" + t + 'px;">', a = $(r).attr("soper"), n = [], l = 0, s = $(r).attr("colname"), d = _.p.colModel.length; l < d && _.p.colModel[l].name !== s;)l++; var t = _.p.colModel[l], p = $.extend({}, t.searchoptions); for (p.sopt || (p.sopt = [], p.sopt[0] = "select" === t.stype ? "eq" : I.defaultSearch), $.each(I.odata, function () { n.push(this.oper) }), l = 0; l < p.sopt.length; l++)-1 !== (i = $.inArray(p.sopt[l], n)) && (o += '<li class="ui-menu-item ' + (a === I.odata[i].oper ? c.highlight : "") + '" role="presentation"><a class="' + c.cornerall + ' g-menu-item" tabindex="0" role="menuitem" value="' + I.odata[i].oper + '" oper="' + I.operands[I.odata[i].oper] + '"><table class="ui-common-table"><tr><td class="opersign">' + I.operands[I.odata[i].oper] + "</td><td>" + I.odata[i].text + "</td></tr></table></a></li>"); o += "</ul>", $("body").append(o), $("#sopt_menu").addClass("ui-menu " + m.menu_widget), $("#sopt_menu > li > a").hover(function () { $(this).addClass(c.hover) }, function () { $(this).removeClass(c.hover) }).click(function () { var e = $(this).attr("value"), t = $(this).attr("oper"); $(_).triggerHandler("jqGridToolbarSelectOper", [e, t, r]), $("#sopt_menu").hide(), $(r).text(t).attr("soper", e), !0 === I.autosearch && (t = $(r).parent().next().children()[0], ($(t).val() || "nu" === e || "nn" === e || 0 <= $.inArray(e, q)) && b()) }) }(this, t.left, t.top), e.stopPropagation() }), $("body").on("click", function (e) { "soptclass" !== e.target.className && $("#sopt_menu").remove() })), $(".clearsearchclass", j).click(function () { for (var e, t, r = $(this).parents("tr:first"), i = $("td.ui-search-oper", r).attr("columname"), o = 0, a = _.p.colModel.length, n = $("td.ui-search-oper a", r).attr("soper"); o < a;) { if (_.p.colModel[o].name === i) { e = _.p.colModel[o]; break } o++ } var l, s, d = $.extend({}, _.p.colModel[o].searchoptions || {}), p = d.defaultValue || ""; "select" === _.p.colModel[o].stype ? (l = $("td.ui-search-input select", r), p ? l.val(p) : l[0].selectedIndex = 0) : (l = $("td.ui-search-input input", r)).val(p), $(_).triggerHandler("jqGridToolbarClearVal", [l[0], o, d, p]), $.isFunction(I.onClearSearchValue) && I.onClearSearchValue.call(_, l[0], o, d, p), ("nu" === n || "nn" === n || 0 <= $.inArray(n, q)) && (t = d.sopt ? d.sopt[0] : "select" === e.stype ? "eq" : I.defaultSearch, s = null != _.p.customFilterDef && null != _.p.customFilterDef[t] ? _.p.customFilterDef[t].operand : I.operands[t] || "", (t === n ? $("td.ui-search-oper a", r).attr("soper", "dummy") : $("td.ui-search-oper a", r).attr("soper", t)).text(s)), !0 === I.autosearch && (b(), t === n && $("td.ui-search-oper a", r).attr("soper", t).text(s)) }), $(_.grid.hDiv).on("scroll", function (e) { _.grid.bDiv.scrollLeft = _.grid.hDiv.scrollLeft }), this.p.filterToolbar = !0, this.triggerToolbar = b, this.clearToolbar = function (e) { var r, i = {}, o = 0; e = "boolean" != typeof e || e, $.each(_.p.colModel, function () { var t, e = $("#gs_" + _.p.idPrefix + $.jgrid.jqID(this.name), !0 === this.frozen && !0 === _.p.frozenColumns ? _.grid.fhDiv : _.grid.hDiv); switch (this.searchoptions && void 0 !== this.searchoptions.defaultValue && (t = this.searchoptions.defaultValue), r = this.index || this.name, this.stype) { case "select": if (e.find("option").each(function (e) { if (0 === e && (this.selected = !0), $(this).val() === t) return !(this.selected = !0) }), void 0 !== t) i[r] = t, o++; else try { delete _.p.postData[r] } catch (e) { } break; case "text": if (e.val(t || ""), void 0 !== t) i[r] = t, o++; else try { delete _.p.postData[r] } catch (e) { } break; case "custom": $.isFunction(this.searchoptions.custom_value) && 0 < e.length && this.searchoptions.custom_value.call(_, e, "set", t || "") } }); var a, n, t, l = 0 < o; (_.p.resetsearch = !0) === I.stringResult || "local" === _.p.datatype ? (a = '{"groupOp":"' + I.groupOp + '","rules":[', n = 0, $.each(i, function (e, t) { 0 < n && (a += ","), a += '{"field":"' + e + '",', a += '"op":"eq",', a += '"data":"' + (t += "").replace(/\\/g, "\\\\").replace(/\"/g, '\\"') + '"}', n++ }), a += "]}", !0 === _.p.mergeSearch && _.p.searchModules.hasOwnProperty("filterToolbar") && !1 !== _.p.searchModules.filterToolbar ? (_.p.searchModules.filterToolbar = 0 < n ? a : null, l = !0, $.extend(_.p.postData, { filters: $.jgrid.splitSearch(_.p.searchModules) })) : $.extend(_.p.postData, { filters: a }), $.each(["searchField", "searchString", "searchOper"], function (e, t) { _.p.postData.hasOwnProperty(t) && delete _.p.postData[t] })) : $.extend(_.p.postData, i), I.url && (t = _.p.url, $(_).jqGrid("setGridParam", { url: I.url })); var s = "stop" === $(_).triggerHandler("jqGridToolbarBeforeClear"); !s && $.isFunction(I.beforeClear) && (s = I.beforeClear.call(_)), s || e && $(_).jqGrid("setGridParam", { search: l }).trigger("reloadGrid", [{ page: 1 }]), t && $(_).jqGrid("setGridParam", { url: t }), $(_).triggerHandler("jqGridToolbarAfterClear"), $.isFunction(I.afterClear) && I.afterClear() }, this.toggleToolbar = function () { var e = $("tr.ui-search-toolbar", _.grid.hDiv); !0 === _.p.frozenColumns && $(_).jqGrid("destroyFrozenColumns"), "none" === e.css("display") ? e.show() : e.hide(), !0 === _.p.frozenColumns && $(_).jqGrid("setFrozenColumns") } } }) }, destroyFilterToolbar: function () { return this.each(function () { this.p.filterToolbar && (this.triggerToolbar = null, this.clearToolbar = null, this.toggleToolbar = null, this.p.filterToolbar = !1, $(this.grid.hDiv).find("table thead tr.ui-search-toolbar").remove()) }) }, refreshFilterToolbar: function (g) { return g = $.extend(!0, { filters: "", onClearVal: null, onSetVal: null }, g || {}), this.each(function () { var o, a, n, e, l, s, d, p = this, c = p.p.colModel, u = p.p.colModel.length, h = []; if (p.p.filterToolbar) { for (a = $(p).data("filterToolbar"), o = 0; o < u; o++) { switch (h.push(c[o].name), n = $("#gs_" + p.p.idPrefix + $.jgrid.jqID(c[o].name)), c[o].stype) { case "select": case "text": n.val("") }$.isFunction(g.onClearVal) && g.onClearVal.call(p, n, c[o].name) } "string" == typeof g.filters && (g.filters.length ? e = g.filters : p.p.postData.hasOwnProperty("filters") && (e = p.p.postData.filters), e = $.jgrid.parse(e)), $.isPlainObject(e) && function e(t) { if (t && t.rules) { for (l = t.rules, u = l.length, o = 0; o < u; o++) { var r; s = l[o], -1 !== (d = $.inArray(s.field, h)) && 0 < (n = $("#gs_" + p.p.idPrefix + $.jgrid.jqID(c[d].name))).length && ("select" === c[d].stype ? n.find("option[value='" + $.jgrid.jqID(s.data) + "']").prop("selected", !0) : "text" === c[d].stype && n.val(s.data), $.isFunction(g.onSetVal) && g.onSetVal.call(p, n, c[d].name), a && a.searchOperators && (r = n.parent().prev()).hasClass("ui-search-oper") && ($(".soptclass", r).attr("soper", s.op), a.operands.hasOwnProperty(s.op) && $(".soptclass", r).html(a.operands[s.op]))) } if (t.groups) for (var i = 0; i < t.groups.length; i++)e(t.groups[i]) } }(e) } }) }, searchGrid: function (S) { var e = $.jgrid.getRegional(this[0], "search"); return S = $.extend(!0, { recreateFilter: !1, drag: !0, sField: "searchField", sValue: "searchString", sOper: "searchOper", sFilter: "filters", loadDefaults: !0, beforeShowSearch: null, afterShowSearch: null, onInitializeSearch: null, afterRedraw: null, afterChange: null, sortStrategy: null, closeAfterSearch: !1, closeAfterReset: !1, closeOnEscape: !1, searchOnEnter: !1, multipleSearch: !1, multipleGroup: !1, top: 0, left: 0, jqModal: !0, modal: !1, resize: !0, width: 450, height: "auto", dataheight: "auto", showQuery: !1, errorcheck: !0, sopt: null, stringResult: void 0, onClose: null, onSearch: null, onReset: null, toTop: !0, overlay: 30, columns: [], tmplNames: null, tmplFilters: null, tmplLabel: " Template: ", showOnLoad: !1, layer: null, splitSelect: ",", groupOpSelect: "OR", operands: { eq: "=", ne: "<>", lt: "<", le: "<=", gt: ">", ge: ">=", bw: "LIKE", bn: "NOT LIKE", in: "IN", ni: "NOT IN", ew: "LIKE", en: "NOT LIKE", cn: "LIKE", nc: "NOT LIKE", nu: "IS NULL", nn: "ISNOT NULL" }, buttons: [] }, e, S || {}), this.each(function () { var o = this; if (o.grid) { var t, r, i = "fbox_" + o.p.id, a = !0, n = !0, l = { themodal: "searchmod" + i, modalhead: "searchhd" + i, modalcontent: "searchcnt" + i, scrollelm: i }, e = [], s = $.jgrid.styleUI[o.p.styleUI || "jQueryUI"].filter, d = $.jgrid.styleUI[o.p.styleUI || "jQueryUI"].common; if (S.styleUI = o.p.styleUI, "string" == typeof (t = $.isPlainObject(o.p._savedFilter) && !$.isEmptyObject(o.p._savedFilter) ? o.p._savedFilter : !0 === o.p.mergeSearch && o.p.searchModules.hasOwnProperty("searchGrid") && !1 !== o.p.searchModules.searchGrid ? !0 === o.p.searchModules.searchGrid ? "" : o.p.searchModules.searchGrid : o.p.postData[S.sFilter]) && (t = $.jgrid.parse(t)), !0 === S.recreateFilter && $("#" + $.jgrid.jqID(l.themodal)).remove(), void 0 !== $("#" + $.jgrid.jqID(l.themodal))[0]) k($("#fbox_" + $.jgrid.jqID(o.p.id))); else { var p = $("<div><div id='" + i + "' class='searchFilter' style='overflow:auto'></div></div>").insertBefore("#gview_" + $.jgrid.jqID(o.p.id)), c = "left", u = ""; "rtl" === o.p.direction && (c = "right", u = " style='text-align:left'", p.attr("dir", "rtl")); var h, g = $.extend([], o.p.colModel), f = "<a id='" + i + "_search' class='fm-button " + d.button + " fm-button-icon-right ui-search'><span class='" + d.icon_base + " " + s.icon_search + "'></span>" + S.Find + "</a>", m = "<a id='" + i + "_reset' class='fm-button " + d.button + " fm-button-icon-left ui-reset'><span class='" + d.icon_base + " " + s.icon_reset + "'></span>" + S.Reset + "</a>", v = "", b = "", j = !1, y = -1, w = !1, x = []; S.showQuery && (v = "<a id='" + i + "_query' class='fm-button " + d.button + " fm-button-icon-left'><span class='" + d.icon_base + " " + s.icon_query + "'></span>Query</a>"); var _ = $.jgrid.buildButtons(S.buttons, v + f, d), q = null; $(o).jqGrid("isGroupHeaderOn") && (f = $("table.ui-jqgrid-htable", o.grid.hDiv).find(".jqg-second-row-header"), I = o.p.groupHeader.length, void 0 !== f[0] && (q = o.p.groupHeader[I - 1])); var I; if (S.columns.length) g = S.columns, h = g[y = 0].index || g[0].name; else { if (null !== q) for (var D = 0; D < g.length; D++) { var C = function (e, t) { for (var r = t.length, i = 0; i < r; i++)if (t[i].startColumnName === e) return i; return -1 }(g[D].name, q.groupHeaders); if (0 <= C) { g[D].label = q.groupHeaders[C].titleText + "::" + o.p.colNames[D]; for (var F = 1; F <= q.groupHeaders[C].numberOfColumns - 1; F++)g[D + F].label = q.groupHeaders[C].titleText + "::" + o.p.colNames[D + F]; D = D + q.groupHeaders[C].numberOfColumns - 1 } } $.each(g, function (e, t) { var r, i; t.label || (t.label = o.p.colNames[e]), j || (r = void 0 === t.search || t.search, i = !0 === t.hidden, (t.searchoptions && !0 === t.searchoptions.searchhidden && r || r && !i) && (j = !0, h = t.index || t.name, y = e)), "select" === t.stype && t.searchoptions && t.searchoptions.multiple && (w = !0, x.push(t.index || t.name)) }) } if ((!t && h || !1 === S.multipleSearch) && (I = "eq", 0 <= y && g[y].searchoptions && g[y].searchoptions.sopt ? I = g[y].searchoptions.sopt[0] : S.sopt && S.sopt.length && (I = S.sopt[0]), t = { groupOp: "AND", rules: [{ field: h, op: I, data: "" }] }), j = !1, S.tmplNames && S.tmplNames.length && (j = !0, b = "<tr><td class='ui-search-label'>" + S.tmplLabel + "</td>", b += "<td><select size='1' class='ui-template " + s.srSelect + "'>", b += "<option value='default'>Default</option>", $.each(S.tmplNames, function (e, t) { b += "<option value='" + e + "'>" + t + "</option>" }), b += "</select></td></tr>"), void 0 !== o.p.customFilterDef) for (var G in o.p.customFilterDef) o.p.customFilterDef.hasOwnProperty(G) && !S.operands.hasOwnProperty(G) && (S.odata.push({ oper: G, text: o.p.customFilterDef[G].text }), S.operands[G] = o.p.customFilterDef[G].operand, !0 === o.p.customFilterDef[G].unary && e.push(G)); _ = "<table class='EditTable' style='border:0px none;margin-top:5px' id='" + i + "_2'><tbody><tr><td colspan='2'><hr class='" + d.content + "' style='margin:1px'/></td></tr>" + b + "<tr><td class='EditButton' style='text-align:" + c + "'>" + m + "</td><td class='EditButton' " + u + ">" + _ + "</td></tr></tbody></table>", i = $.jgrid.jqID(i), $("#" + i).jqFilter({ columns: g, sortStrategy: S.sortStrategy, filter: S.loadDefaults ? t : null, showQuery: S.showQuery, errorcheck: S.errorcheck, sopt: S.sopt, groupButton: S.multipleGroup, ruleButtons: S.multipleSearch, uniqueSearchFields: S.uniqueSearchFields, afterRedraw: S.afterRedraw, ops: S.odata, operands: S.operands, ajaxSelectOptions: o.p.ajaxSelectOptions, groupOps: S.groupOps, addsubgrup: S.addsubgrup, addrule: S.addrule, delgroup: S.delgroup, delrule: S.delrule, autoencode: o.p.autoencode, unaryOperations: e, onChange: function () { this.p.showQuery && $(".query", this).html(this.toUserFriendlyString()), $.isFunction(S.afterChange) && S.afterChange.call(o, $("#" + i), S) }, direction: o.p.direction, id: o.p.id }), p.append(_), $("#" + i + "_2").find("[data-index]").each(function () { var t = parseInt($(this).attr("data-index"), 10); 0 <= t && $(this).on("click", function (e) { S.buttons[t].click.call(o, $("#" + i), S, e) }) }), j && S.tmplFilters && S.tmplFilters.length && $(".ui-template", p).on("change", function () { var e = $(this).val(); return "default" === e ? $("#" + i).jqFilter("addFilter", t) : $("#" + i).jqFilter("addFilter", S.tmplFilters[parseInt(e, 10)]), !1 }), !0 === S.multipleGroup && (S.multipleSearch = !0), $(o).triggerHandler("jqGridFilterInitialize", [$("#" + i)]), $.isFunction(S.onInitializeSearch) && S.onInitializeSearch.call(o, $("#" + i)), S.gbox = "#gbox_" + $.jgrid.jqID(o.p.id); _ = $(".ui-jqgrid").css("font-size") || "11px"; S.layer ? $.jgrid.createModal(l, p, S, "#gview_" + $.jgrid.jqID(o.p.id), $("#gbox_" + $.jgrid.jqID(o.p.id))[0], "string" == typeof S.layer ? "#" + $.jgrid.jqID(S.layer) : S.layer, "string" == typeof S.layer ? { position: "relative", "font-size": _ } : { "font-size": _ }) : $.jgrid.createModal(l, p, S, "#gview_" + $.jgrid.jqID(o.p.id), $("#gbox_" + $.jgrid.jqID(o.p.id))[0], null, { "font-size": _ }), (S.searchOnEnter || S.closeOnEscape) && $("#" + $.jgrid.jqID(l.themodal)).keydown(function (e) { var t = $(e.target); return !S.searchOnEnter || 13 !== e.which || t.hasClass("add-group") || t.hasClass("add-rule") || t.hasClass("delete-group") || t.hasClass("delete-rule") || t.hasClass("fm-button") && t.is("[id$=_query]") ? S.closeOnEscape && 27 === e.which ? ($("#" + $.jgrid.jqID(l.modalhead)).find(".ui-jqdialog-titlebar-close").click(), !1) : void 0 : ($("#" + i + "_search").click(), !1) }), v && $("#" + i + "_query").on("click", function () { return $(".queryresult", p).toggle(), !1 }), void 0 === S.stringResult && (S.stringResult = S.multipleSearch), $("#" + i + "_search").on("click", function () { var e, t = {}; return (r = $("#" + i)).find(".input-elm:focus").change(), w && S.multipleSearch ? (o.p._savedFilter = {}, e = $.jgrid.filterRefactor({ ruleGroup: $.extend(!0, {}, r.jqFilter("filterData")), ssfield: x, splitSelect: S.splitSelect, groupOpSelect: S.groupOpSelect }), o.p._savedFilter = $.extend(!0, {}, r.jqFilter("filterData"))) : e = r.jqFilter("filterData"), S.errorcheck && (r[0].hideError(), S.showQuery || r.jqFilter("toSQLString"), r[0].p.error) ? r[0].showError() : (S.stringResult ? (t[S.sFilter] = JSON.stringify(e), $.each([S.sField, S.sValue, S.sOper], function () { t[this] = "" })) : S.multipleSearch ? (t[S.sFilter] = e, $.each([S.sField, S.sValue, S.sOper], function () { t[this] = "" })) : (t[S.sField] = e.rules[0].field, t[S.sValue] = e.rules[0].data, t[S.sOper] = e.rules[0].op, t[S.sFilter] = ""), "string" != typeof t[S.sFilter] && (t[S.sFilter] = JSON.stringify(t[S.sFilter])), (o.p.search = !0) === o.p.mergeSearch && o.p.searchModules.hasOwnProperty("searchGrid") && !1 !== o.p.searchModules.searchGrid ? ("" !== t[S.sFilter] ? o.p.searchModules.searchGrid = t[S.sFilter] : o.p.searchModules.searchGrid = null, $.extend(o.p.postData, { filters: $.jgrid.splitSearch(o.p.searchModules) })) : $.extend(o.p.postData, t), void 0 === (n = $(o).triggerHandler("jqGridFilterSearch")) && (n = !0), n && $.isFunction(S.onSearch) && (n = S.onSearch.call(o, o.p.filters)), !1 !== n && $(o).trigger("reloadGrid", [{ page: 1 }]), S.closeAfterSearch && $.jgrid.hideModal("#" + $.jgrid.jqID(l.themodal), { gb: "#gbox_" + $.jgrid.jqID(o.p.id), jqm: S.jqModal, onClose: S.onClose })), !1 }), $("#" + i + "_reset").on("click", function () { var e = {}, t = $("#" + i); return o.p.search = !1, !(o.p.resetsearch = !0) === S.multipleSearch ? e[S.sField] = e[S.sValue] = e[S.sOper] = "" : e[S.sFilter] = "", t[0].resetFilter(), j && $(".ui-template", p).val("default"), !0 === o.p.mergeSearch && o.p.searchModules.hasOwnProperty("searchGrid") && !1 !== o.p.searchModules.searchGrid ? (o.p.searchModules.searchGrid = null, $.extend(o.p.postData, { filters: $.jgrid.splitSearch(o.p.searchModules) }), o.p.search = !0) : $.extend(o.p.postData, e), void 0 === (n = $(o).triggerHandler("jqGridFilterReset")) && (n = !0), n && $.isFunction(S.onReset) && (n = S.onReset.call(o)), !1 !== n && $(o).trigger("reloadGrid", [{ page: 1 }]), S.closeAfterReset && $.jgrid.hideModal("#" + $.jgrid.jqID(l.themodal), { gb: "#gbox_" + $.jgrid.jqID(o.p.id), jqm: S.jqModal, onClose: S.onClose }), !1 }), k($("#" + i)), $(".fm-button:not(." + d.disabled + ")", p).hover(function () { $(this).addClass(d.hover) }, function () { $(this).removeClass(d.hover) }) } } function k(e) { void 0 === (a = $(o).triggerHandler("jqGridFilterBeforeShow", [e])) && (a = !0), a && $.isFunction(S.beforeShowSearch) && (a = S.beforeShowSearch.call(o, e)), a && ($.jgrid.viewModal("#" + $.jgrid.jqID(l.themodal), { gbox: "#gbox_" + $.jgrid.jqID(o.p.id), jqm: S.jqModal, modal: S.modal, overlay: S.overlay, toTop: S.toTop }), $(o).triggerHandler("jqGridFilterAfterShow", [e]), $.isFunction(S.afterShowSearch) && S.afterShowSearch.call(o, e)) } }) }, filterInput: function (n, l) { return l = $.extend(!0, { defaultSearch: "cn", groupOp: "OR", searchAll: !1, beforeSearch: null, afterSearch: null }, l || {}), this.each(function () { var e, t, r, i, o, a = this; a.grid && (t = '{"groupOp":"' + l.groupOp + '","rules":[', r = 0, n += "", "local" === a.p.datatype && ($.each(a.p.colModel, function () { e = this.index || this.name, i = this.searchoptions || {}, i = l.defaultSearch || (i.sopt ? i.sopt[0] : l.defaultSearch), this.search = !1 !== this.search, (this.search || l.searchAll) && (0 < r && (t += ","), t += '{"field":"' + e + '",', t += '"op":"' + i + '",', t += '"data":"' + n.replace(/\\/g, "\\\\").replace(/\"/g, '\\"') + '"}', r++) }), t += "]}", !0 === a.p.mergeSearch && a.p.searchModules.hasOwnProperty("filterInput") && !1 !== a.p.searchModules.filterInput ? (a.p.searchModules.filterInput = 0 < r ? t : null, $.extend(a.p.postData, { filters: $.jgrid.splitSearch(a.p.searchModules) })) : $.extend(a.p.postData, { filters: t }), $.each(["searchField", "searchString", "searchOper"], function (e, t) { a.p.postData.hasOwnProperty(t) && delete a.p.postData[t] }), !(o = "stop" === $(a).triggerHandler("jqGridFilterInputBeforeSearch")) && $.isFunction(l.beforeSearch) && (o = l.beforeSearch.call(a)), o || $(a).jqGrid("setGridParam", { search: !0 }).trigger("reloadGrid", [{ page: 1 }]), $(a).triggerHandler("jqGridFilterInputAfterSearch"), $.isFunction(l.afterSearch) && l.afterSearch.call(a))) }) }, autoSelect: function (p) { return p = $.extend(!0, { field: "", direction: "asc", src_date: "Y-m-d", allValues: "All", count_item: !0, create_value: !0 }, p || {}), this.each(function () { var e, t = this, r = ""; if (p.field && t.p.data && $.isArray(t.p.data)) { var i, o, a, n, l, s, d = []; try { s = (l = $.jgrid.from.call(t, t.p.data).groupBy(p.field, p.direction, "text", p.src_date)).length } catch (e) { } if (l && l.length) { for (i = $("#gsh_" + t.p.id + "_" + p.field).find("td.ui-search-input > select"), s = l.length, p.allValues && (r = "<option value=''>" + p.allValues + "</option>", d.push(":" + p.allValues)); s--;)e = l[s], o = p.count_item ? " (" + e.items.length + ")" : "", r += "<option value='" + e.unique + "'>" + e.unique + o + "</option>", d.push(e.unique + ":" + e.unique + o); if (i.append(r), i.on("change", function () { t.triggerToolbar() }), p.create_value) { for (s = 0, n = t.p.colModel.length; s < n; s++)if (t.p.colModel[s].name === p.field) { a = t.p.colModel[s]; break } a && (a.searchoptions ? $.extend(a.searchoptions, { value: d.join(";") }) : (a.searchoptions = {}, a.searchoptions.value = d.join(";"))) } } } }) } }); var rp_ge = {}, setSelected; function _pivotfilter(e, t) { var r, i, o, a = []; if (!this || "function" != typeof e || e instanceof RegExp) throw new TypeError; for (o = this.length, r = 0; r < o; r++)if (this.hasOwnProperty(r) && (i = this[r], e.call(t, i, r, this))) { a.push(i); break } return a } $.jgrid.extend({ editGridRow: function (N, O) { var e = $.jgrid.getRegional(this[0], "edit"), t = this[0].p.styleUI, T = $.jgrid.styleUI[t].formedit, A = $.jgrid.styleUI[t].common; return O = $.extend(!0, { top: 0, left: 0, width: "500", datawidth: "auto", height: "auto", dataheight: "auto", modal: !1, overlay: 30, drag: !0, resize: !0, url: null, mtype: "POST", clearAfterAdd: !0, closeAfterEdit: !1, reloadAfterSubmit: !0, onInitializeForm: null, beforeInitData: null, beforeShowForm: null, afterShowForm: null, beforeSubmit: null, afterSubmit: null, onclickSubmit: null, afterComplete: null, onclickPgButtons: null, afterclickPgButtons: null, editData: {}, recreateForm: !1, jqModal: !0, closeOnEscape: !1, addedrow: "first", topinfo: "", bottominfo: "", saveicon: [], closeicon: [], savekey: [!1, 13], navkeys: [!1, 38, 40], checkOnSubmit: !1, checkOnUpdate: !1, processing: !1, onClose: null, ajaxEditOptions: {}, serializeEditData: null, viewPagerButtons: !0, overlayClass: A.overlay, removemodal: !0, form: "edit", template: null, focusField: !0, editselected: !1, html5Check: !1, buttons: [] }, e, O || {}), rp_ge[$(this)[0].p.id] = O, this.each(function () { var u, h, g, t, r, f, m, w, v, x, i, e, o, a, n, l, s, d, p, c, b, j, y, _, q, I = this; function D() { var e, t, i = {}; for (e in $(h).find(".FormElement").each(function () { var e, t = $(".customelement", this); if (t.length) { var t = t[0], r = $(t).attr("name"); $.each(I.p.colModel, function () { if (this.name === r && this.editoptions && $.isFunction(this.editoptions.custom_value)) { try { if (f[r] = this.editoptions.custom_value.call(I, $("#" + $.jgrid.jqID(r), h), "get"), void 0 === f[r]) throw "e1" } catch (e) { "e1" === e ? $.jgrid.info_dialog(v.errcap, "function 'custom_value' " + rp_ge[$(this)[0]].p.msg.novalue, rp_ge[$(this)[0]].p.bClose, { styleUI: rp_ge[$(this)[0]].p.styleUI }) : $.jgrid.info_dialog(v.errcap, e.message, rp_ge[$(this)[0]].p.bClose, { styleUI: rp_ge[$(this)[0]].p.styleUI }) } return !0 } }) } else { switch ($(this).get(0).type) { case "checkbox": $(this).is(":checked") ? f[this.name] = $(this).val() : (e = $(this).attr("offval"), f[this.name] = e); break; case "select-one": f[this.name] = $(this).val(); break; case "select-multiple": f[this.name] = $(this).val(), f[this.name] = f[this.name] ? f[this.name].join(",") : ""; break; case "radio": if (i.hasOwnProperty(this.name)) return !0; i[this.name] = void 0 === $(this).attr("offval") ? "off" : $(this).attr("offval"); break; default: f[this.name] = $(this).val() }I.p.autoencode && (f[this.name] = $.jgrid.htmlEncode(f[this.name])) } }), i) i.hasOwnProperty(e) && (t = $('input[name="' + e + '"]:checked', h).val(), f[e] = void 0 !== t ? t : i[e], I.p.autoencode && (f[e] = $.jgrid.htmlEncode(f[e]))); return 1 } function C(r, i, o) { var a, n, e, t, l, s = 0; (rp_ge[I.p.id].checkOnSubmit || rp_ge[I.p.id].checkOnUpdate) && (I.p.savedData = {}, I.p.savedData[i.p.id + "_id"] = r); var d = i.p.colModel; if ("_empty" === r) return $(d).each(function () { a = this.name, l = $.extend({}, this.editoptions || {}), (e = $("#" + $.jgrid.jqID(a), o)) && e.length && null !== e[0] && (t = "", "custom" === this.edittype && $.isFunction(l.custom_value) ? l.custom_value.call(I, $("#" + a, o), "set", t) : l.defaultValue ? (t = $.isFunction(l.defaultValue) ? l.defaultValue.call(I) : l.defaultValue, "checkbox" === e[0].type ? (l = t.toLowerCase()).search(/(false|f|0|no|n|off|undefined)/i) < 0 && "" !== l ? (e[0].checked = !0, e[0].defaultChecked = !0, e[0].value = t) : (e[0].checked = !1, e[0].defaultChecked = !1) : e.val(t)) : "checkbox" === e[0].type ? (e[0].checked = !1, e[0].defaultChecked = !1, t = $(e).attr("offval")) : e[0].type && "select" === e[0].type.substr(0, 6) ? e[0].selectedIndex = 0 : e.val(t), !0 !== rp_ge[I.p.id].checkOnSubmit && !rp_ge[I.p.id].checkOnUpdate || (I.p.savedData[a] = t)) }), void $("#id_g", o).val(r); var p = $(i).jqGrid("getInd", r, !0); p && ($('td[role="gridcell"]', p).each(function (t) { if ("cb" !== (a = d[t].name) && "subgrid" !== a && "rn" !== a && !0 === d[t].editable) { if (a === i.p.ExpandColumn && !0 === i.p.treeGrid) n = $(this).text(); else try { n = $.unformat.call(i, $(this), { rowId: r, colModel: d[t] }, t) } catch (e) { n = "textarea" === d[t].edittype ? $(this).text() : $(this).html() } switch (I.p.autoencode && (n = $.jgrid.htmlDecode(n)), !0 !== rp_ge[I.p.id].checkOnSubmit && !rp_ge[I.p.id].checkOnUpdate || (I.p.savedData[a] = n), a = $.jgrid.jqID(a), d[t].edittype) { case "select": var e = n.split(","), e = $.map(e, function (e) { return $.trim(e) }); $("#" + a + " option", o).each(function () { !(d[t].editoptions.multiple || $.trim(n) !== $.trim($(this).text()) && e[0] !== $.trim($(this).text()) && e[0] !== $.trim($(this).val())) || d[t].editoptions.multiple && (-1 < $.inArray($.trim($(this).text()), e) || -1 < $.inArray($.trim($(this).val()), e)) ? this.selected = !0 : this.selected = !1 }), !0 !== rp_ge[I.p.id].checkOnSubmit && !rp_ge[I.p.id].checkOnUpdate || (n = $("#" + a, o).val(), d[t].editoptions.multiple && (n = n.join(",")), I.p.savedData[a] = n); break; case "checkbox": n = String(n), d[t].editoptions && d[t].editoptions.value ? d[t].editoptions.value.split(":")[0] === n ? $("#" + a, o)[I.p.useProp ? "prop" : "attr"]({ checked: !0, defaultChecked: !0 }) : $("#" + a, o)[I.p.useProp ? "prop" : "attr"]({ checked: !1, defaultChecked: !1 }) : (n = n.toLowerCase()).search(/(false|f|0|no|n|off|undefined)/i) < 0 && "" !== n ? ($("#" + a, o)[I.p.useProp ? "prop" : "attr"]("checked", !0), $("#" + a, o)[I.p.useProp ? "prop" : "attr"]("defaultChecked", !0)) : ($("#" + a, o)[I.p.useProp ? "prop" : "attr"]("checked", !1), $("#" + a, o)[I.p.useProp ? "prop" : "attr"]("defaultChecked", !1)), !0 !== rp_ge[I.p.id].checkOnSubmit && !rp_ge[I.p.id].checkOnUpdate || (n = $("#" + a, o).is(":checked") ? $("#" + a, o).val() : $("#" + a, o).attr("offval"), I.p.savedData[a] = n); break; case "custom": try { if (!d[t].editoptions || !$.isFunction(d[t].editoptions.custom_value)) throw "e1"; d[t].editoptions.custom_value.call(I, $("#" + a, o), "set", n) } catch (e) { "e1" === e ? $.jgrid.info_dialog(v.errcap, "function 'custom_value' " + rp_ge[$(this)[0]].p.msg.nodefined, $.rp_ge[$(this)[0]].p.bClose, { styleUI: rp_ge[$(this)[0]].p.styleUI }) : $.jgrid.info_dialog(v.errcap, e.message, $.rp_ge[$(this)[0]].p.bClose, { styleUI: rp_ge[$(this)[0]].p.styleUI }) } break; default: ("&nbsp;" === n || "&#160;" === n || 1 === n.length && 160 === n.charCodeAt(0)) && (n = ""), $("#" + a, o).val(n) }s++ } }), 0 < s && ($("#id_g", h).val(r), !0 !== rp_ge[I.p.id].checkOnSubmit && !rp_ge[I.p.id].checkOnUpdate || (I.p.savedData[i.p.id + "_id"] = r))) } function F() { var i, o, a, e, n, t, r, l = [!0, "", ""], s = {}, d = I.p.prmNames, p = $(I).triggerHandler("jqGridAddEditBeforeCheckValues", [f, $(q), m]); if (p && "object" == typeof p && (f = p), $.isFunction(rp_ge[I.p.id].beforeCheckValues) && (p = rp_ge[I.p.id].beforeCheckValues.call(I, f, $(q), m)) && "object" == typeof p && (f = p), !rp_ge[I.p.id].html5Check || $.jgrid.validateForm(x[0])) { for (e in f) if (f.hasOwnProperty(e) && !1 === (l = $.jgrid.checkValues.call(I, f[e], e))[0]) break; if ($.each(I.p.colModel, function (e, t) { t.editoptions && !0 === t.editoptions.NullIfEmpty && f.hasOwnProperty(t.name) && "" === f[t.name] && (f[t.name] = "null") }), l[0] && (void 0 === (s = $(I).triggerHandler("jqGridAddEditClickSubmit", [rp_ge[I.p.id], f, m])) && $.isFunction(rp_ge[I.p.id].onclickSubmit) && (s = rp_ge[I.p.id].onclickSubmit.call(I, rp_ge[I.p.id], f, m) || {}), void 0 === (l = $(I).triggerHandler("jqGridAddEditBeforeSubmit", [f, $(q), m])) && (l = [!0, "", ""]), l[0] && $.isFunction(rp_ge[I.p.id].beforeSubmit) && (l = rp_ge[I.p.id].beforeSubmit.call(I, f, $(q), m))), l[0] && !rp_ge[I.p.id].processing) { if (rp_ge[I.p.id].processing = !0, $("#sData", h + "_2").addClass(A.active), p = rp_ge[I.p.id].url || $(I).jqGrid("getGridParam", "editurl"), a = d.oper, o = "clientArray" === p ? I.p.keyName : d.id, f[a] = "_empty" === $.trim(f[I.p.id + "_id"]) ? d.addoper : d.editoper, f[a] === d.addoper && void 0 !== f[o] || (f[o] = f[I.p.id + "_id"]), delete f[I.p.id + "_id"], f = $.extend(f, rp_ge[I.p.id].editData, s), !0 === I.p.treeGrid) for (t in f[a] === d.addoper && (n = $(I).jqGrid("getGridParam", "selrow"), c = "adjacency" === I.p.treeGridModel ? I.p.treeReader.parent_id_field : "parent_id", f[c] = n), I.p.treeReader) I.p.treeReader.hasOwnProperty(t) && (r = I.p.treeReader[t], f.hasOwnProperty(r) && (f[a] === d.addoper && "parent_id_field" === t || delete f[r])); f[o] = $.jgrid.stripPref(I.p.idPrefix, f[o]); var c = $.extend({ url: p, type: rp_ge[I.p.id].mtype, data: $.isFunction(rp_ge[I.p.id].serializeEditData) ? rp_ge[I.p.id].serializeEditData.call(I, f) : f, complete: function (e, t) { if ($("#sData", h + "_2").removeClass(A.active), f[o] = I.p.idPrefix + f[o], 300 <= e.status && 304 !== e.status ? (l[0] = !1, l[1] = $(I).triggerHandler("jqGridAddEditErrorTextFormat", [e, m]), $.isFunction(rp_ge[I.p.id].errorTextFormat) ? l[1] = rp_ge[I.p.id].errorTextFormat.call(I, e, m) : l[1] = t + " Status: '" + e.statusText + "'. Error code: " + e.status) : (void 0 === (l = $(I).triggerHandler("jqGridAddEditAfterSubmit", [e, f, m])) && (l = [!0, "", ""]), l[0] && $.isFunction(rp_ge[I.p.id].afterSubmit) && (l = rp_ge[I.p.id].afterSubmit.call(I, e, f, m))), !1 === l[0]) $(".FormError", q).html(l[1]), $(".FormError", q).show(); else if (I.p.autoencode && $.each(f, function (e, t) { f[e] = $.jgrid.htmlDecode(t) }), f[a] === d.addoper ? (l[2] || (l[2] = $.jgrid.randId()), null == f[o] || f[o] === I.p.idPrefix + "_empty" || "" === f[o] ? f[o] = l[2] : l[2] = f[o], rp_ge[I.p.id].reloadAfterSubmit ? $(I).trigger("reloadGrid") : !0 === I.p.treeGrid ? $(I).jqGrid("addChildNode", l[2], n, f) : $(I).jqGrid("addRowData", l[2], f, O.addedrow), rp_ge[I.p.id].closeAfterAdd ? (!0 !== I.p.treeGrid && $(I).jqGrid("setSelection", l[2]), $.jgrid.hideModal("#" + $.jgrid.jqID(g.themodal), { gb: "#gbox_" + $.jgrid.jqID(u), jqm: O.jqModal, onClose: rp_ge[I.p.id].onClose, removemodal: rp_ge[I.p.id].removemodal, formprop: !rp_ge[I.p.id].recreateForm, form: rp_ge[I.p.id].form })) : rp_ge[I.p.id].clearAfterAdd && C("_empty", I, q)) : (rp_ge[I.p.id].reloadAfterSubmit ? ($(I).trigger("reloadGrid"), rp_ge[I.p.id].closeAfterEdit || setTimeout(function () { $(I).jqGrid("setSelection", f[o]) }, 1e3)) : !0 === I.p.treeGrid ? $(I).jqGrid("setTreeRow", f[o], f) : $(I).jqGrid("setRowData", f[o], f), rp_ge[I.p.id].closeAfterEdit && $.jgrid.hideModal("#" + $.jgrid.jqID(g.themodal), { gb: "#gbox_" + $.jgrid.jqID(u), jqm: O.jqModal, onClose: rp_ge[I.p.id].onClose, removemodal: rp_ge[I.p.id].removemodal, formprop: !rp_ge[I.p.id].recreateForm, form: rp_ge[I.p.id].form })), ($.isFunction(rp_ge[I.p.id].afterComplete) || Object.prototype.hasOwnProperty.call($._data($(I)[0], "events"), "jqGridAddEditAfterComplete")) && (i = e, setTimeout(function () { $(I).triggerHandler("jqGridAddEditAfterComplete", [i, f, $(q), m]); try { rp_ge[I.p.id].afterComplete.call(I, i, f, $(q), m) } catch (e) { } i = null }, 500)), (rp_ge[I.p.id].checkOnSubmit || rp_ge[I.p.id].checkOnUpdate) && ($(q).data("disabled", !1), "_empty" !== I.p.savedData[I.p.id + "_id"])) for (var r in I.p.savedData) I.p.savedData.hasOwnProperty(r) && f[r] && (I.p.savedData[r] = f[r]); rp_ge[I.p.id].processing = !1; try { $(":input:visible", q)[0].focus() } catch (e) { } } }, $.jgrid.ajaxOptions, rp_ge[I.p.id].ajaxEditOptions); c.url || rp_ge[I.p.id].useDataProxy || ($.isFunction(I.p.dataProxy) ? rp_ge[I.p.id].useDataProxy = !0 : (l[0] = !1, l[1] += " " + v.nourl)), l[0] && (rp_ge[I.p.id].useDataProxy ? (void 0 === (p = I.p.dataProxy.call(I, c, "set_" + I.p.id)) && (p = [!0, ""]), !1 === p[0] ? (l[0] = !1, l[1] = p[1] || "Error deleting the selected row!") : (c.data.oper === d.addoper && rp_ge[I.p.id].closeAfterAdd && $.jgrid.hideModal("#" + $.jgrid.jqID(g.themodal), { gb: "#gbox_" + $.jgrid.jqID(u), jqm: O.jqModal, onClose: rp_ge[I.p.id].onClose, removemodal: rp_ge[I.p.id].removemodal, formprop: !rp_ge[I.p.id].recreateForm, form: rp_ge[I.p.id].form }), c.data.oper === d.editoper && rp_ge[I.p.id].closeAfterEdit && $.jgrid.hideModal("#" + $.jgrid.jqID(g.themodal), { gb: "#gbox_" + $.jgrid.jqID(u), jqm: O.jqModal, onClose: rp_ge[I.p.id].onClose, removemodal: rp_ge[I.p.id].removemodal, formprop: !rp_ge[I.p.id].recreateForm, form: rp_ge[I.p.id].form }))) : "clientArray" === c.url ? (rp_ge[I.p.id].reloadAfterSubmit = !1, f = c.data, c.complete({ status: 200, statusText: "" }, "")) : $.ajax(c)) } !1 === l[0] && ($(".FormError", q).html(l[1]), $(".FormError", q).show()) } } function G(e, t) { var r, i = !1; if (!(i = !($.isPlainObject(e) && $.isPlainObject(t) && Object.getOwnPropertyNames(e).length === Object.getOwnPropertyNames(t).length))) for (r in t) if (t.hasOwnProperty(r)) { if (!e.hasOwnProperty(r)) { i = !0; break } if (e[r] !== t[r]) { i = !0; break } } return i } function k() { var e = !0; return $(".FormError", q).hide(), rp_ge[I.p.id].checkOnUpdate && (f = {}, D(), G(f, I.p.savedData) && ($(q).data("disabled", !0), $(".confirm", "#" + g.themodal).show(), e = !1)), e } function S(e, t) { var r = t[1].length - 1; 0 === e || void 0 !== t[1][e - 1] && $("#" + $.jgrid.jqID(t[1][e - 1])).hasClass(A.disabled) ? $("#pData", _).addClass(A.disabled) : $("#pData", _).removeClass(A.disabled), e === r || void 0 !== t[1][e + 1] && $("#" + $.jgrid.jqID(t[1][e + 1])).hasClass(A.disabled) ? $("#nData", _).addClass(A.disabled) : $("#nData", _).removeClass(A.disabled) } function R() { var e = $(I).jqGrid("getDataIDs"), t = $("#id_g", h).val(); if (I.p.multiselect && rp_ge[I.p.id].editselected) { for (var r = [], i = 0, o = e.length; i < o; i++)-1 !== $.inArray(e[i], I.p.selarrrow) && r.push(e[i]); return [$.inArray(t, r), r] } return [$.inArray(t, e), e] } function M() { if (rp_ge[I.p.id].checkOnSubmit || rp_ge[I.p.id].checkOnUpdate) { var e, t, r = [], i = {}, r = $.map(I.p.savedData, function (e, t) { return t }); for (e in $(".FormElement", x).each(function () { if ("" !== $.trim(this.name) && -1 === r.indexOf(this.name)) { var e = $(this).val(), t = $(this).get(0).type; if ("checkbox" === t) $(this).is(":checked") || (e = $(this).attr("offval")); else if ("select-multiple" === t) e = e.join(","); else if ("radio" === t) { if (i.hasOwnProperty(this.name)) return !0; i[this.name] = void 0 === $(this).attr("offval") ? "off" : $(this).attr("offval") } I.p.savedData[this.name] = e } }), i) i.hasOwnProperty(e) && (t = $('input[name="' + e + '"]:checked', x).val(), I.p.savedData[e] = void 0 !== t ? t : i[e]) } } I.grid && N && (I.p.savedData = {}, u = I.p.id, q = "FrmGrid_" + u, b = "TblGrid_" + u, h = "#" + $.jgrid.jqID(b), g = { themodal: "editmod" + u, modalhead: "edithd" + u, modalcontent: "editcnt" + u, scrollelm: q }, s = !0, t = 1, r = 0, w = "string" == typeof rp_ge[I.p.id].template && 0 < rp_ge[I.p.id].template.length, v = $.jgrid.getRegional(this, "errors"), rp_ge[I.p.id].styleUI = I.p.styleUI || "jQueryUI", $.jgrid.isMobile() && (rp_ge[I.p.id].resize = !1), "new" === N ? (N = "_empty", m = "add", O.caption = rp_ge[I.p.id].addCaption) : (O.caption = rp_ge[I.p.id].editCaption, m = "edit"), O.recreateForm || $(I).data("formProp") && $.extend(rp_ge[$(this)[0].p.id], $(I).data("formProp")), y = !0, O.checkOnUpdate && O.jqModal && !O.modal && (y = !1), l = isNaN(rp_ge[$(this)[0].p.id].dataheight) ? rp_ge[$(this)[0].p.id].dataheight : rp_ge[$(this)[0].p.id].dataheight + "px", n = isNaN(rp_ge[$(this)[0].p.id].datawidth) ? rp_ge[$(this)[0].p.id].datawidth : rp_ge[$(this)[0].p.id].datawidth + "px", x = $("<form name='FormPost' id='" + q + "' class='FormGrid' onSubmit='return false;' style='width:" + n + ";height:" + l + ";'></form>").data("disabled", !1), _ = w ? (e = rp_ge[$(this)[0].p.id].template, o = "", "string" == typeof e && (o = e.replace(/\{([\w\-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g, function (e, t) { return '<span id="' + t + '" ></span>' })), i = o, h) : (i = $("<table id='" + b + "' class='EditTable ui-common-table'><tbody></tbody></table>"), h + "_2"), q = "#" + $.jgrid.jqID(q), $(x).append("<div class='FormError " + A.error + "' style='display:none;'></div>"), $(x).append("<div class='tinfo topinfo'>" + rp_ge[I.p.id].topinfo + "</div>"), $(I.p.colModel).each(function () { var e = this.formoptions; t = Math.max(t, e && e.colpos || 0), r = Math.max(r, e && e.rowpos || 0) }), $(x).append(i), void 0 === (s = $(I).triggerHandler("jqGridAddEditBeforeInitData", [x, m])) && (s = !0), s && $.isFunction(rp_ge[I.p.id].beforeInitData) && (s = rp_ge[I.p.id].beforeInitData.call(I, x, m)), !1 !== s && (function () { var e; if ("_empty" !== N && void 0 !== I.p.savedRow && 0 < I.p.savedRow.length && $.isFunction($.fn.jqGrid.restoreRow)) for (e = 0; e < I.p.savedRow.length; e++)if (I.p.savedRow[e].id === N) { $(I).jqGrid("restoreRow", N); break } }(), function (n, l, s, d) { for (var p, c, u, h, g, f, m, e, v = 0, b = [], j = !1, y = "", t = 1; t <= d; t++)y += "<td class='CaptionTD'></td><td class='DataTD'></td>"; "_empty" !== n && (j = $(l).jqGrid("getInd", n)), $(l.p.colModel).each(function (t) { if (p = this.name, c = (!this.editrules || !0 !== this.editrules.edithidden) && !0 === this.hidden, g = c ? "style='display:none'" : "", "cb" !== p && "subgrid" !== p && !0 === this.editable && "rn" !== p) { if (!1 === j) h = ""; else if (p === l.p.ExpandColumn && !0 === l.p.treeGrid) h = $("td[role='gridcell']:eq(" + t + ")", l.rows[j]).text(); else { try { h = $.unformat.call(l, $("td[role='gridcell']:eq(" + t + ")", l.rows[j]), { rowId: n, colModel: this }, t) } catch (e) { h = this.edittype && "textarea" === this.edittype ? $("td[role='gridcell']:eq(" + t + ")", l.rows[j]).text() : $("td[role='gridcell']:eq(" + t + ")", l.rows[j]).html() } h && "&nbsp;" !== h && "&#160;" !== h && (1 !== h.length || 160 !== h.charCodeAt(0)) || (h = "") } var e, r = $.extend({}, this.editoptions || {}, { id: p, name: p, rowId: n, oper: "edit", module: "form", checkUpdate: rp_ge[I.p.id].checkOnSubmit || rp_ge[I.p.id].checkOnUpdate }), i = $.extend({}, { elmprefix: "", elmsuffix: "", rowabove: !1, rowcontent: "" }, this.formoptions || {}), o = parseInt(i.rowpos, 10) || v + 1, a = parseInt(2 * (parseInt(i.colpos, 10) || 1), 10); "_empty" === n && r.defaultValue && (h = $.isFunction(r.defaultValue) ? r.defaultValue.call(I) : r.defaultValue), this.edittype || (this.edittype = "text"), I.p.autoencode && (h = $.jgrid.htmlDecode(h)), f = $.jgrid.createEl.call(I, this.edittype, r, h, !1, $.extend({}, $.jgrid.ajaxOptions, l.p.ajaxSelectOptions || {})), "select" === this.edittype && (h = $(f).val(), "select-multiple" === $(f).get(0).type && h && (h = h.join(","))), "checkbox" === this.edittype && (h = $(f).is(":checked") ? $(f).val() : $(f).attr("offval")), $(f).addClass("FormElement"), -1 < $.inArray(this.edittype, ["text", "textarea", "password", "select", "color", "date", "datetime", "datetime-local", "email", "month", "number", "range", "search", "tel", "time", "url", "week"]) && $(f).addClass(T.inputClass), m = !0, w ? (e = $(x).find("#" + p)).length ? e.replaceWith(f) : m = !1 : (u = $(s).find("tr[rowpos=" + o + "]"), i.rowabove && (e = $("<tr><td class='contentinfo' colspan='" + 2 * d + "'>" + i.rowcontent + "</td></tr>"), $(s).append(e), e[0].rp = o), 0 === u.length && (u = $(1 < d ? "<tr rowpos='" + o + "'></tr>" : "<tr " + g + " rowpos='" + o + "'></tr>").addClass("FormData").attr("id", "tr_" + p), $(u).append(y), $(s).append(u), u[0].rp = o), $("td:eq(" + (a - 2) + ")", u[0]).html("<label for='" + p + "'>" + (void 0 === i.label ? l.p.colNames[t] : i.label) + "</label>"), $("td:eq(" + (a - 1) + ")", u[0]).append(i.elmprefix).append(f).append(i.elmsuffix), 1 < d && c && ($("td:eq(" + (a - 2) + ")", u[0]).hide(), $("td:eq(" + (a - 1) + ")", u[0]).hide())), (rp_ge[I.p.id].checkOnSubmit || rp_ge[I.p.id].checkOnUpdate) && m && (I.p.savedData[p] = h), "custom" === this.edittype && $.isFunction(r.custom_value) && r.custom_value.call(I, $("#" + p, q), "set", h), $.jgrid.bindEv.call(I, f, r), b[v] = t, v++ } }), 0 < v && (w ? (e = "<div class='FormData' style='display:none'><input class='FormElement' id='id_g' type='text' name='" + l.p.id + "_id' value='" + n + "'/>", $(x).append(e)) : ((e = $("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='" + (2 * d - 1) + "' class='DataTD'><input class='FormElement' id='id_g' type='text' name='" + l.p.id + "_id' value='" + n + "'/></td></tr>"))[0].rp = v + 999, $(s).append(e)), (rp_ge[I.p.id].checkOnSubmit || rp_ge[I.p.id].checkOnUpdate) && (I.p.savedData[l.p.id + "_id"] = n)) }(N, I, i, t), j = (a = "rtl" === I.p.direction) ? "pData" : "nData", c = "<a id='" + (a ? "nData" : "pData") + "' class='fm-button " + A.button + "'><span class='" + A.icon_base + " " + T.icon_prev + "'></span></a>", n = "<a id='" + j + "' class='fm-button " + A.button + "'><span class='" + A.icon_base + " " + T.icon_next + "'></span></a>", l = "<a id='sData' class='fm-button " + A.button + "'>" + O.bSubmit + "</a>", s = "<a id='cData' class='fm-button " + A.button + "'>" + O.bCancel + "</a>", j = $.isArray(rp_ge[I.p.id].buttons) ? $.jgrid.buildButtons(rp_ge[I.p.id].buttons, l + s, A) : l + s, j = "<table style='height:auto' class='EditTable ui-common-table' id='" + b + "_2'><tbody><tr><td colspan='2'><hr class='" + A.content + "' style='margin:1px'/></td></tr><tr id='Act_Buttons'><td class='navButton'>" + (a ? n + c : c + n) + "</td><td class='EditButton'>" + j + "</td></tr>", j += "</tbody></table>", 0 < r && (d = [], $.each($(i)[0].rows, function (e, t) { d[e] = t }), d.sort(function (e, t) { return e.rp > t.rp ? 1 : e.rp < t.rp ? -1 : 0 }), $.each(d, function (e, t) { $("tbody", i).append(t) })), O.gbox = "#gbox_" + $.jgrid.jqID(u), !(p = !1) === O.closeOnEscape && (O.closeOnEscape = !1, p = !0), c = w ? ($(x).find("#pData").replaceWith(c), $(x).find("#nData").replaceWith(n), $(x).find("#sData").replaceWith(l), $(x).find("#cData").replaceWith(s), $("<div id=" + b + "></div>").append(x)) : $("<div></div>").append(x).append(j), $(x).append("<div class='binfo topinfo bottominfo'>" + rp_ge[I.p.id].bottominfo + "</div>"), b = $(".ui-jqgrid").css("font-size") || "11px", $.jgrid.createModal(g, c, rp_ge[$(this)[0].p.id], "#gview_" + $.jgrid.jqID(I.p.id), $("#gbox_" + $.jgrid.jqID(I.p.id))[0], null, { "font-size": b }), a && ($("#pData, #nData", h + "_2").css("float", "right"), $(".EditButton", h + "_2").css("text-align", "left")), rp_ge[I.p.id].topinfo && $(".tinfo", q).show(), rp_ge[I.p.id].bottominfo && $(".binfo", q).show(), j = c = null, $("#" + $.jgrid.jqID(g.themodal)).keydown(function (e) { var t = e.target; return !0 !== $(q).data("disabled") && (!0 === rp_ge[I.p.id].savekey[0] && e.which === rp_ge[I.p.id].savekey[1] && "TEXTAREA" !== t.tagName ? ($("#sData", h + "_2").trigger("click"), !1) : 27 === e.which ? (k() && p && $.jgrid.hideModal("#" + $.jgrid.jqID(g.themodal), { gb: O.gbox, jqm: O.jqModal, onClose: rp_ge[I.p.id].onClose, removemodal: rp_ge[I.p.id].removemodal, formprop: !rp_ge[I.p.id].recreateForm, form: rp_ge[I.p.id].form }), !1) : !0 === rp_ge[I.p.id].navkeys[0] ? "_empty" === $("#id_g", h).val() || (e.which === rp_ge[I.p.id].navkeys[1] ? ($("#pData", _).trigger("click"), !1) : e.which === rp_ge[I.p.id].navkeys[2] ? ($("#nData", _).trigger("click"), !1) : void 0) : void 0) }), O.checkOnUpdate && ($("a.ui-jqdialog-titlebar-close span", "#" + $.jgrid.jqID(g.themodal)).removeClass("jqmClose"), $("a.ui-jqdialog-titlebar-close", "#" + $.jgrid.jqID(g.themodal)).off("click").click(function () { return k() && $.jgrid.hideModal("#" + $.jgrid.jqID(g.themodal), { gb: "#gbox_" + $.jgrid.jqID(u), jqm: O.jqModal, onClose: rp_ge[I.p.id].onClose, removemodal: rp_ge[I.p.id].removemodal, formprop: !rp_ge[I.p.id].recreateForm, form: rp_ge[I.p.id].form }), !1 })), O.saveicon = $.extend([!0, "left", T.icon_save], O.saveicon), O.closeicon = $.extend([!0, "left", T.icon_close], O.closeicon), !0 === O.saveicon[0] && $("#sData", _).addClass("right" === O.saveicon[1] ? "fm-button-icon-right" : "fm-button-icon-left").append("<span class='" + A.icon_base + " " + O.saveicon[2] + "'></span>"), !0 === O.closeicon[0] && $("#cData", _).addClass("right" === O.closeicon[1] ? "fm-button-icon-right" : "fm-button-icon-left").append("<span class='" + A.icon_base + " " + O.closeicon[2] + "'></span>"), (rp_ge[I.p.id].checkOnSubmit || rp_ge[I.p.id].checkOnUpdate) && (l = "<a id='sNew' class='fm-button " + A.button + "' style='z-index:1002'>" + O.bYes + "</a>", n = "<a id='nNew' class='fm-button " + A.button + "' style='z-index:1002;margin-left:5px'>" + O.bNo + "</a>", s = "<a id='cNew' class='fm-button " + A.button + "' style='z-index:1002;margin-left:5px;'>" + O.bExit + "</a>", j = O.zIndex || 999, j++, $("#" + g.themodal).append("<div class='" + O.overlayClass + " jqgrid-overlay confirm' style='z-index:" + j + ";display:none;position:absolute;'>&#160;</div><div class='confirm ui-jqconfirm " + A.content + "' style='z-index:" + (1 + j) + "'>" + O.saveData + "<br/><br/>" + l + n + s + "</div>"), $("#sNew", "#" + $.jgrid.jqID(g.themodal)).click(function () { return F(), $(q).data("disabled", !1), $(".confirm", "#" + $.jgrid.jqID(g.themodal)).hide(), !1 }), $("#nNew", "#" + $.jgrid.jqID(g.themodal)).click(function () { return $(".confirm", "#" + $.jgrid.jqID(g.themodal)).hide(), $(q).data("disabled", !1), setTimeout(function () { $(":input:visible", q)[0].focus() }, 0), !1 }), $("#cNew", "#" + $.jgrid.jqID(g.themodal)).click(function () { return $(".confirm", "#" + $.jgrid.jqID(g.themodal)).hide(), $(q).data("disabled", !1), $.jgrid.hideModal("#" + $.jgrid.jqID(g.themodal), { gb: "#gbox_" + $.jgrid.jqID(u), jqm: O.jqModal, onClose: rp_ge[I.p.id].onClose, removemodal: rp_ge[I.p.id].removemodal, formprop: !rp_ge[I.p.id].recreateForm, form: rp_ge[I.p.id].form }), !1 })), $(I).triggerHandler("jqGridAddEditInitializeForm", [$(q), m]), $.isFunction(rp_ge[I.p.id].onInitializeForm) && rp_ge[I.p.id].onInitializeForm.call(I, $(q), m), "_empty" !== N && rp_ge[I.p.id].viewPagerButtons ? $("#pData,#nData", _).show() : $("#pData,#nData", _).hide(), $(I).triggerHandler("jqGridAddEditBeforeShowForm", [$(q), m]), $.isFunction(rp_ge[I.p.id].beforeShowForm) && rp_ge[I.p.id].beforeShowForm.call(I, $(q), m), M(), $("#" + $.jgrid.jqID(g.themodal)).data("onClose", rp_ge[I.p.id].onClose), $.jgrid.viewModal("#" + $.jgrid.jqID(g.themodal), { gbox: "#gbox_" + $.jgrid.jqID(u), jqm: O.jqModal, overlay: O.overlay, modal: O.modal, overlayClass: O.overlayClass, focusField: O.focusField, onHide: function (e) { var t = $("#editmod" + u)[0].style.height, r = $("#editmod" + u)[0].style.width, i = "rtl" === $("#gbox_" + $.jgrid.jqID(u)).attr("dir"); -1 < t.indexOf("px") && (t = parseFloat(t)), -1 < r.indexOf("px") && (r = parseFloat(r)), $(I).data("formProp", { top: parseFloat($(e.w).css("top")), left: i ? $("#gbox_" + $.jgrid.jqID(u)).outerWidth() - r - parseFloat($(e.w).css("left")) + 12 : parseFloat($(e.w).css("left")), width: r, height: t, dataheight: $(q).height(), datawidth: $(q).width() }), e.w.remove(), e.o && e.o.remove() } }), y || $("." + $.jgrid.jqID(O.overlayClass)).click(function () { return k() && $.jgrid.hideModal("#" + $.jgrid.jqID(g.themodal), { gb: "#gbox_" + $.jgrid.jqID(u), jqm: O.jqModal, onClose: rp_ge[I.p.id].onClose, removemodal: rp_ge[I.p.id].removemodal, formprop: !rp_ge[I.p.id].recreateForm, form: rp_ge[I.p.id].form }), !1 }), $(".fm-button", "#" + $.jgrid.jqID(g.themodal)).hover(function () { $(this).addClass(A.hover) }, function () { $(this).removeClass(A.hover) }), $("#sData", _).click(function () { return f = {}, $(".FormError", q).hide(), D(), "_empty" !== f[I.p.id + "_id"] && !0 === O.checkOnSubmit && G(f, I.p.savedData) ? ($(q).data("disabled", !0), $(".confirm", "#" + $.jgrid.jqID(g.themodal)).show()) : F(), !1 }), $("#cData", _).click(function () { return k() && $.jgrid.hideModal("#" + $.jgrid.jqID(g.themodal), { gb: "#gbox_" + $.jgrid.jqID(u), jqm: O.jqModal, onClose: rp_ge[I.p.id].onClose, removemodal: rp_ge[I.p.id].removemodal, formprop: !rp_ge[I.p.id].recreateForm, form: rp_ge[I.p.id].form }), !1 }), $(_).find("[data-index]").each(function () { var t = parseInt($(this).attr("data-index"), 10); 0 <= t && O.buttons[t].hasOwnProperty("click") && $(this).on("click", function (e) { O.buttons[t].click.call(I, $(q)[0], rp_ge[I.p.id], e) }) }), $("#nData", _).click(function () { if (!k()) return !1; $(".FormError", q).hide(); var e, t = R(); if (t[0] = parseInt(t[0], 10), -1 !== t[0] && t[1][t[0] + 1]) { if ($(I).triggerHandler("jqGridAddEditClickPgButtons", ["next", $(q), t[1][t[0]]]), $.isFunction(O.onclickPgButtons) && void 0 !== (e = O.onclickPgButtons.call(I, "next", $(q), t[1][t[0]])) && !1 === e) return !1; if ($("#" + $.jgrid.jqID(t[1][t[0] + 1])).hasClass(A.disabled)) return !1; C(t[1][t[0] + 1], I, q), I.p.multiselect && rp_ge[I.p.id].editselected || $(I).jqGrid("setSelection", t[1][t[0] + 1]), $(I).triggerHandler("jqGridAddEditAfterClickPgButtons", ["next", $(q), t[1][t[0]]]), $.isFunction(O.afterclickPgButtons) && O.afterclickPgButtons.call(I, "next", $(q), t[1][t[0] + 1]), M(), S(t[0] + 1, t) } return !1 }), $("#pData", _).click(function () { if (!k()) return !1; $(".FormError", q).hide(); var e, t = R(); if (-1 !== t[0] && t[1][t[0] - 1]) { if ($(I).triggerHandler("jqGridAddEditClickPgButtons", ["prev", $(q), t[1][t[0]]]), $.isFunction(O.onclickPgButtons) && void 0 !== (e = O.onclickPgButtons.call(I, "prev", $(q), t[1][t[0]])) && !1 === e) return !1; if ($("#" + $.jgrid.jqID(t[1][t[0] - 1])).hasClass(A.disabled)) return !1; C(t[1][t[0] - 1], I, q), I.p.multiselect && rp_ge[I.p.id].editselected || $(I).jqGrid("setSelection", t[1][t[0] - 1]), $(I).triggerHandler("jqGridAddEditAfterClickPgButtons", ["prev", $(q), t[1][t[0]]]), $.isFunction(O.afterclickPgButtons) && O.afterclickPgButtons.call(I, "prev", $(q), t[1][t[0] - 1]), M(), S(t[0] - 1, t) } return !1 }), $(I).triggerHandler("jqGridAddEditAfterShowForm", [$(q), m]), $.isFunction(rp_ge[I.p.id].afterShowForm) && rp_ge[I.p.id].afterShowForm.call(I, $(q), m), S((y = R())[0], y))) }) }, viewGridRow: function (j, w) { var e = $.jgrid.getRegional(this[0], "view"), t = this[0].p.styleUI, y = $.jgrid.styleUI[t].formedit, x = $.jgrid.styleUI[t].common; return w = $.extend(!0, { top: 0, left: 0, width: 500, datawidth: "auto", height: "auto", dataheight: "auto", modal: !1, overlay: 30, drag: !0, resize: !0, jqModal: !0, closeOnEscape: !1, labelswidth: "auto", closeicon: [], navkeys: [!1, 38, 40], onClose: null, beforeShowForm: null, beforeInitData: null, viewPagerButtons: !0, recreateForm: !1, removemodal: !0, form: "view", buttons: [] }, e, w || {}), rp_ge[$(this)[0].p.id] = w, this.each(function () { var i, o, l, r, t, a, n, e, s, d, p, c, u, h, g = this; function f() { !0 !== rp_ge[g.p.id].closeOnEscape && !0 !== rp_ge[g.p.id].navkeys[0] || setTimeout(function () { $(".ui-jqdialog-titlebar-close", "#" + $.jgrid.jqID(t.modalhead)).attr("tabindex", "-1").focus() }, 0) } function m(e, t) { var r, i, o, a = 0, n = $(t).jqGrid("getInd", e, !0); n && ($("td", n).each(function (e) { r = t.p.colModel[e].name, i = (!t.p.colModel[e].editrules || !0 !== t.p.colModel[e].editrules.edithidden) && !0 === t.p.colModel[e].hidden, "cb" !== r && "subgrid" !== r && "rn" !== r && (o = r === t.p.ExpandColumn && !0 === t.p.treeGrid ? $(this).text() : $(this).html(), r = $.jgrid.jqID("v_" + r), $("#" + r + " span", "#" + l).html(o), i && $("#" + r, "#" + l).parents("tr:first").hide(), a++) }), 0 < a && $("#id_g", "#" + l).val(e)) } function v(e, t) { var r = t[1].length - 1; 0 === e ? $("#pData", "#" + l + "_2").addClass(x.disabled) : void 0 !== t[1][e - 1] && $("#" + $.jgrid.jqID(t[1][e - 1])).hasClass(x.disabled) ? $("#pData", l + "_2").addClass(x.disabled) : $("#pData", "#" + l + "_2").removeClass(x.disabled), e === r ? $("#nData", "#" + l + "_2").addClass(x.disabled) : void 0 !== t[1][e + 1] && $("#" + $.jgrid.jqID(t[1][e + 1])).hasClass(x.disabled) ? $("#nData", l + "_2").addClass(x.disabled) : $("#nData", "#" + l + "_2").removeClass(x.disabled) } function b() { var e = $(g).jqGrid("getDataIDs"), t = $("#id_g", "#" + l).val(); if (g.p.multiselect && rp_ge[g.p.id].viewselected) { for (var r = [], i = 0, o = e.length; i < o; i++)-1 !== $.inArray(e[i], g.p.selarrrow) && r.push(e[i]); return [$.inArray(t, r), r] } return [$.inArray(t, e), e] } g.grid && j && (i = g.p.id, o = "ViewGrid_" + $.jgrid.jqID(i), l = "ViewTbl_" + $.jgrid.jqID(i), r = "ViewGrid_" + i, p = "ViewTbl_" + i, t = { themodal: "viewmod" + i, modalhead: "viewhd" + i, modalcontent: "viewcnt" + i, scrollelm: o }, h = !0, a = 1, n = 0, rp_ge[g.p.id].styleUI = g.p.styleUI || "jQueryUI", w.recreateForm || $(g).data("viewProp") && $.extend(rp_ge[$(this)[0].p.id], $(g).data("viewProp")), u = isNaN(rp_ge[$(this)[0].p.id].dataheight) ? rp_ge[$(this)[0].p.id].dataheight : rp_ge[$(this)[0].p.id].dataheight + "px", d = isNaN(rp_ge[$(this)[0].p.id].datawidth) ? rp_ge[$(this)[0].p.id].datawidth : rp_ge[$(this)[0].p.id].datawidth + "px", e = $("<form name='FormPost' id='" + r + "' class='FormGrid' style='width:" + d + ";height:" + u + ";'></form>"), s = $("<table id='" + p + "' class='EditTable ViewTable'><tbody></tbody></table>"), $(g.p.colModel).each(function () { var e = this.formoptions; a = Math.max(a, e && e.colpos || 0), n = Math.max(n, e && e.rowpos || 0) }), $(e).append(s), void 0 === (h = $(g).triggerHandler("jqGridViewRowBeforeInitData", [e])) && (h = !0), h && $.isFunction(rp_ge[g.p.id].beforeInitData) && (h = rp_ge[g.p.id].beforeInitData.call(g, e)), !1 !== h && (function (e, a, n, l) { for (var s, d, p, c, u, h, g, f, m = 0, v = [], t = "<td class='CaptionTD form-view-label " + x.content + "' width='" + w.labelswidth + "'></td><td class='DataTD form-view-data ui-helper-reset " + x.content + "'></td>", b = "", r = "<td class='CaptionTD form-view-label " + x.content + "'></td><td class='DataTD form-view-data " + x.content + "'></td>", i = ["integer", "number", "currency"], o = 0, j = 0, y = 1; y <= l; y++)b += 1 === y ? t : r; $(a.p.colModel).each(function () { (d = (!this.editrules || !0 !== this.editrules.edithidden) && !0 === this.hidden) || "right" !== this.align || (this.formatter && -1 !== $.inArray(this.formatter, i) ? o = Math.max(o, parseInt(this.width, 10)) : j = Math.max(j, parseInt(this.width, 10))) }), h = 0 !== o ? o : 0 !== j ? j : 0, u = $(a).jqGrid("getInd", e), $(a.p.colModel).each(function (e) { var t, r, i, o; s = this.name, d = (!this.editrules || !0 !== this.editrules.edithidden) && !0 === this.hidden, c = d ? "style='display:none'" : "", f = "boolean" != typeof this.viewable || this.viewable, "cb" !== s && "subgrid" !== s && "rn" !== s && f && (p = !1 === u ? "" : s === a.p.ExpandColumn && !0 === a.p.treeGrid ? $("td:eq(" + e + ")", a.rows[u]).text() : $("td:eq(" + e + ")", a.rows[u]).html(), g = "right" === this.align && 0 !== h, t = $.extend({}, { rowabove: !1, rowcontent: "" }, this.formoptions || {}), r = parseInt(t.rowpos, 10) || m + 1, i = parseInt(2 * (parseInt(t.colpos, 10) || 1), 10), t.rowabove && (o = $("<tr><td class='contentinfo' colspan='" + 2 * l + "'>" + t.rowcontent + "</td></tr>"), $(n).append(o), o[0].rp = r), 0 === (f = $(n).find("tr[rowpos=" + r + "]")).length && (f = $("<tr " + c + " rowpos='" + r + "'></tr>").addClass("FormData").attr("id", "trv_" + s), $(f).append(b), $(n).append(f), f[0].rp = r), $("td:eq(" + (i - 2) + ")", f[0]).html("<b>" + (void 0 === t.label ? a.p.colNames[e] : t.label) + "</b>"), $("td:eq(" + (i - 1) + ")", f[0]).append("<span>" + p + "</span>").attr("id", "v_" + s), g && $("td:eq(" + (i - 1) + ") span", f[0]).css({ "text-align": "right", width: h + "px" }), v[m] = e, m++) }), 0 < m && ((e = $("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='" + (2 * l - 1) + "' class='DataTD'><input class='FormElement' id='id_g' type='text' name='id' value='" + e + "'/></td></tr>"))[0].rp = m + 99, $(n).append(e)) }(j, g, s, a), u = (d = "rtl" === g.p.direction) ? "pData" : "nData", p = "<a id='" + (d ? "nData" : "pData") + "' class='fm-button " + x.button + "'><span class='" + x.icon_base + " " + y.icon_prev + "'></span></a>", h = "<a id='" + u + "' class='fm-button " + x.button + "'><span class='" + x.icon_base + " " + y.icon_next + "'></span></a>", u = "<a id='cData' class='fm-button " + x.button + "'>" + w.bClose + "</a>", u = $.isArray(rp_ge[g.p.id].buttons) ? $.jgrid.buildButtons(rp_ge[g.p.id].buttons, u, x) : u, 0 < n && (c = [], $.each($(s)[0].rows, function (e, t) { c[e] = t }), c.sort(function (e, t) { return e.rp > t.rp ? 1 : e.rp < t.rp ? -1 : 0 }), $.each(c, function (e, t) { $("tbody", s).append(t) })), w.gbox = "#gbox_" + $.jgrid.jqID(i), h = $("<div></div>").append(e).append("<table border='0' class='EditTable' id='" + l + "_2'><tbody><tr id='Act_Buttons'><td class='navButton' width='" + w.labelswidth + "'>" + (d ? h + p : p + h) + "</td><td class='EditButton'>" + u + "</td></tr></tbody></table>"), u = $(".ui-jqgrid").css("font-size") || "11px", $.jgrid.createModal(t, h, rp_ge[$(this)[0].p.id], "#gview_" + $.jgrid.jqID(g.p.id), $("#gview_" + $.jgrid.jqID(g.p.id))[0], null, { "font-size": u }), d && ($("#pData, #nData", "#" + l + "_2").css("float", "right"), $(".EditButton", "#" + l + "_2").css("text-align", "left")), w.viewPagerButtons || $("#pData, #nData", "#" + l + "_2").hide(), h = null, $("#" + t.themodal).keydown(function (e) { return 27 === e.which ? (rp_ge[g.p.id].closeOnEscape && $.jgrid.hideModal("#" + $.jgrid.jqID(t.themodal), { gb: w.gbox, jqm: w.jqModal, onClose: w.onClose, removemodal: rp_ge[g.p.id].removemodal, formprop: !rp_ge[g.p.id].recreateForm, form: rp_ge[g.p.id].form }), !1) : !0 === w.navkeys[0] ? e.which === w.navkeys[1] ? ($("#pData", "#" + l + "_2").trigger("click"), !1) : e.which === w.navkeys[2] ? ($("#nData", "#" + l + "_2").trigger("click"), !1) : void 0 : void 0 }), w.closeicon = $.extend([!0, "left", y.icon_close], w.closeicon), !0 === w.closeicon[0] && $("#cData", "#" + l + "_2").addClass("right" === w.closeicon[1] ? "fm-button-icon-right" : "fm-button-icon-left").append("<span class='" + x.icon_base + " " + w.closeicon[2] + "'></span>"), $(g).triggerHandler("jqGridViewRowBeforeShowForm", [$("#" + o)]), $.isFunction(w.beforeShowForm) && w.beforeShowForm.call(g, $("#" + o)), $.jgrid.viewModal("#" + $.jgrid.jqID(t.themodal), { gbox: "#gbox_" + $.jgrid.jqID(i), jqm: w.jqModal, overlay: w.overlay, modal: w.modal, onHide: function (e) { var t = "rtl" === $("#gbox_" + $.jgrid.jqID(i)).attr("dir"), r = parseFloat($("#viewmod" + i)[0].style.width); $(g).data("viewProp", { top: parseFloat($(e.w).css("top")), left: t ? $("#gbox_" + $.jgrid.jqID(i)).outerWidth() - r - parseFloat($(e.w).css("left")) + 12 : parseFloat($(e.w).css("left")), width: $(e.w).width(), height: $(e.w).height(), dataheight: $("#" + o).height(), datawidth: $("#" + o).width() }), e.w.remove(), e.o && e.o.remove() } }), $(".fm-button:not(." + x.disabled + ")", "#" + l + "_2").hover(function () { $(this).addClass(x.hover) }, function () { $(this).removeClass(x.hover) }), f(), $("#cData", "#" + l + "_2").click(function () { return $.jgrid.hideModal("#" + $.jgrid.jqID(t.themodal), { gb: "#gbox_" + $.jgrid.jqID(i), jqm: w.jqModal, onClose: w.onClose, removemodal: rp_ge[g.p.id].removemodal, formprop: !rp_ge[g.p.id].recreateForm, form: rp_ge[g.p.id].form }), !1 }), $("#" + l + "_2").find("[data-index]").each(function () { var t = parseInt($(this).attr("data-index"), 10); 0 <= t && w.buttons[t].hasOwnProperty("click") && $(this).on("click", function (e) { w.buttons[t].click.call(g, $("#" + r)[0], rp_ge[g.p.id], e) }) }), $("#nData", "#" + l + "_2").click(function () { $("#FormError", "#" + l).hide(); var e = b(); return e[0] = parseInt(e[0], 10), -1 !== e[0] && e[1][e[0] + 1] && ($(g).triggerHandler("jqGridViewRowClickPgButtons", ["next", $("#" + o), e[1][e[0]]]), $.isFunction(w.onclickPgButtons) && w.onclickPgButtons.call(g, "next", $("#" + o), e[1][e[0]]), m(e[1][e[0] + 1], g), g.p.multiselect && rp_ge[g.p.id].viewselected || $(g).jqGrid("setSelection", e[1][e[0] + 1]), $(g).triggerHandler("jqGridViewRowAfterClickPgButtons", ["next", $("#" + o), e[1][e[0] + 1]]), $.isFunction(w.afterclickPgButtons) && w.afterclickPgButtons.call(g, "next", $("#" + o), e[1][e[0] + 1]), v(e[0] + 1, e)), f(), !1 }), $("#pData", "#" + l + "_2").click(function () { $("#FormError", "#" + l).hide(); var e = b(); return -1 !== e[0] && e[1][e[0] - 1] && ($(g).triggerHandler("jqGridViewRowClickPgButtons", ["prev", $("#" + o), e[1][e[0]]]), $.isFunction(w.onclickPgButtons) && w.onclickPgButtons.call(g, "prev", $("#" + o), e[1][e[0]]), m(e[1][e[0] - 1], g), g.p.multiselect && rp_ge[g.p.id].viewselected || $(g).jqGrid("setSelection", e[1][e[0] - 1]), $(g).triggerHandler("jqGridViewRowAfterClickPgButtons", ["prev", $("#" + o), e[1][e[0] - 1]]), $.isFunction(w.afterclickPgButtons) && w.afterclickPgButtons.call(g, "prev", $("#" + o), e[1][e[0] - 1]), v(e[0] - 1, e)), f(), !1 }), v((h = b())[0], h))) }) }, delGridRow: function (h, g) { var e = $.jgrid.getRegional(this[0], "del"), t = this[0].p.styleUI, f = $.jgrid.styleUI[t].formedit, m = $.jgrid.styleUI[t].common; return g = $.extend(!0, { top: 0, left: 0, width: 240, height: "auto", dataheight: "auto", modal: !1, overlay: 30, drag: !0, resize: !0, url: "", mtype: "POST", reloadAfterSubmit: !0, beforeShowForm: null, beforeInitData: null, afterShowForm: null, beforeSubmit: null, onclickSubmit: null, afterSubmit: null, jqModal: !0, closeOnEscape: !1, delData: {}, delicon: [], cancelicon: [], onClose: null, ajaxDelOptions: {}, processing: !1, serializeDelData: null, useDataProxy: !1 }, e, g || {}), rp_ge[$(this)[0].p.id] = g, this.each(function () { var n = this; if (n.grid && h) { var l, i, s, d = n.p.id, p = {}, e = !0, c = "DelTbl_" + $.jgrid.jqID(d), r = "DelTbl_" + d, u = { themodal: "delmod" + d, modalhead: "delhd" + d, modalcontent: "delcnt" + d, scrollelm: c }; if (rp_ge[n.p.id].styleUI = n.p.styleUI || "jQueryUI", $.isArray(h) && (h = h.join()), void 0 !== $("#" + $.jgrid.jqID(u.themodal))[0]) { if (void 0 === (e = $(n).triggerHandler("jqGridDelRowBeforeInitData", [$("#" + c)])) && (e = !0), e && $.isFunction(rp_ge[n.p.id].beforeInitData) && (e = rp_ge[n.p.id].beforeInitData.call(n, $("#" + c))), !1 === e) return; $("#DelData>td", "#" + c).text(h), $("#DelError", "#" + c).hide(), !0 === rp_ge[n.p.id].processing && (rp_ge[n.p.id].processing = !1, $("#dData", "#" + c).removeClass(m.active)), $(n).triggerHandler("jqGridDelRowBeforeShowForm", [$("#" + c)]), $.isFunction(rp_ge[n.p.id].beforeShowForm) && rp_ge[n.p.id].beforeShowForm.call(n, $("#" + c)), $.jgrid.viewModal("#" + $.jgrid.jqID(u.themodal), { gbox: "#gbox_" + $.jgrid.jqID(d), jqm: rp_ge[n.p.id].jqModal, overlay: rp_ge[n.p.id].overlay, modal: rp_ge[n.p.id].modal }), $(n).triggerHandler("jqGridDelRowAfterShowForm", [$("#" + c)]), $.isFunction(rp_ge[n.p.id].afterShowForm) && rp_ge[n.p.id].afterShowForm.call(n, $("#" + c)) } else { var t = isNaN(rp_ge[n.p.id].dataheight) ? rp_ge[n.p.id].dataheight : rp_ge[n.p.id].dataheight + "px", o = isNaN(g.datawidth) ? g.datawidth : g.datawidth + "px", a = "<div id='" + r + "' class='formdata' style='width:" + o + ";overflow:auto;position:relative;height:" + t + ";'>"; a += "<table class='DelTable'><tbody>", a += "<tr id='DelError' style='display:none'><td class='" + m.error + "'></td></tr>", a += "<tr id='DelData' style='display:none'><td >" + h + "</td></tr>", a += '<tr><td class="delmsg" style="white-space:pre;">' + rp_ge[n.p.id].msg + "</td></tr><tr><td >&#160;</td></tr>", a += "</tbody></table></div>"; o = "<a id='dData' class='fm-button " + m.button + "'>" + g.bSubmit + "</a>", t = "<a id='eData' class='fm-button " + m.button + "'>" + g.bCancel + "</a>", o = $.isArray(rp_ge[n.p.id].buttons) ? $.jgrid.buildButtons(rp_ge[n.p.id].buttons, o + t, m) : o + t, t = $(".ui-jqgrid").css("font-size") || "11px"; if (a += "<table class='EditTable ui-common-table' id='" + c + "_2'><tbody><tr><td><hr class='" + m.content + "' style='margin:1px'/></td></tr><tr><td class='DelButton EditButton'>" + o + "</td></tr></tbody></table>", g.gbox = "#gbox_" + $.jgrid.jqID(d), $.jgrid.createModal(u, a, rp_ge[n.p.id], "#gview_" + $.jgrid.jqID(n.p.id), $("#gview_" + $.jgrid.jqID(n.p.id))[0], null, { "font-size": t }), $(".fm-button", "#" + c + "_2").hover(function () { $(this).addClass(m.hover) }, function () { $(this).removeClass(m.hover) }), g.delicon = $.extend([!0, "left", f.icon_del], rp_ge[n.p.id].delicon), g.cancelicon = $.extend([!0, "left", f.icon_cancel], rp_ge[n.p.id].cancelicon), !0 === g.delicon[0] && $("#dData", "#" + c + "_2").addClass("right" === g.delicon[1] ? "fm-button-icon-right" : "fm-button-icon-left").append("<span class='" + m.icon_base + " " + g.delicon[2] + "'></span>"), !0 === g.cancelicon[0] && $("#eData", "#" + c + "_2").addClass("right" === g.cancelicon[1] ? "fm-button-icon-right" : "fm-button-icon-left").append("<span class='" + m.icon_base + " " + g.cancelicon[2] + "'></span>"), $("#dData", "#" + c + "_2").click(function () { var e, o = [!0, ""], a = $("#DelData>td", "#" + c).text(); if (p = {}, void 0 === (p = $(n).triggerHandler("jqGridDelRowClickSubmit", [rp_ge[n.p.id], a])) && $.isFunction(rp_ge[n.p.id].onclickSubmit) && (p = rp_ge[n.p.id].onclickSubmit.call(n, rp_ge[n.p.id], a) || {}), void 0 === (o = $(n).triggerHandler("jqGridDelRowBeforeSubmit", [a])) && (o = [!0, "", ""]), o[0] && $.isFunction(rp_ge[n.p.id].beforeSubmit) && (o = rp_ge[n.p.id].beforeSubmit.call(n, a)), o[0] && !rp_ge[n.p.id].processing) { if (rp_ge[n.p.id].processing = !0, i = n.p.prmNames, l = $.extend({}, rp_ge[n.p.id].delData, p), s = i.oper, l[s] = i.deloper, i = i.id, !(a = String(a).split(",")).length) return !1; for (e in a) a.hasOwnProperty(e) && (a[e] = $.jgrid.stripPref(n.p.idPrefix, a[e])); l[i] = a.join(), $(this).addClass(m.active); var t, r = $.extend({ url: rp_ge[n.p.id].url || $(n).jqGrid("getGridParam", "editurl"), type: rp_ge[n.p.id].mtype, data: $.isFunction(rp_ge[n.p.id].serializeDelData) ? rp_ge[n.p.id].serializeDelData.call(n, l) : l, complete: function (e, t) { var r, i; if ($("#dData", "#" + c + "_2").removeClass(m.active), 300 <= e.status && 304 !== e.status ? (o[0] = !1, o[1] = $(n).triggerHandler("jqGridDelRowErrorTextFormat", [e]), $.isFunction(rp_ge[n.p.id].errorTextFormat) && (o[1] = rp_ge[n.p.id].errorTextFormat.call(n, e)), void 0 === o[1] && (o[1] = t + " Status: '" + e.statusText + "'. Error code: " + e.status)) : (void 0 === (o = $(n).triggerHandler("jqGridDelRowAfterSubmit", [e, l])) && (o = [!0, "", ""]), o[0] && $.isFunction(rp_ge[n.p.id].afterSubmit) && (o = rp_ge[n.p.id].afterSubmit.call(n, e, l))), !1 === o[0]) $("#DelError>td", "#" + c).html(o[1]), $("#DelError", "#" + c).show(); else { if (rp_ge[n.p.id].reloadAfterSubmit && "local" !== n.p.datatype) $(n).trigger("reloadGrid"); else { if (!0 === n.p.treeGrid) try { $(n).jqGrid("delTreeNode", n.p.idPrefix + a[0]) } catch (e) { } else for (r = 0; r < a.length; r++)$(n).jqGrid("delRowData", n.p.idPrefix + a[r]); n.p.selrow = null, n.p.selarrrow = [] } ($.isFunction(rp_ge[n.p.id].afterComplete) || Object.prototype.hasOwnProperty.call($._data($(n)[0], "events"), "jqGridDelRowAfterComplete")) && (i = e, setTimeout(function () { $(n).triggerHandler("jqGridDelRowAfterComplete", [i, l]); try { rp_ge[n.p.id].afterComplete.call(n, i, l) } catch (e) { } }, 500)) } rp_ge[n.p.id].processing = !1, o[0] && $.jgrid.hideModal("#" + $.jgrid.jqID(u.themodal), { gb: "#gbox_" + $.jgrid.jqID(d), jqm: g.jqModal, onClose: rp_ge[n.p.id].onClose }) } }, $.jgrid.ajaxOptions, rp_ge[n.p.id].ajaxDelOptions); r.url || rp_ge[n.p.id].useDataProxy || ($.isFunction(n.p.dataProxy) ? rp_ge[n.p.id].useDataProxy = !0 : (o[0] = !1, o[1] += " " + $.jgrid.getRegional(n, "errors.nourl"))), o[0] && (rp_ge[n.p.id].useDataProxy ? (void 0 === (t = n.p.dataProxy.call(n, r, "del_" + n.p.id)) && (t = [!0, ""]), !1 === t[0] ? (o[0] = !1, o[1] = t[1] || "Error deleting the selected row!") : $.jgrid.hideModal("#" + $.jgrid.jqID(u.themodal), { gb: "#gbox_" + $.jgrid.jqID(d), jqm: g.jqModal, onClose: rp_ge[n.p.id].onClose })) : "clientArray" === r.url ? (l = r.data, r.complete({ status: 200, statusText: "" }, "")) : $.ajax(r)) } return !1 === o[0] && ($("#DelError>td", "#" + c).html(o[1]), $("#DelError", "#" + c).show()), !1 }), $("#eData", "#" + c + "_2").click(function () { return $.jgrid.hideModal("#" + $.jgrid.jqID(u.themodal), { gb: "#gbox_" + $.jgrid.jqID(d), jqm: rp_ge[n.p.id].jqModal, onClose: rp_ge[n.p.id].onClose }), !1 }), $("#" + c + "_2").find("[data-index]").each(function () { var t = parseInt($(this).attr("data-index"), 10); 0 <= t && g.buttons[t].hasOwnProperty("click") && $(this).on("click", function (e) { g.buttons[t].click.call(n, $("#" + r)[0], rp_ge[n.p.id], e) }) }), void 0 === (e = $(n).triggerHandler("jqGridDelRowBeforeInitData", [$("#" + c)])) && (e = !0), e && $.isFunction(rp_ge[n.p.id].beforeInitData) && (e = rp_ge[n.p.id].beforeInitData.call(n, $("#" + c))), !1 === e) return; $(n).triggerHandler("jqGridDelRowBeforeShowForm", [$("#" + c)]), $.isFunction(rp_ge[n.p.id].beforeShowForm) && rp_ge[n.p.id].beforeShowForm.call(n, $("#" + c)), $.jgrid.viewModal("#" + $.jgrid.jqID(u.themodal), { gbox: "#gbox_" + $.jgrid.jqID(d), jqm: rp_ge[n.p.id].jqModal, overlay: rp_ge[n.p.id].overlay, modal: rp_ge[n.p.id].modal }), $(n).triggerHandler("jqGridDelRowAfterShowForm", [$("#" + c)]), $.isFunction(rp_ge[n.p.id].afterShowForm) && rp_ge[n.p.id].afterShowForm.call(n, $("#" + c)) } !0 === rp_ge[n.p.id].closeOnEscape && setTimeout(function () { $(".ui-jqdialog-titlebar-close", "#" + $.jgrid.jqID(u.modalhead)).attr("tabindex", "-1").focus() }, 0) } }) }, navGrid: function (h, g, f, m, v, b, j) { var y = $.jgrid.getRegional(this[0], "nav"), w = this[0].p.styleUI, e = $.jgrid.styleUI[w].navigator, x = $.jgrid.styleUI[w].common; return g = $.extend({ edit: !0, editicon: e.icon_edit_nav, add: !0, addicon: e.icon_add_nav, del: !0, delicon: e.icon_del_nav, search: !0, searchicon: e.icon_search_nav, refresh: !0, refreshicon: e.icon_refresh_nav, refreshstate: "firstpage", view: !1, viewicon: e.icon_view_nav, position: "left", closeOnEscape: !0, beforeRefresh: null, afterRefresh: null, cloneToTop: !1, alertwidth: 200, alertheight: "auto", alerttop: null, alertleft: null, alertzIndex: null, dropmenu: !1, navButtonText: "" }, y, g || {}), this.each(function () { if (!this.p.navGrid) { var t, e, r = { themodal: "alertmod_" + this.p.id, modalhead: "alerthd_" + this.p.id, modalcontent: "alertcnt_" + this.p.id }, i = this; if (i.grid && "string" == typeof h) { $(i).data("navGrid") || $(i).data("navGrid", g), t = $(i).data("navGrid"), i.p.force_regional && (t = $.extend(t, y)), void 0 === $("#" + r.themodal)[0] && (t.alerttop || t.alertleft || ((e = $.jgrid.findPos(this))[0] = Math.round(e[0]), e[1] = Math.round(e[1]), t.alertleft = e[0] + this.p.width / 2 - parseInt(t.alertwidth, 10) / 2, t.alerttop = e[1] + this.p.height / 2 - 25), e = $(".ui-jqgrid").css("font-size") || "11px", $.jgrid.createModal(r, "<div>" + t.alerttext + "</div><span tabindex='0'><span tabindex='-1' id='jqg_alrt'></span></span>", { gbox: "#gbox_" + $.jgrid.jqID(i.p.id), jqModal: !0, drag: !0, resize: !0, caption: t.alertcap, top: t.alerttop, left: t.alertleft, width: t.alertwidth, height: t.alertheight, closeOnEscape: t.closeOnEscape, zIndex: t.alertzIndex, styleUI: i.p.styleUI }, "#gview_" + $.jgrid.jqID(i.p.id), $("#gbox_" + $.jgrid.jqID(i.p.id))[0], !0, { "font-size": e })); var o, a = 1, n = function () { $(this).hasClass(x.disabled) || $(this).addClass(x.hover) }, l = function () { $(this).removeClass(x.hover) }; for (t.cloneToTop && i.p.toppager && (a = 2), o = 0; o < a; o++) { var s, d, p, c = $("<table class='ui-pg-table navtable ui-common-table'><tbody><tr></tr></tbody></table>"), u = "<td class='ui-pg-button " + x.disabled + "' style='width:4px;'><span class='ui-separator'></span></td>"; 0 === o ? (0 === (d = h).indexOf("#") && (d = d.substring(1), d = "#" + $.jgrid.jqID(d)), p = i.p.id, d === i.p.toppager && (p += "_top", a = 1)) : (d = i.p.toppager, p = i.p.id + "_top"), "rtl" === i.p.direction && $(c).attr("dir", "rtl").css("float", "right"), m = m || {}, t.add && (s = $("<td class='ui-pg-button " + x.cornerall + "'></td>"), $(s).append("<div class='ui-pg-div'><span class='" + x.icon_base + " " + t.addicon + "'></span>" + t.addtext + "</div>"), $("tr", c).append(s), $(s, c).attr({ title: t.addtitle || "", id: m.id || "add_" + p }).click(function () { return $(this).hasClass(x.disabled) || ($.jgrid.setSelNavIndex(i, this), $.isFunction(t.addfunc) ? t.addfunc.call(i) : $(i).jqGrid("editGridRow", "new", m)), !1 }).hover(n, l), s = null), f = f || {}, t.edit && (s = $("<td class='ui-pg-button " + x.cornerall + "'></td>"), $(s).append("<div class='ui-pg-div'><span class='" + x.icon_base + " " + t.editicon + "'></span>" + t.edittext + "</div>"), $("tr", c).append(s), $(s, c).attr({ title: t.edittitle || "", id: f.id || "edit_" + p }).click(function () { var e; return $(this).hasClass(x.disabled) || ((e = i.p.selrow) ? ($.jgrid.setSelNavIndex(i, this), $.isFunction(t.editfunc) ? t.editfunc.call(i, e) : $(i).jqGrid("editGridRow", e, f)) : ($.jgrid.viewModal("#" + r.themodal, { gbox: "#gbox_" + $.jgrid.jqID(i.p.id), jqm: !0 }), $("#jqg_alrt").focus())), !1 }).hover(n, l), s = null), j = j || {}, t.view && (s = $("<td class='ui-pg-button " + x.cornerall + "'></td>"), $(s).append("<div class='ui-pg-div'><span class='" + x.icon_base + " " + t.viewicon + "'></span>" + t.viewtext + "</div>"), $("tr", c).append(s), $(s, c).attr({ title: t.viewtitle || "", id: j.id || "view_" + p }).click(function () { var e; return $(this).hasClass(x.disabled) || ((e = i.p.selrow) ? ($.jgrid.setSelNavIndex(i, this), $.isFunction(t.viewfunc) ? t.viewfunc.call(i, e) : $(i).jqGrid("viewGridRow", e, j)) : ($.jgrid.viewModal("#" + r.themodal, { gbox: "#gbox_" + $.jgrid.jqID(i.p.id), jqm: !0 }), $("#jqg_alrt").focus())), !1 }).hover(n, l), s = null), v = v || {}, t.del && (s = $("<td class='ui-pg-button " + x.cornerall + "'></td>"), $(s).append("<div class='ui-pg-div'><span class='" + x.icon_base + " " + t.delicon + "'></span>" + t.deltext + "</div>"), $("tr", c).append(s), $(s, c).attr({ title: t.deltitle || "", id: v.id || "del_" + p }).click(function () { var e; return $(this).hasClass(x.disabled) || (i.p.multiselect ? 0 === (e = i.p.selarrrow).length && (e = null) : e = i.p.selrow, e ? ($.jgrid.setSelNavIndex(i, this), $.isFunction(t.delfunc) ? t.delfunc.call(i, e) : $(i).jqGrid("delGridRow", e, v)) : ($.jgrid.viewModal("#" + r.themodal, { gbox: "#gbox_" + $.jgrid.jqID(i.p.id), jqm: !0 }), $("#jqg_alrt").focus())), !1 }).hover(n, l), s = null), (t.add || t.edit || t.del || t.view) && $("tr", c).append(u), b = b || {}, t.search && (s = $("<td class='ui-pg-button " + x.cornerall + "'></td>"), $(s).append("<div class='ui-pg-div'><span class='" + x.icon_base + " " + t.searchicon + "'></span>" + t.searchtext + "</div>"), $("tr", c).append(s), $(s, c).attr({ title: t.searchtitle || "", id: b.id || "search_" + p }).click(function () { return $(this).hasClass(x.disabled) || ($.jgrid.setSelNavIndex(i, this), $.isFunction(t.searchfunc) ? t.searchfunc.call(i, b) : $(i).jqGrid("searchGrid", b)), !1 }).hover(n, l), b.showOnLoad && !0 === b.showOnLoad && $(s, c).click(), s = null), t.refresh && (s = $("<td class='ui-pg-button " + x.cornerall + "'></td>"), $(s).append("<div class='ui-pg-div'><span class='" + x.icon_base + " " + t.refreshicon + "'></span>" + t.refreshtext + "</div>"), $("tr", c).append(s), $(s, c).attr({ title: t.refreshtitle || "", id: "refresh_" + p }).click(function () { if (!$(this).hasClass(x.disabled)) { $.isFunction(t.beforeRefresh) && t.beforeRefresh.call(i), i.p.search = !1, i.p.resetsearch = !0; try { if ("currentfilter" !== t.refreshstate) { var e = i.p.id; i.p.postData.filters = ""; try { $("#fbox_" + $.jgrid.jqID(e)).jqFilter("resetFilter") } catch (e) { } $.isFunction(i.clearToolbar) && i.clearToolbar.call(i, !1) } } catch (e) { } switch (t.refreshstate) { case "firstpage": $(i).trigger("reloadGrid", [{ page: 1 }]); break; case "current": case "currentfilter": $(i).trigger("reloadGrid", [{ current: !0 }]) }$.isFunction(t.afterRefresh) && t.afterRefresh.call(i), $.jgrid.setSelNavIndex(i, this) } return !1 }).hover(n, l), s = null), u = $(".ui-jqgrid").css("font-size") || "11px", $("body").append("<div id='testpg2' class='ui-jqgrid " + $.jgrid.styleUI[w].base.entrieBox + "' style='font-size:" + u + ";visibility:hidden;' ></div>"), u = $(c).clone().appendTo("#testpg2").width(), $("#testpg2").remove(), i.p._nvtd && (t.dropmenu ? (c = null, $(i).jqGrid("_buildNavMenu", d, p, g, f, m, v, b, j)) : u > i.p._nvtd[0] ? (i.p.responsive ? (c = null, $(i).jqGrid("_buildNavMenu", d, p, g, f, m, v, b, j)) : $(d + "_" + t.position, d).append(c).width(u), i.p._nvtd[0] = u) : $(d + "_" + t.position, d).append(c), i.p._nvtd[1] = u), i.p.navGrid = !0 } i.p.storeNavOptions && (i.p.navOptions = t, i.p.editOptions = f, i.p.addOptions = m, i.p.delOptions = v, i.p.searchOptions = b, i.p.viewOptions = j, i.p.navButtons = []) } } }) }, navButtonAdd: function (s, d) { var p = this[0].p.styleUI, e = $.jgrid.styleUI[p].navigator; return d = $.extend({ caption: "newButton", title: "", buttonicon: e.icon_newbutton_nav, onClickButton: null, position: "last", cursor: "pointer", internal: !1 }, d || {}), this.each(function () { var t, r, e, i, o, a, n, l; this.grid && "string" == typeof s && (0 === s.indexOf("#") && (s = s.substring(1)), s = "#" + $.jgrid.jqID(s), l = $(".navtable", s)[0], t = this, r = $.jgrid.styleUI[p].common.disabled, e = $.jgrid.styleUI[p].common.hover, i = $.jgrid.styleUI[p].common.cornerall, o = $.jgrid.styleUI[p].common.icon_base, t.p.storeNavOptions && !d.internal && t.p.navButtons.push([s, d]), l ? d.id && void 0 !== $("#" + $.jgrid.jqID(d.id), l)[0] || (a = $("<td></td>"), "NONE" === d.buttonicon.toString().toUpperCase() ? $(a).addClass("ui-pg-button " + i).append("<div class='ui-pg-div'>" + d.caption + "</div>") : $(a).addClass("ui-pg-button " + i).append("<div class='ui-pg-div'><span class='" + o + " " + d.buttonicon + "'></span>" + d.caption + "</div>"), d.id && $(a).attr("id", d.id), "first" !== d.position || 0 === l.rows[0].cells.length ? $("tr", l).append(a) : $("tr td:eq(0)", l).before(a), $(a, l).attr("title", d.title || "").click(function (e) { return $(this).hasClass(r) || ($.jgrid.setSelNavIndex(t, this), $.isFunction(d.onClickButton) && d.onClickButton.call(t, e)), !1 }).hover(function () { $(this).hasClass(r) || $(this).addClass(e) }, function () { $(this).removeClass(e) })) : (l = $(".dropdownmenu", s)[0]) && (n = $(l).val(), l = d.id || $.jgrid.randId(), l = $('<li class="ui-menu-item" role="presentation"><a class="' + i + ' g-menu-item" tabindex="0" role="menuitem" id="' + l + '">' + (d.caption || d.title) + "</a></li>"), n && ("first" === d.position ? $("#" + n).prepend(l) : $("#" + n).append(l), $(l).on("click", function (e) { return $(this).hasClass(r) || ($("#" + n).hide(), $.isFunction(d.onClickButton) && d.onClickButton.call(t, e)), !1 }).find("a").hover(function () { $(this).hasClass(r) || $(this).addClass(e) }, function () { $(this).removeClass(e) })))) }) }, navSeparatorAdd: function (i, o) { var e = this[0].p.styleUI, a = $.jgrid.styleUI[e].common; return o = $.extend({ sepclass: "ui-separator", sepcontent: "", position: "last" }, o || {}), this.each(function () { var e, t, r; this.grid && ("string" == typeof i && 0 !== i.indexOf("#") && (i = "#" + $.jgrid.jqID(i)), e = $(".navtable", i)[0], this.p.storeNavOptions && this.p.navButtons.push([i, o]), e ? (t = "<td class='ui-pg-button " + a.disabled + "' style='width:4px;'><span class='" + o.sepclass + "'></span>" + o.sepcontent + "</td>", "first" !== o.position || 0 === e.rows[0].cells.length ? $("tr", e).append(t) : $("tr td:eq(0)", e).before(t)) : (e = $(".dropdownmenu", i)[0], t = "<li class='ui-menu-item " + a.disabled + "' style='width:100%' role='presentation'><hr class='ui-separator-li'></li>", e && (r = $(e).val()) && ("first" === o.position ? $("#" + r).prepend(t) : $("#" + r).append(t)))) }) }, _buildNavMenu: function (c, u, h, g, f, m, v, b) { return this.each(function () { var t = this, e = $.jgrid.getRegional(t, "nav"), r = t.p.styleUI, i = ($.jgrid.styleUI[r].navigator, $.jgrid.styleUI[r].filter), o = $.jgrid.styleUI[r].common, a = "form_menu_" + $.jgrid.randId(), e = h.navButtonText || e.selectcaption || "Actions", e = "<button class='dropdownmenu " + o.button + "' value='" + a + "'>" + e + "</button>"; $(c + "_" + h.position, c).append(e); var n, l, s, d, p = "alertmod_" + this.p.id; this.p.id, this.p.id; s = $(".ui-jqgrid").css("font-size") || "11px", d = $('<ul id="' + a + '" class="ui-nav-menu modal-content" role="menu" tabindex="0" style="display:none;font-size:' + s + '"></ul>'), h.add && (n = (f = f || {}).id || "add_" + u, l = $('<li class="ui-menu-item" role="presentation"><a class="' + o.cornerall + ' g-menu-item" tabindex="0" role="menuitem" id="' + n + '">' + (h.addtext || h.addtitle) + "</a></li>").click(function () { return $(this).hasClass(o.disabled) || ($.isFunction(h.addfunc) ? h.addfunc.call(t) : $(t).jqGrid("editGridRow", "new", f), $(d).hide()), !1 }), $(d).append(l)), h.edit && (n = (g = g || {}).id || "edit_" + u, l = $('<li class="ui-menu-item" role="presentation"><a class="' + o.cornerall + ' g-menu-item" tabindex="0" role="menuitem" id="' + n + '">' + (h.edittext || h.edittitle) + "</a></li>").click(function () { var e; return $(this).hasClass(o.disabled) || ((e = t.p.selrow) ? $.isFunction(h.editfunc) ? h.editfunc.call(t, e) : $(t).jqGrid("editGridRow", e, g) : ($.jgrid.viewModal("#" + p, { gbox: "#gbox_" + $.jgrid.jqID(t.p.id), jqm: !0 }), $("#jqg_alrt").focus()), $(d).hide()), !1 }), $(d).append(l)), h.view && (n = (b = b || {}).id || "view_" + u, l = $('<li class="ui-menu-item" role="presentation"><a class="' + o.cornerall + ' g-menu-item" tabindex="0" role="menuitem" id="' + n + '">' + (h.viewtext || h.viewtitle) + "</a></li>").click(function () { var e; return $(this).hasClass(o.disabled) || ((e = t.p.selrow) ? $.isFunction(h.editfunc) ? h.viewfunc.call(t, e) : $(t).jqGrid("viewGridRow", e, b) : ($.jgrid.viewModal("#" + p, { gbox: "#gbox_" + $.jgrid.jqID(t.p.id), jqm: !0 }), $("#jqg_alrt").focus()), $(d).hide()), !1 }), $(d).append(l)), h.del && (n = (m = m || {}).id || "del_" + u, l = $('<li class="ui-menu-item" role="presentation"><a class="' + o.cornerall + ' g-menu-item" tabindex="0" role="menuitem" id="' + n + '">' + (h.deltext || h.deltitle) + "</a></li>").click(function () { var e; return $(this).hasClass(o.disabled) || (t.p.multiselect ? 0 === (e = t.p.selarrrow).length && (e = null) : e = t.p.selrow, e ? $.isFunction(h.delfunc) ? h.delfunc.call(t, e) : $(t).jqGrid("delGridRow", e, m) : ($.jgrid.viewModal("#" + p, { gbox: "#gbox_" + $.jgrid.jqID(t.p.id), jqm: !0 }), $("#jqg_alrt").focus()), $(d).hide()), !1 }), $(d).append(l)), (h.add || h.edit || h.del || h.view) && $(d).append("<li class='ui-menu-item " + o.disabled + "' style='width:100%' role='presentation'><hr class='ui-separator-li'></li>"), h.search && (n = (v = v || {}).id || "search_" + u, l = $('<li class="ui-menu-item" role="presentation"><a class="' + o.cornerall + ' g-menu-item" tabindex="0" role="menuitem" id="' + n + '">' + (h.searchtext || h.searchtitle) + "</a></li>").click(function () { return $(this).hasClass(o.disabled) || ($.isFunction(h.searchfunc) ? h.searchfunc.call(t, v) : $(t).jqGrid("searchGrid", v), $(d).hide()), !1 }), $(d).append(l), v.showOnLoad && !0 === v.showOnLoad && $(l).click()), h.refresh && (n = v.id || "search_" + u, l = $('<li class="ui-menu-item" role="presentation"><a class="' + o.cornerall + ' g-menu-item" tabindex="0" role="menuitem" id="' + n + '">' + (h.refreshtext || h.refreshtitle) + "</a></li>").click(function () { if (!$(this).hasClass(o.disabled)) { $.isFunction(h.beforeRefresh) && h.beforeRefresh.call(t), t.p.search = !1, t.p.resetsearch = !0; try { if ("currentfilter" !== h.refreshstate) { var e = t.p.id; t.p.postData.filters = ""; try { $("#fbox_" + $.jgrid.jqID(e)).jqFilter("resetFilter") } catch (e) { } $.isFunction(t.clearToolbar) && t.clearToolbar.call(t, !1) } } catch (e) { } switch (h.refreshstate) { case "firstpage": $(t).trigger("reloadGrid", [{ page: 1 }]); break; case "current": case "currentfilter": $(t).trigger("reloadGrid", [{ current: !0 }]) }$.isFunction(h.afterRefresh) && h.afterRefresh.call(t), $(d).hide() } return !1 }), $(d).append(l)), $(d).hide(), $("body").append(d), $("#" + a).addClass("ui-menu " + i.menu_widget), $("#" + a + " > li > a").hover(function () { $(this).addClass(o.hover) }, function () { $(this).removeClass(o.hover) }), $(".dropdownmenu", c + "_" + h.position).on("click", function (e) { var t = $(this).offset(), r = t.left, i = parseInt(t.top), t = $(this).val(); $("#" + t).show().css({ top: i - ($("#" + t).height() + 10) + "px", left: r + "px" }), e.stopPropagation() }), $("body").on("click", function (e) { $(e.target).hasClass("dropdownmenu") || $("#" + a).hide() }) }) }, GridToForm: function (i, o) { return this.each(function () { var e, t = this; if (t.grid) { var r = $(t).jqGrid("getRowData", i); if (r) for (e in r) r.hasOwnProperty(e) && ($("[name=" + $.jgrid.jqID(e) + "]", o).is("input:radio") || $("[name=" + $.jgrid.jqID(e) + "]", o).is("input:checkbox") ? $("[name=" + $.jgrid.jqID(e) + "]", o).each(function () { $(this).val() == r[e] ? $(this)[t.p.useProp ? "prop" : "attr"]("checked", !0) : $(this)[t.p.useProp ? "prop" : "attr"]("checked", !1) }) : $("[name=" + $.jgrid.jqID(e) + "]", o).val(r[e])) } }) }, FormToGrid: function (t, i, o, a) { return this.each(function () { var e, r; this.grid && (o = o || "set", a = a || "first", e = $(i).serializeArray(), r = {}, $.each(e, function (e, t) { r[t.name] = t.value }), "add" === o ? $(this).jqGrid("addRowData", t, r, a) : "set" === o && $(this).jqGrid("setRowData", t, r)) }) } }), $.jgrid.extend({ groupingSetup: function () { return this.each(function () { var e, t, r, i = this, o = i.p.colModel, a = i.p.groupingView, n = $.jgrid.styleUI[i.p.styleUI || "jQueryUI"].grouping; if (null === a || "object" != typeof a && !$.isFunction(a)) i.p.grouping = !1; else if (a.plusicon || (a.plusicon = n.icon_plus), a.minusicon || (a.minusicon = n.icon_minus), a.groupField.length) { for (void 0 === a.visibiltyOnNextGrouping && (a.visibiltyOnNextGrouping = []), a.lastvalues = [], a._locgr || (a.groups = []), a.counters = [], e = 0; e < a.groupField.length; e++)a.groupOrder[e] || (a.groupOrder[e] = "asc"), a.groupText[e] || (a.groupText[e] = "{0}"), "boolean" != typeof a.groupColumnShow[e] && (a.groupColumnShow[e] = !0), "boolean" != typeof a.groupSummary[e] && (a.groupSummary[e] = !1), a.groupSummaryPos[e] || (a.groupSummaryPos[e] = "footer"), !0 === a.groupColumnShow[e] ? (a.visibiltyOnNextGrouping[e] = !0, $(i).jqGrid("showCol", a.groupField[e])) : (a.visibiltyOnNextGrouping[e] = $("#" + $.jgrid.jqID(i.p.id + "_" + a.groupField[e])).is(":visible"), $(i).jqGrid("hideCol", a.groupField[e])); for (a.summary = [], a.hideFirstGroupCol && $.isArray(a.formatDisplayField) && !$.isFunction(a.formatDisplayField[0]) && (a.formatDisplayField[0] = function (e) { return e }), t = 0, r = o.length; t < r; t++)a.hideFirstGroupCol && (o[t].hidden || a.groupField[0] !== o[t].name || (o[t].formatter = function () { return "" })), o[t].summaryType && (o[t].summaryDivider ? a.summary.push({ nm: o[t].name, st: o[t].summaryType, v: "", sd: o[t].summaryDivider, vd: "", sr: o[t].summaryRound, srt: o[t].summaryRoundType || "round" }) : a.summary.push({ nm: o[t].name, st: o[t].summaryType, v: "", sr: o[t].summaryRound, srt: o[t].summaryRoundType || "round" })) } else i.p.grouping = !1 }) }, groupingPrepare: function (d, p) { return this.each(function () { for (var e, t, r, i = this.p.groupingView, o = this, a = function () { $.isFunction(this.st) ? this.v = this.st.call(o, this.v, this.nm, d) : (this.v = $(o).jqGrid("groupingCalculations.handler", this.st, this.v, this.nm, this.sr, this.srt, d), "avg" === this.st.toLowerCase() && this.sd && (this.vd = $(o).jqGrid("groupingCalculations.handler", this.st, this.vd, this.sd, this.sr, this.srt, d))) }, n = i.groupField.length, l = 0, s = 0; s < n; s++)e = i.groupField[s], r = i.displayField[s], t = d[e], null == (r = null == r ? null : d[r]) && (r = t), void 0 !== t && (0 === p ? (i.groups.push({ idx: s, dataIndex: e, value: t, displayValue: r, startRow: p, cnt: 1, summary: [] }), i.lastvalues[s] = t, i.counters[s] = { cnt: 1, pos: i.groups.length - 1, summary: $.extend(!0, [], i.summary) }) : "object" == typeof t || ($.isArray(i.isInTheSameGroup) && $.isFunction(i.isInTheSameGroup[s]) ? i.isInTheSameGroup[s].call(o, i.lastvalues[s], t, s, i) : i.lastvalues[s] === t) ? 1 === l ? (i.groups.push({ idx: s, dataIndex: e, value: t, displayValue: r, startRow: p, cnt: 1, summary: [] }), i.lastvalues[s] = t, i.counters[s] = { cnt: 1, pos: i.groups.length - 1, summary: $.extend(!0, [], i.summary) }) : (i.counters[s].cnt += 1, i.groups[i.counters[s].pos].cnt = i.counters[s].cnt) : (i.groups.push({ idx: s, dataIndex: e, value: t, displayValue: r, startRow: p, cnt: 1, summary: [] }), i.lastvalues[s] = t, l = 1, i.counters[s] = { cnt: 1, pos: i.groups.length - 1, summary: $.extend(!0, [], i.summary) }), $.each(i.counters[s].summary, a), i.groups[i.counters[s].pos].summary = i.counters[s].summary) }), this }, groupingToggle: function (v) { return this.each(function () { var e = this, t = e.p.groupingView, r = v.split("_"), i = parseInt(r[r.length - 2], 10); r.splice(r.length - 2, 2); function o(e) { return 0 < (e = $.map(e.split(" "), function (e) { if (e.substring(0, s.length + 1) === s + "_") return parseInt(e.substring(s.length + 1), 10) })).length ? e[0] : void 0 } var a, n, l, s = r.join("_"), d = t.minusicon, p = t.plusicon, c = $("#" + $.jgrid.jqID(v)), u = c.length ? c[0].nextSibling : null, h = $("#" + $.jgrid.jqID(v) + " span.tree-wrap-" + e.p.direction), r = !1, g = !1, f = !!e.p.frozenColumns && e.p.id + "_frozen", c = !!f && $("#" + $.jgrid.jqID(v), "#" + $.jgrid.jqID(f)), m = c && c.length ? c[0].nextSibling : null; if (h.hasClass(d)) { if (u) for (; u && !(void 0 !== (a = o(u.className)) && a <= i);)l = parseInt($(u).attr("jqfootlevel"), 10), (g = !isNaN(l) && (t.showSummaryOnHide && l <= i)) || $(u).hide(), u = u.nextSibling, f && (g || $(m).hide(), m = m.nextSibling); h.removeClass(d).addClass(p), r = !0 } else { if (u) for (n = void 0; u;) { if (a = o(u.className), void 0 === n && (n = void 0 === a), g = $(u).hasClass("ui-subgrid") && $(u).hasClass("ui-sg-collapsed"), void 0 !== a) { if (a <= i) break; a === i + 1 && (g || ($(u).show().find(">td>span.tree-wrap-" + e.p.direction).removeClass(d).addClass(p), f && $(m).show().find(">td>span.tree-wrap-" + e.p.direction).removeClass(d).addClass(p))) } else n && (g || ($(u).show(), f && $(m).show())); u = u.nextSibling, f && (m = m.nextSibling) } h.removeClass(p).addClass(d) } $(e).triggerHandler("jqGridGroupingClickGroup", [v, r]), $.isFunction(e.p.onClickGroup) && e.p.onClickGroup.call(e, v, r) }), !1 }, groupingRender: function (I, D, C, F) { return this.each(function () { var p, c, u, h, g = this, f = g.p.groupingView, m = "", v = f.groupCollapse ? f.plusicon : f.minusicon, b = [], j = f.groupField.length, y = $.jgrid.styleUI[g.p.styleUI || "jQueryUI"].common, v = v + " tree-wrap-" + g.p.direction; $.each(g.p.colModel, function (e, t) { for (var r = 0; r < j; r++)if (f.groupField[r] === t.name) { b[r] = e; break } }); var w = 0; function x(e, t, r, i, o) { for (var a, n, l, s = function (e, t, r) { var i, o = !1; if (0 === t) o = r[e]; else { var a = r[e].idx; if (0 === a) o = r[e]; else for (i = e; 0 <= i; i--)if (r[i].idx === a - t) { o = r[i]; break } } return o }(e, t, r), d = g.p.colModel, p = s.cnt, c = "", u = !1, h = i; h < D; h++)!d[h].hidden && !u && o ? (n = o, u = !0) : n = "<td " + g.formatCol(h, 1, "") + ">&#160;</td>", $.each(s.summary, function () { if (this.nm === d[h].name) { l = d[h].summaryTpl || "{0}", "string" == typeof this.st && "avg" === this.st.toLowerCase() && (this.sd && this.vd ? this.v = this.v / this.vd : this.v && 0 < p && (this.v = this.v / p)); try { this.groupCount = s.cnt, this.groupIndex = s.dataIndex, this.groupValue = s.value, a = g.formatter("", this.v, h, this) } catch (e) { a = this.v } return n = "<td " + g.formatCol(h, 1, "") + ">" + $.jgrid.template(l, a, s.cnt, s.dataIndex, s.displayValue) + "</td>", !1 } }), c += n; return c } var _, q = $.makeArray(f.groupSummary); q.reverse(), _ = g.p.multiselect ? ' colspan="2"' : "", $.each(f.groups, function (e, t) { if (f._locgr && !(t.startRow + t.cnt > (C - 1) * F && t.startRow < C * F)) return !0; w++, u = g.p.id + "ghead_" + t.idx, c = u + "_" + e, p = "<span style='cursor:pointer;margin-right:8px;margin-left:5px;' class='" + y.icon_base + " " + v + "' onclick=\"jQuery('#" + $.jgrid.jqID(g.p.id) + "').jqGrid('groupingToggle','" + c + "');return false;\"></span>"; try { h = $.isArray(f.formatDisplayField) && $.isFunction(f.formatDisplayField[t.idx]) ? f.formatDisplayField[t.idx].call(g, t.displayValue, t.value, g.p.colModel[b[t.idx]], t.idx, f) : g.formatter(c, t.displayValue, b[t.idx], t.value) } catch (e) { h = t.displayValue } var r = ""; if ("string" != typeof (r = $.isFunction(f.groupText[t.idx]) ? f.groupText[t.idx].call(g, h, t.cnt, t.summary) : $.jgrid.template(f.groupText[t.idx], h, t.cnt, t.summary)) && "number" != typeof r && (r = h), "header" === f.groupSummaryPos[t.idx] ? (m += '<tr id="' + c + '"' + (f.groupCollapse && 0 < t.idx ? ' style="display:none;" ' : " ") + 'role="row" class= "' + y.content + " jqgroup ui-row-" + g.p.direction + " " + u + '">', m += x(e, 0, f.groups, _ ? 1 : 0, '<td style="padding-left:' + 12 * t.idx + 'px;"' + _ + ">" + p + r + "</td>"), m += "</tr>") : m += '<tr id="' + c + '"' + (f.groupCollapse && 0 < t.idx ? ' style="display:none;" ' : " ") + 'role="row" class= "' + y.content + " jqgroup ui-row-" + g.p.direction + " " + u + '"><td style="padding-left:' + 12 * t.idx + 'px;" colspan="' + (!1 === f.groupColumnShow[t.idx] ? D - 1 : D) + '">' + p + r + "</td></tr>", j - 1 === t.idx) { var i, o, a, n, l = f.groups[e + 1], s = 0, r = t.startRow, d = void 0 !== l ? l.startRow : f.groups[e].startRow + f.groups[e].cnt; for (f._locgr && (s = (C - 1) * F) > t.startRow && (r = s), i = r; i < d && I[i - s]; i++)m += I[i - s].join(""); if ("header" !== f.groupSummaryPos[t.idx]) { if (void 0 !== l) { for (a = 0; a < f.groupField.length && l.dataIndex !== f.groupField[a]; a++); w = f.groupField.length - a } for (o = 0; o < w; o++)q[o] && (n = "", f.groupCollapse && !f.showSummaryOnHide && (n = ' style="display:none;"'), m += "<tr" + n + ' jqfootlevel="' + (t.idx - o) + '" role="row" class="' + y.content + " jqfoot ui-row-" + g.p.direction + '">', m += x(e, o, f.groups, 0, !1), m += "</tr>"); w = a } } }), $("#" + $.jgrid.jqID(g.p.id) + " tbody:first").append(m), m = null }) }, groupingGroupBy: function (i, o) { return this.each(function () { var e = this; "string" == typeof i && (i = [i]); var t, r = e.p.groupingView; for (e.p.grouping = !0, r._locgr = !1, void 0 === r.visibiltyOnNextGrouping && (r.visibiltyOnNextGrouping = []), t = 0; t < r.groupField.length; t++)!r.groupColumnShow[t] && r.visibiltyOnNextGrouping[t] && $(e).jqGrid("showCol", r.groupField[t]); for (t = 0; t < i.length; t++)r.visibiltyOnNextGrouping[t] = $("#" + $.jgrid.jqID(e.p.id) + "_" + $.jgrid.jqID(i[t])).is(":visible"); e.p.groupingView = $.extend(e.p.groupingView, o || {}), r.groupField = i, $(e).trigger("reloadGrid") }) }, groupingRemove: function (i) { return this.each(function () { var e = this; if (void 0 === i && (i = !0), !(e.p.grouping = !1) === i) { for (var t = e.p.groupingView, r = 0; r < t.groupField.length; r++)!t.groupColumnShow[r] && t.visibiltyOnNextGrouping[r] && $(e).jqGrid("showCol", t.groupField); $("tr.jqgroup, tr.jqfoot", "#" + $.jgrid.jqID(e.p.id) + " tbody:first").remove(), $("tr.jqgrow:hidden", "#" + $.jgrid.jqID(e.p.id) + " tbody:first").show() } else $(e).trigger("reloadGrid") }) }, groupingCalculations: { handler: function (e, t, r, i, o, a) { var n = { sum: function () { return parseFloat(t || 0) + parseFloat(a[r] || 0) }, min: function () { return "" === t ? parseFloat(a[r] || 0) : Math.min(parseFloat(t), parseFloat(a[r] || 0)) }, max: function () { return "" === t ? parseFloat(a[r] || 0) : Math.max(parseFloat(t), parseFloat(a[r] || 0)) }, count: function () { return "" === t && (t = 0), a.hasOwnProperty(r) ? t + 1 : 0 }, avg: function () { return n.sum() } }; if (!n[e]) throw "jqGrid Grouping No such method: " + e; e = n[e](); return null != i && (e = "fixed" === o ? e.toFixed(i) : (i = Math.pow(10, i), Math.round(e * i) / i)), e } }, setGroupHeaders: function (x) { return x = $.extend({ useColSpanStyle: !1, groupHeaders: [] }, x || {}), this.each(function () { var e, t, r, i, o, a, n, l, s, d, p = this, c = 0, u = p.p.colModel, h = u.length, g = p.grid.headers, f = $("table.ui-jqgrid-htable", p.grid.hDiv), m = f.children("thead").children("tr.ui-jqgrid-labels:last").addClass("jqg-second-row-header"), v = f.children("thead"), b = f.find(".jqg-first-row-header"), j = !1, y = $.jgrid.styleUI[p.p.styleUI || "jQueryUI"].base; p.p.groupHeader || (p.p.groupHeader = []), p.p.groupHeader.push(x), p.p.groupHeaderOn = !0, void 0 === b[0] ? b = $("<tr>", { role: "row", "aria-hidden": "true" }).addClass("jqg-first-row-header").css("height", "auto") : b.empty(); var w; for (($(document.activeElement).is("input") || $(document.activeElement).is("textarea")) && (j = document.activeElement), $(p).prepend(v), $(p).prepend(v), r = $("<tr>", { role: "row" }).addClass("ui-jqgrid-labels jqg-third-row-header"), e = 0; e < h; e++)if (i = g[e].el, o = $(i), t = u[e], s = { height: "0px", width: g[e].width + "px", display: t.hidden ? "none" : "" }, $("<th>", { role: "gridcell" }).css(s).addClass("ui-first-th-" + p.p.direction).appendTo(b), i.style.width = "", 0 <= (a = function (e, t) { for (var r = t.length, i = 0; i < r; i++)if (t[i].startColumnName === e) return i; return -1 }(t.name, x.groupHeaders))) { for (n = (s = x.groupHeaders[a]).numberOfColumns, w = s.titleText, s = s.className || "", a = l = 0; a < n && e + a < h; a++)u[e + a].hidden || l++; w = $("<th>").attr({ role: "columnheader" }).addClass(y.headerBox + " ui-th-column-header ui-th-" + p.p.direction + " " + s).html(w), 0 < l && w.attr("colspan", String(l)), p.p.headertitles && w.attr("title", w.text()), 0 === l && w.hide(), o.before(w), r.append(i), c = n - 1 } else 0 === c ? x.useColSpanStyle ? (w = o.attr("rowspan") ? parseInt(o.attr("rowspan"), 10) + 1 : 2, o.attr("rowspan", w)) : ($("<th>", { role: "columnheader" }).addClass(y.headerBox + " ui-th-column-header ui-th-" + p.p.direction).css({ display: t.hidden ? "none" : "" }).insertBefore(o), r.append(i)) : (r.append(i), c--); if ((v = $(p).children("thead")).prepend(b), r.insertAfter(m), f.append(v), x.useColSpanStyle && (f.find("span.ui-jqgrid-resize").each(function () { var e = $(this).parent(); e.is(":visible") && (this.style.cssText = "height: " + e.height() + "px !important; cursor: col-resize;") }), f.find("div.ui-jqgrid-sortable").each(function () { var e = $(this), t = e.parent(); t.is(":visible") && t.is(":has(span.ui-jqgrid-resize)") && e.css("top", (t.height() - e.outerHeight()) / 2 - 4 + "px") })), d = v.find("tr.jqg-first-row-header"), $(p).on("jqGridResizeStop.setGroupHeaders", function (e, t, r) { d.find("th").eq(r)[0].style.width = t + "px" }), j) try { $(j).focus() } catch (e) { } "" === $.trim($("tr.jqg-second-row-header th:eq(0)").text()) && $("tr.jqg-second-row-header th:eq(0)").prepend("&nbsp;") }) }, destroyGroupHeader: function (c) { return void 0 === c && (c = !0), this.each(function () { var e, t, r, i, o, a, n = this, l = n.grid, s = $("table.ui-jqgrid-htable thead", l.hDiv), d = n.p.colModel, p = !1; if (l) { for (n.p.frozenColumns && ($(n).jqGrid("destroyFrozenColumns"), p = !0), $(this).off(".setGroupHeaders"), n.p.groupHeaderOn = !1, e = $("<tr>", { role: "row" }).addClass("ui-jqgrid-labels"), t = 0, r = (i = l.headers).length; t < r; t++) { a = d[t].hidden ? "none" : "", o = $(i[t].el).width($("tr.jqg-first-row-header th:eq(" + t + ")", s).width()).css("display", a); try { o.removeAttr("rowSpan") } catch (e) { o.attr("rowSpan", 1) } e.append(o), 0 < (a = o.children("span.ui-jqgrid-resize")).length && (a[0].style.height = ""), o.children("div")[0].style.top = "" } $(s).children("tr.ui-jqgrid-labels").remove(), $(s).children("tr.jqg-first-row-header").remove(), $(s).prepend(e), !0 === c && $(n).jqGrid("setGridParam", { groupHeader: null }), p && $(n).jqGrid("setFrozenColumns") } }) }, isGroupHeaderOn: function () { var e = this[0]; return !0 === e.p.groupHeaderOn && e.p.groupHeader && ($.isArray(e.p.groupHeader) || $.isFunction(e.p.groupHeader)) }, refreshGroupHeaders: function () { return this.each(function () { var e, t = this, r = $(t).jqGrid("isGroupHeaderOn"); if (r && ($(t).jqGrid("destroyGroupHeader", !1), e = $.extend([], t.p.groupHeader), t.p.groupHeader = null), r && e) for (var i = 0; i < e.length; i++)$(t).jqGrid("setGroupHeaders", e[i]) }) } }), $.jgrid = $.jgrid || {}, $.extend($.jgrid, { saveState: function (e, t) { if (t = $.extend({ useStorage: !0, storageType: "localStorage", beforeSetItem: null, compression: !1, compressionModule: "LZString", compressionMethod: "compressToUTF16", debug: !1, saveData: !0 }, t || {}), e) { var r, i = "", o = "", a = $("#" + e)[0]; if (a.grid) { if ((e = $(a).data("inlineNav")) && a.p.inlineNav && $(a).jqGrid("setGridParam", { _iN: e }), (e = $(a).data("filterToolbar")) && a.p.filterToolbar && $(a).jqGrid("setGridParam", { _fT: e }), i = $(a).jqGrid("jqGridExport", { exptype: "jsonstring", ident: "", root: "", data: t.saveData }), o = "", t.saveData && (l = (o = $(a.grid.bDiv).find(".ui-jqgrid-btable tbody:first").html()).indexOf("</tr>"), o = o.slice(l + 5)), $.isFunction(t.beforeSetItem) && null != (r = t.beforeSetItem.call(a, i)) && (i = r), t.debug) { $("#gbox_tree").prepend('<a id="link_save" target="_blank" download="jqGrid_dump.txt">Click to save Dump Data</a>'); var n, l, s = [], d = {}; s.push("Grid Options\n"), s.push(i), s.push("\n"), s.push("GridData\n"), s.push(o), d.type = "plain/text;charset=utf-8"; try { n = new File(s, "jqGrid_dump.txt", d) } catch (e) { n = new Blob(s, d) } l = URL.createObjectURL(n), $("#link_save").attr("href", l).on("click", function () { $(this).remove() }) } if (t.compression && t.compressionModule) try { null != (r = window[t.compressionModule][t.compressionMethod](i)) && (i = r, o = window[t.compressionModule][t.compressionMethod](o)) } catch (e) { } if (t.useStorage && $.jgrid.isLocalStorage()) try { window[t.storageType].setItem("jqGrid" + a.p.id, i), window[t.storageType].setItem("jqGrid" + a.p.id + "_data", o) } catch (e) { 22 === e.code && alert("Local storage limit is over!") } return i } } }, loadState: function (e, t, r) { if (r = $.extend({ useStorage: !0, storageType: "localStorage", clearAfterLoad: !1, beforeSetGrid: null, afterSetGrid: null, decompression: !1, decompressionModule: "LZString", decompressionMethod: "decompressFromUTF16", restoreData: !0 }, r || {}), e) { var i, o, a, n, l = $("#" + e)[0]; if (r.useStorage) try { t = window[r.storageType].getItem("jqGrid" + l.id), o = window[r.storageType].getItem("jqGrid" + l.id + "_data") } catch (e) { } if (t) { if (r.decompression && r.decompressionModule) try { null != (i = window[r.decompressionModule][r.decompressionMethod](t)) && (t = i, o = window[r.decompressionModule][r.decompressionMethod](o)) } catch (e) { } if ((i = $.jgrid.parseFunc(t)) && "object" === $.type(i)) { l.grid && $.jgrid.gridUnload(e), $.isFunction(r.beforeSetGrid) && (d = r.beforeSetGrid(i)) && "object" === $.type(d) && (i = d); var s = function (e) { return e }, d = { reccount: i.reccount, records: i.records, lastpage: i.lastpage, shrinkToFit: s(i.shrinkToFit), data: s(i.data), datatype: s(i.datatype), grouping: s(i.grouping) }; i.shrinkToFit = !1, i.data = [], i.datatype = "local", i.grouping = !1, i.inlineNav && (a = s(i._iN), i._iN = null, delete i._iN), i.filterToolbar && (n = s(i._fT), i._fT = null, delete i._fT); var p = $("#" + e).jqGrid(i); if (p.jqGrid("delRowData", "norecs"), r.restoreData && "" !== $.trim(o) && p.append(o), p.jqGrid("setGridParam", d), i.storeNavOptions && i.navGrid && (p[0].p.navGrid = !1, p.jqGrid("navGrid", i.pager, i.navOptions, i.editOptions, i.addOptions, i.delOptions, i.searchOptions, i.viewOptions), i.navButtons && i.navButtons.length)) for (var c = 0; c < i.navButtons.length; c++)"sepclass" in i.navButtons[c][1] ? p.jqGrid("navSeparatorAdd", i.navButtons[c][0], i.navButtons[c][1]) : p.jqGrid("navButtonAdd", i.navButtons[c][0], i.navButtons[c][1]); if (p[0].refreshIndex(), i.subGrid && (s = 1 === i.multiselect ? 1 : 0, d = !0 === i.rownumbers ? 1 : 0, p.jqGrid("addSubGrid", s + d), $.each(p[0].rows, function (e, t) { $(t).hasClass("ui-sg-expanded") && $(p[0].rows[e - 1]).find("td.sgexpanded").click().click() })), i.treeGrid) for (var u = 1, h = p[0].rows.length, g = i.expColInd, f = i.treeReader.leaf_field, m = i.treeReader.expanded_field; u < h;)$(p[0].rows[u].cells[g]).find("div.treeclick").on("click", function (e) { e = e.target || e.srcElement, e = $.jgrid.stripPref(i.idPrefix, $(e, p[0].rows).closest("tr.jqgrow")[0].id), e = p[0].p._index[e]; return p[0].p.data[e][f] || (p[0].p.data[e][m] ? (p.jqGrid("collapseRow", p[0].p.data[e]), p.jqGrid("collapseNode", p[0].p.data[e])) : (p.jqGrid("expandRow", p[0].p.data[e]), p.jqGrid("expandNode", p[0].p.data[e]))), !1 }), !0 === i.ExpandColClick && $(p[0].rows[u].cells[g]).find("span.cell-wrapper").css("cursor", "pointer").on("click", function (e) { var t = e.target || e.srcElement, e = $.jgrid.stripPref(i.idPrefix, $(t, p[0].rows).closest("tr.jqgrow")[0].id), t = p[0].p._index[e]; return p[0].p.data[t][f] || (p[0].p.data[t][m] ? (p.jqGrid("collapseRow", p[0].p.data[t]), p.jqGrid("collapseNode", p[0].p.data[t])) : (p.jqGrid("expandRow", p[0].p.data[t]), p.jqGrid("expandNode", p[0].p.data[t]))), p.jqGrid("setSelection", e), !1 }), u++; i.multiselect && $.each(i.selarrrow, function () { $("#jqg_" + e + "_" + this)[i.useProp ? "prop" : "attr"]("checked", "checked") }), i.inlineNav && a && (p.jqGrid("setGridParam", { inlineNav: !1 }), p.jqGrid("inlineNav", i.pager, a)), i.filterToolbar && n && (p.jqGrid("setGridParam", { filterToolbar: !1 }), n.restoreFromFilters = !0, p.jqGrid("filterToolbar", n)), i.frozenColumns && p.jqGrid("setFrozenColumns"), p[0].updatepager(!0, !0), $.isFunction(r.afterSetGrid) && r.afterSetGrid(p), r.clearAfterLoad && (window[r.storageType].removeItem("jqGrid" + l.id), window[r.storageType].removeItem("jqGrid" + l.id + "_data")) } else alert("can not convert to object") } } }, isGridInStorage: function (e, t) { var r, i, o, a = { storageType: "localStorage" }, a = $.extend(a, t || {}); try { i = window[a.storageType].getItem("jqGrid" + e), o = window[a.storageType].getItem("jqGrid" + e + "_data"), r = null != i && null != o && "string" == typeof i && "string" == typeof o } catch (e) { r = !1 } return r }, setRegional: function (e, t) { var r = { storageType: "sessionStorage" }; if ((r = $.extend(r, t || {})).regional) { $.jgrid.saveState(e, r), r.beforeSetGrid = function (e) { return e.regional = r.regional, e.force_regional = !0, e }, $.jgrid.loadState(e, null, r); var i = $("#" + e)[0], t = $(i).jqGrid("getGridParam", "colModel"), o = -1, a = $.jgrid.getRegional(i, "nav"); $.each(t, function (e) { if (this.formatter && "actions" === this.formatter) return o = e, !1 }), -1 !== o && a && $("#" + e + " tbody tr").each(function () { var e = this.cells[o]; $(e).find(".ui-inline-edit").attr("title", a.edittitle), $(e).find(".ui-inline-del").attr("title", a.deltitle), $(e).find(".ui-inline-save").attr("title", a.savetitle), $(e).find(".ui-inline-cancel").attr("title", a.canceltitle) }); try { window[r.storageType].removeItem("jqGrid" + i.id), window[r.storageType].removeItem("jqGrid" + i.id + "_data") } catch (e) { } } }, jqGridImport: function (e, r) { r = $.extend({ imptype: "xml", impstring: "", impurl: "", mtype: "GET", impData: {}, xmlGrid: { config: "root>grid", data: "root>rows" }, jsonGrid: { config: "grid", data: "data" }, ajaxOptions: {} }, r || {}); function i(e, t) { var r, i, o, a = $(t.xmlGrid.config, e)[0], t = $(t.xmlGrid.data, e)[0]; if ($.grid.xmlToJSON) { for (o in r = $.jgrid.xmlToJSON(a)) r.hasOwnProperty(o) && (i = r[o]); t ? (t = r.grid.datatype, r.grid.datatype = "xmlstring", r.grid.datastr = e, $(n).jqGrid(i).jqGrid("setGridParam", { datatype: t })) : setTimeout(function () { $(n).jqGrid(i) }, 0) } else alert("xml2json or parse are not present") } function t(e, t) { var r; e && "string" == typeof e && (e = (r = $.jgrid.parseFunc(e))[t.jsonGrid.config], (r = r[t.jsonGrid.data]) ? (t = e.datatype, e.datatype = "jsonstring", e.datastr = r, $(n).jqGrid(e).jqGrid("setGridParam", { datatype: t })) : $(n).jqGrid(e)) } var o, n = (0 === e.indexOf("#") ? "" : "#") + $.jgrid.jqID(e); switch (r.imptype) { case "xml": $.ajax($.extend({ url: r.impurl, type: r.mtype, data: r.impData, dataType: "xml", complete: function (e, t) { "success" === t && (i(e.responseXML, r), $(n).triggerHandler("jqGridImportComplete", [e, r]), $.isFunction(r.importComplete) && r.importComplete(e)), e = null } }, r.ajaxOptions)); break; case "xmlstring": !r.impstring || "string" != typeof r.impstring || (o = $.parseXML(r.impstring)) && (i(o, r), $(n).triggerHandler("jqGridImportComplete", [o, r]), $.isFunction(r.importComplete) && r.importComplete(o)); break; case "json": $.ajax($.extend({ url: r.impurl, type: r.mtype, data: r.impData, dataType: "json", complete: function (e) { try { t(e.responseText, r), $(n).triggerHandler("jqGridImportComplete", [e, r]), $.isFunction(r.importComplete) && r.importComplete(e) } catch (e) { } e = null } }, r.ajaxOptions)); break; case "jsonstring": r.impstring && "string" == typeof r.impstring && (t(r.impstring, r), $(n).triggerHandler("jqGridImportComplete", [r.impstring, r]), $.isFunction(r.importComplete) && r.importComplete(r.impstring)) } } }), $.jgrid.extend({ jqGridExport: function (t) { t = $.extend({ exptype: "xmlstring", root: "grid", ident: "\t", addOptions: {}, data: !0 }, t || {}); var r = null; return this.each(function () { if (this.grid) { var e = $.extend(!0, {}, $(this).jqGrid("getGridParam"), t.addOptions); switch (e.rownumbers && (e.colNames.splice(0, 1), e.colModel.splice(0, 1)), e.multiselect && (e.colNames.splice(0, 1), e.colModel.splice(0, 1)), e.subGrid && (e.colNames.splice(0, 1), e.colModel.splice(0, 1)), e.knv = null, t.data || (e.data = [], e._index = {}), t.exptype) { case "xmlstring": r = "<" + t.root + ">" + $.jgrid.jsonToXML(e, { xmlDecl: "" }) + "</" + t.root + ">"; break; case "jsonstring": r = $.jgrid.stringify(e), t.root && (r = "{" + t.root + ":" + r + "}") } } }), r }, excelExport: function (l) { return l = $.extend({ exptype: "remote", url: null, oper: "oper", tag: "excel", beforeExport: null, exporthidden: !1, exportgrouping: !1, exportOptions: {} }, l || {}), this.each(function () { if (this.grid && "remote" === l.exptype) { var e, t = $.extend({}, this.p.postData); if (t[l.oper] = l.tag, $.isFunction(l.beforeExport) && (n = l.beforeExport.call(this, t), $.isPlainObject(n) && (t = n)), l.exporthidden) { for (var r = this.p.colModel, i = r.length, o = [], a = 0; a < i; a++)void 0 === r[a].hidden && (r[a].hidden = !1), o.push({ name: r[a].name, hidden: r[a].hidden }); var n = JSON.stringify(o); "string" == typeof n && (t.colModel = n) } l.exportgrouping && "string" == typeof (e = JSON.stringify(this.p.groupingView)) && (t.groupingView = e); var t = jQuery.param(t), t = -1 !== l.url.indexOf("?") ? l.url + "&" + t : l.url + "?" + t; window.location = t } }) } }), $.jgrid.inlineEdit = $.jgrid.inlineEdit || {}, $.jgrid.extend({ editRow: function (c, e, t, r, i, o, a, n, l) { var u = {}, s = $.makeArray(arguments).slice(1), h = this[0]; return "object" === $.type(s[0]) ? u = s[0] : (void 0 !== e && (u.keys = e), $.isFunction(t) && (u.oneditfunc = t), $.isFunction(r) && (u.successfunc = r), void 0 !== i && (u.url = i), void 0 !== o && (u.extraparam = o), $.isFunction(a) && (u.aftersavefunc = a), $.isFunction(n) && (u.errorfunc = n), $.isFunction(l) && (u.afterrestorefunc = l)), u = $.extend(!0, { keys: !1, keyevent: "keydown", onEnter: null, onEscape: null, oneditfunc: null, successfunc: null, url: null, extraparam: {}, aftersavefunc: null, errorfunc: null, afterrestorefunc: null, restoreAfterError: !0, mtype: "POST", focusField: !0, saveui: "enable", savetext: $.jgrid.getRegional(h, "defaults.savetext") }, $.jgrid.inlineEdit, u), this.each(function () { var o, a, t, n, e, l = 0, s = null, d = {}, p = $(this).jqGrid("getStyleUI", h.p.styleUI + ".inlinedit", "inputClass", !0); h.grid && !1 !== (t = $(h).jqGrid("getInd", c, !0)) && (h.p.beforeAction = !0, void 0 === (e = $.isFunction(u.beforeEditRow) ? u.beforeEditRow.call(h, u, c) : void 0) && (e = !0), e ? "0" !== ($(t).attr("editable") || "0") || $(t).hasClass("not-editable-row") || (n = h.p.colModel, $(t).children('td[role="gridcell"]').each(function (t) { o = n[t].name; var e, r, i = !0 === h.p.treeGrid && o === h.p.ExpandColumn; if (i) a = $("span:first", this).html(); else try { a = $.unformat.call(h, this, { rowId: c, colModel: n[t] }, t) } catch (e) { a = n[t].edittype && "textarea" === n[t].edittype ? $(this).text() : $(this).html() } "cb" !== o && "subgrid" !== o && "rn" !== o && (h.p.autoencode && (a = $.jgrid.htmlDecode(a)), !0 === n[t].editable && (d[o] = a, null === s && (s = t), (i ? $("span:first", this) : $(this)).html(""), e = $.extend({}, n[t].editoptions || {}, { id: c + "_" + o, name: o, rowId: c, oper: "edit", module: "inline" }), n[t].edittype || (n[t].edittype = "text"), ("&nbsp;" === a || "&#160;" === a || null !== a && 1 === a.length && 160 === a.charCodeAt(0)) && (a = ""), r = $.jgrid.createEl.call(h, n[t].edittype, e, a, !0, $.extend({}, $.jgrid.ajaxOptions, h.p.ajaxSelectOptions || {})), $(r).addClass("editable inline-edit-cell"), -1 < $.inArray(n[t].edittype, ["text", "textarea", "password", "select"]) && $(r).addClass(p), (i ? $("span:first", this) : $(this)).append(r), $.jgrid.bindEv.call(h, r, e), "select" === n[t].edittype && void 0 !== n[t].editoptions && !0 === n[t].editoptions.multiple && void 0 === n[t].editoptions.dataUrl && $.jgrid.msie() && $(r).width($(r).width()), l++)) }), 0 < l && (d.id = c, h.p.savedRow.push(d), $(t).attr("editable", "1"), u.focusField && ("number" == typeof u.focusField && parseInt(u.focusField, 10) <= n.length && (s = u.focusField), setTimeout(function () { var e = $("td:eq(" + s + ") :input:visible", t).not(":disabled"); 0 < e.length && e.focus() }, 0)), !0 === u.keys && $(t).on(u.keyevent, function (e) { if (27 === e.keyCode) { if ($.isFunction(u.onEscape)) return u.onEscape.call(h, c, u, e), !0; if ($(h).jqGrid("restoreRow", c, u), h.p.inlineNav) try { $(h).jqGrid("showAddEditButtons") } catch (e) { } return !1 } if (13 === e.keyCode) { if ("TEXTAREA" === e.target.tagName) return !0; if ($.isFunction(u.onEnter)) return u.onEnter.call(h, c, u, e), !0; if ($(h).jqGrid("saveRow", c, u) && h.p.inlineNav) try { $(h).jqGrid("showAddEditButtons") } catch (e) { } return !1 } }), $(h).triggerHandler("jqGridInlineEditRow", [c, u]), $.isFunction(u.oneditfunc) && u.oneditfunc.call(h, c))) : h.p.beforeAction = !1) }) }, saveRow: function (a, e, t, r, i, o, n) { var l = $.makeArray(arguments).slice(1), s = {}, d = this[0]; "object" === $.type(l[0]) ? s = l[0] : ($.isFunction(e) && (s.successfunc = e), void 0 !== t && (s.url = t), void 0 !== r && (s.extraparam = r), $.isFunction(i) && (s.aftersavefunc = i), $.isFunction(o) && (s.errorfunc = o), $.isFunction(n) && (s.afterrestorefunc = n)), s = $.extend(!0, { successfunc: null, url: null, extraparam: {}, aftersavefunc: null, errorfunc: null, afterrestorefunc: null, restoreAfterError: !0, mtype: "POST", saveui: "enable", savetext: $.jgrid.getRegional(d, "defaults.savetext") }, $.jgrid.inlineEdit, s); var p, c, u, h, g = !1, f = {}, m = {}, v = {}, b = !1, j = $.trim($(d).jqGrid("getStyleUI", d.p.styleUI + ".common", "error", !0)); if (!d.grid) return g; if (!1 === (h = $(d).jqGrid("getInd", a, !0))) return g; var y, w, x, _, q, I = $.jgrid.getRegional(d, "errors"), D = $.jgrid.getRegional(d, "edit"), o = $.isFunction(s.beforeSaveRow) ? s.beforeSaveRow.call(d, s, a) : void 0; if (void 0 === o && (o = !0), o) { if (n = $(h).attr("editable"), s.url = s.url || d.p.editurl, "1" === n) { if ($(h).children('td[role="gridcell"]').each(function (e) { if (y = d.p.colModel[e], p = y.name, x = "", "cb" !== p && "subgrid" !== p && !0 === y.editable && "rn" !== p && !$(this).hasClass("not-editable-cell")) { switch (y.edittype) { case "checkbox": var t = ["Yes", "No"]; y.editoptions && y.editoptions.value && (t = y.editoptions.value.split(":")), f[p] = $("input", this).is(":checked") ? t[0] : t[1], x = $("input", this); break; case "text": case "password": case "textarea": case "button": f[p] = $("input, textarea", this).val(), x = $("input, textarea", this); break; case "select": var r; y.editoptions.multiple ? (t = $("select", this), r = [], f[p] = $(t).val(), f[p] ? f[p] = f[p].join(",") : f[p] = "", $("select option:selected", this).each(function (e, t) { r[e] = $(t).text() }), m[p] = r.join(",")) : (f[p] = $("select option:selected", this).val(), m[p] = $("select option:selected", this).text()), y.formatter && "select" === y.formatter && (m = {}), x = $("select", this); break; case "custom": try { if (!y.editoptions || !$.isFunction(y.editoptions.custom_value)) throw "e1"; if (f[p] = y.editoptions.custom_value.call(d, $(".customelement", this), "get"), void 0 === f[p]) throw "e2" } catch (e) { "e1" === e ? $.jgrid.info_dialog(I.errcap, "function 'custom_value' " + D.msg.nodefined, D.bClose, { styleUI: d.p.styleUI }) : $.jgrid.info_dialog(I.errcap, e.message, D.bClose, { styleUI: d.p.styleUI }) } }if (!1 === (u = $.jgrid.checkValues.call(d, f[p], e))[0]) return w = e, !1; d.p.autoencode && (f[p] = $.jgrid.htmlEncode(f[p])), "clientArray" !== s.url && y.editoptions && !0 === y.editoptions.NullIfEmpty && "" === f[p] && (v[p] = "null", b = !0) } }), !1 === u[0]) { try { $.isFunction(d.p.validationCell) ? d.p.validationCell.call(d, x, u[1], h.rowIndex, w) : (_ = $(d).jqGrid("getGridRowById", a), q = $.jgrid.findPos(_), $.jgrid.info_dialog(I.errcap, u[1], D.bClose, { left: q[0], top: q[1] + $(_).outerHeight(), styleUI: d.p.styleUI, onClose: function () { 0 <= w && $("#" + a + "_" + d.p.colModel[w].name).focus() } })) } catch (e) { alert(u[1]) } return g } var o = d.p.prmNames, C = a, n = !1 === d.p.keyName ? o.id : d.p.keyName; if (f && (f[o.oper] = o.editoper, void 0 === f[n] || "" === f[n] ? f[n] = a : h.id !== d.p.idPrefix + f[n] && (o = $.jgrid.stripPref(d.p.idPrefix, a), void 0 !== d.p._index[o] && (d.p._index[f[n]] = d.p._index[o], delete d.p._index[o]), a = d.p.idPrefix + f[n], $(h).attr("id", a), d.p.selrow === C && (d.p.selrow = a), !$.isArray(d.p.selarrrow) || 0 <= (o = $.inArray(C, d.p.selarrrow)) && (d.p.selarrrow[o] = a), d.p.multiselect && (G = "jqg_" + d.p.id + "_" + a, $("input.cbox", h).attr("id", G).attr("name", G))), void 0 === d.p.inlineData && (d.p.inlineData = {}), f = $.extend({}, f, d.p.inlineData, s.extraparam)), "clientArray" === s.url) { f = $.extend({}, f, m), d.p.autoencode && $.each(f, function (e, t) { f[e] = $.jgrid.htmlDecode(t) }), f = $.isFunction(d.p.serializeRowData) ? d.p.serializeRowData.call(d, f) : f; var F, G = $(d).jqGrid("setRowData", a, f); for ($(h).attr("editable", "0"), F = 0; F < d.p.savedRow.length; F++)if (String(d.p.savedRow[F].id) === String(C)) { c = F; break } $(d).triggerHandler("jqGridInlineAfterSaveRow", [a, G, f, s]), $.isFunction(s.aftersavefunc) && s.aftersavefunc.call(d, a, G, f, s), 0 <= c && d.p.savedRow.splice(c, 1), g = !0, $(h).removeClass("jqgrid-new-row").off("keydown") } else $(d).jqGrid("progressBar", { method: "show", loadtype: s.saveui, htmlcontent: s.savetext }), (v = $.extend({}, f, v))[n] = $.jgrid.stripPref(d.p.idPrefix, v[n]), $.ajax($.extend({ url: s.url, data: $.isFunction(d.p.serializeRowData) ? d.p.serializeRowData.call(d, v) : v, type: s.mtype, async: !1, complete: function (e, t) { if ($(d).jqGrid("progressBar", { method: "hide", loadtype: s.saveui, htmlcontent: s.savetext }), "success" === t) { var r, i = !0, o = $(d).triggerHandler("jqGridInlineSuccessSaveRow", [e, a, s]); if ($.isArray(o) || (o = [!0, v]), o[0] && $.isFunction(s.successfunc) && (o = s.successfunc.call(d, e)), $.isArray(o) ? (i = o[0], f = o[1] || f) : i = o, !0 === i) { for (d.p.autoencode && $.each(f, function (e, t) { f[e] = $.jgrid.htmlDecode(t) }), b && $.each(f, function (e) { "null" === f[e] && (f[e] = "") }), f = $.extend({}, f, m), $(d).jqGrid("setRowData", a, f), $(h).attr("editable", "0"), r = 0; r < d.p.savedRow.length; r++)if (String(d.p.savedRow[r].id) === String(a)) { c = r; break } $(d).triggerHandler("jqGridInlineAfterSaveRow", [a, e, f, s]), $.isFunction(s.aftersavefunc) && s.aftersavefunc.call(d, a, e, f, s), 0 <= c && d.p.savedRow.splice(c, 1), g = !0, $(h).removeClass("jqgrid-new-row").off("keydown") } else $(d).triggerHandler("jqGridInlineErrorSaveRow", [a, e, t, null, s]), $.isFunction(s.errorfunc) && s.errorfunc.call(d, a, e, t, null), !0 === s.restoreAfterError && $(d).jqGrid("restoreRow", a, s) } }, error: function (e, t, r) { if ($("#lui_" + $.jgrid.jqID(d.p.id)).hide(), $(d).triggerHandler("jqGridInlineErrorSaveRow", [a, e, t, r, s]), $.isFunction(s.errorfunc)) s.errorfunc.call(d, a, e, t, r); else { var i = e.responseText || e.statusText; try { $.jgrid.info_dialog(I.errcap, '<div class="' + j + '">' + i + "</div>", D.bClose, { buttonalign: "right", styleUI: d.p.styleUI }) } catch (e) { alert(i) } } !0 === s.restoreAfterError && $(d).jqGrid("restoreRow", a, s) } }, $.jgrid.ajaxOptions, d.p.ajaxRowOptions || {})) } return g } }, restoreRow: function (n, e) { var t = $.makeArray(arguments).slice(1), l = {}; return "object" === $.type(t[0]) ? l = t[0] : $.isFunction(e) && (l.afterrestorefunc = e), l = $.extend(!0, {}, $.jgrid.inlineEdit, l), this.each(function () { var e, t, r = this, i = -1, o = {}; if (r.grid && !1 !== (e = $(r).jqGrid("getInd", n, !0))) { var a = $.isFunction(l.beforeCancelRow) ? l.beforeCancelRow.call(r, l, n) : void 0; if (void 0 === a && (a = !0), a) { for (t = 0; t < r.p.savedRow.length; t++)if (String(r.p.savedRow[t].id) === String(n)) { i = t; break } if (0 <= i) { if ($.isFunction($.fn.datepicker)) try { $("input.hasDatepicker", "#" + $.jgrid.jqID(e.id)).datepicker("hide") } catch (e) { } $.each(r.p.colModel, function () { r.p.savedRow[i].hasOwnProperty(this.name) && (o[this.name] = r.p.savedRow[i][this.name]) }), $(r).jqGrid("setRowData", n, o), $(e).attr("editable", "0").off("keydown"), r.p.savedRow.splice(i, 1), $("#" + $.jgrid.jqID(n), "#" + $.jgrid.jqID(r.p.id)).hasClass("jqgrid-new-row") && setTimeout(function () { $(r).jqGrid("delRowData", n), $(r).jqGrid("showAddEditButtons") }, 0) } $(r).triggerHandler("jqGridInlineAfterRestoreRow", [n]), $.isFunction(l.afterrestorefunc) && l.afterrestorefunc.call(r, n) } } }) }, addRow: function (i) { return i = $.extend(!0, { rowID: null, initdata: {}, position: "first", useDefValues: !0, useFormatter: !1, addRowParams: { extraparam: {} } }, i || {}), this.each(function () { var t, e, r; this.grid && ((t = this).p.beforeAction = !0, void 0 === (r = $.isFunction(i.beforeAddRow) ? i.beforeAddRow.call(t, i.addRowParams) : void 0) && (r = !0), r ? (i.rowID = $.isFunction(i.rowID) ? i.rowID.call(t, i) : null != i.rowID ? i.rowID : $.jgrid.randId(), !0 === i.useDefValues && $(t.p.colModel).each(function () { var e; this.editoptions && this.editoptions.defaultValue && (e = this.editoptions.defaultValue, e = $.isFunction(e) ? e.call(t) : e, i.initdata[this.name] = e) }), $(t).jqGrid("addRowData", i.rowID, i.initdata, i.position), i.rowID = t.p.idPrefix + i.rowID, $("#" + $.jgrid.jqID(i.rowID), "#" + $.jgrid.jqID(t.p.id)).addClass("jqgrid-new-row"), i.useFormatter ? $("#" + $.jgrid.jqID(i.rowID) + " .ui-inline-edit", "#" + $.jgrid.jqID(t.p.id)).click() : (r = (e = t.p.prmNames).oper, i.addRowParams.extraparam[r] = e.addoper, $(t).jqGrid("editRow", i.rowID, i.addRowParams), $(t).jqGrid("setSelection", i.rowID))) : t.p.beforeAction = !1) }) }, inlineNav: function (a, n) { var l = this[0], s = $.jgrid.getRegional(l, "nav"), e = $.jgrid.styleUI[l.p.styleUI].inlinedit; return n = $.extend(!0, { edit: !0, editicon: e.icon_edit_nav, add: !0, addicon: e.icon_add_nav, save: !0, saveicon: e.icon_save_nav, cancel: !0, cancelicon: e.icon_cancel_nav, addParams: { addRowParams: { extraparam: {} } }, editParams: {}, restoreAfterSelect: !0, saveAfterSelect: !1 }, s, n || {}), this.each(function () { if (this.grid && !this.p.inlineNav) { var o = $.jgrid.jqID(l.p.id), t = $.trim($(l).jqGrid("getStyleUI", l.p.styleUI + ".common", "disabled", !0)); if (l.p.navGrid || $(l).jqGrid("navGrid", a, { refresh: !1, edit: !1, add: !1, del: !1, search: !1, view: !1 }), $(l).data("inlineNav") || $(l).data("inlineNav", n), l.p.force_regional && (n = $.extend(n, s)), (l.p.inlineNav = !0) === n.addParams.useFormatter) for (var e, r = l.p.colModel, i = 0; i < r.length; i++)if (r[i].formatter && "actions" === r[i].formatter) { r[i].formatoptions && (e = $.extend({ keys: !1, onEdit: null, onSuccess: null, afterSave: null, onError: null, afterRestore: null, extraparam: {}, url: null }, r[i].formatoptions), n.addParams.addRowParams = { keys: e.keys, oneditfunc: e.onEdit, successfunc: e.onSuccess, url: e.url, extraparam: e.extraparam, aftersavefunc: e.afterSave, errorfunc: e.onError, afterrestorefunc: e.afterRestore }); break } n.add && $(l).jqGrid("navButtonAdd", a, { caption: n.addtext, title: n.addtitle, buttonicon: n.addicon, id: l.p.id + "_iladd", internal: !0, onClickButton: function () { void 0 === l.p.beforeAction && (l.p.beforeAction = !0), $(l).jqGrid("addRow", n.addParams), !n.addParams.useFormatter && l.p.beforeAction && ($("#" + o + "_ilsave").removeClass(t), $("#" + o + "_ilcancel").removeClass(t), $("#" + o + "_iladd").addClass(t), $("#" + o + "_iledit").addClass(t)) } }), n.edit && $(l).jqGrid("navButtonAdd", a, { caption: n.edittext, title: n.edittitle, buttonicon: n.editicon, id: l.p.id + "_iledit", internal: !0, onClickButton: function () { var e = $(l).jqGrid("getGridParam", "selrow"); e ? (void 0 === l.p.beforeAction && (l.p.beforeAction = !0), $(l).jqGrid("editRow", e, n.editParams), l.p.beforeAction && ($("#" + o + "_ilsave").removeClass(t), $("#" + o + "_ilcancel").removeClass(t), $("#" + o + "_iladd").addClass(t), $("#" + o + "_iledit").addClass(t))) : ($.jgrid.viewModal("#alertmod_" + o, { gbox: "#gbox_" + o, jqm: !0 }), $("#jqg_alrt").focus()) } }), n.save && ($(l).jqGrid("navButtonAdd", a, { caption: n.savetext || "", title: n.savetitle || "Save row", buttonicon: n.saveicon, id: l.p.id + "_ilsave", internal: !0, onClickButton: function () { var e, t, r, i = l.p.savedRow[0].id; i ? (t = (e = l.p.prmNames).oper, r = n.editParams, $("#" + $.jgrid.jqID(i), "#" + o).hasClass("jqgrid-new-row") ? (n.addParams.addRowParams.extraparam[t] = e.addoper, r = n.addParams.addRowParams) : (n.editParams.extraparam || (n.editParams.extraparam = {}), n.editParams.extraparam[t] = e.editoper), $(l).jqGrid("saveRow", i, r) && $(l).jqGrid("showAddEditButtons")) : ($.jgrid.viewModal("#alertmod_" + o, { gbox: "#gbox_" + o, jqm: !0 }), $("#jqg_alrt").focus()) } }), $("#" + o + "_ilsave").addClass(t)), n.cancel && ($(l).jqGrid("navButtonAdd", a, { caption: n.canceltext || "", title: n.canceltitle || "Cancel row editing", buttonicon: n.cancelicon, id: l.p.id + "_ilcancel", internal: !0, onClickButton: function () { var e = l.p.savedRow[0].id, t = n.editParams; e ? ($("#" + $.jgrid.jqID(e), "#" + o).hasClass("jqgrid-new-row") && (t = n.addParams.addRowParams), $(l).jqGrid("restoreRow", e, t), $(l).jqGrid("showAddEditButtons")) : ($.jgrid.viewModal("#alertmod", { gbox: "#gbox_" + o, jqm: !0 }), $("#jqg_alrt").focus()) } }), $("#" + o + "_ilcancel").addClass(t)), !0 !== n.restoreAfterSelect && !0 !== n.saveAfterSelect || $(l).on("jqGridBeforeSelectRow.inlineNav", function (e, t) { 0 < l.p.savedRow.length && !0 === l.p.inlineNav && t !== l.p.selrow && null !== l.p.selrow && (t = !0, l.p.selrow === n.addParams.rowID ? $(l).jqGrid("delRowData", l.p.selrow) : !0 === n.restoreAfterSelect ? $(l).jqGrid("restoreRow", l.p.selrow, n.editParams) : t = $(l).jqGrid("saveRow", l.p.selrow, n.editParams), t && $(l).jqGrid("showAddEditButtons")) }) } }) }, showAddEditButtons: function () { return this.each(function () { var e, t; this.grid && (e = $.jgrid.jqID(this.p.id), t = $.trim($(this).jqGrid("getStyleUI", this.p.styleUI + ".common", "disabled", !0)), $("#" + e + "_ilsave").addClass(t), $("#" + e + "_ilcancel").addClass(t), $("#" + e + "_iladd").removeClass(t), $("#" + e + "_iledit").removeClass(t)) }) }, showSaveCancelButtons: function () { return this.each(function () { var e, t; this.grid && (e = $.jgrid.jqID(this.p.id), t = $.trim($(this).jqGrid("getStyleUI", this.p.styleUI + ".common", "disabled", !0)), $("#" + e + "_ilsave").removeClass(t), $("#" + e + "_ilcancel").removeClass(t), $("#" + e + "_iladd").addClass(t), $("#" + e + "_iledit").addClass(t)) }) } }), $.jgrid.msie() && 8 === $.jgrid.msiever() && ($.expr[":"].hidden = function (e) { return 0 === e.offsetWidth || 0 === e.offsetHeight || "none" === e.style.display }), $.jgrid._multiselect = !1, $.ui && $.ui.multiselect && ($.ui.multiselect.prototype._setSelected && (setSelected = $.ui.multiselect.prototype._setSelected, $.ui.multiselect.prototype._setSelected = function (e, t) { var r, e = setSelected.call(this, e, t); return t && this.selectedList && (r = this.element, this.selectedList.find("li").each(function () { $(this).data("optionLink") && $(this).data("optionLink").remove().appendTo(r) })), e }), $.ui.multiselect.prototype.destroy && ($.ui.multiselect.prototype.destroy = function () { this.element.show(), this.container.remove(), (void 0 === $.Widget ? $.widget : $.Widget).prototype.destroy.apply(this, arguments) }), $.jgrid._multiselect = !0), $.jgrid.extend({ sortableColumns: function (l) { return this.each(function () { var n = this, e = $.jgrid.jqID(n.p.id), t = !1; function r() { n.p.disableClick = !0, n.p.frozenColumns && ($(n).jqGrid("destroyFrozenColumns"), t = !0) } function i() { setTimeout(function () { n.p.disableClick = !1, t && ($(n).jqGrid("setFrozenColumns"), t = !1) }, 50) } var o, a, e = { tolerance: "pointer", axis: "x", scrollSensitivity: "1", items: ">th:not(:has(#jqgh_" + e + "_cb,#jqgh_" + e + "_rn,#jqgh_" + e + "_subgrid),:hidden)", placeholder: { element: function (e) { return $(document.createElement(e[0].nodeName)).addClass(e[0].className + " ui-sortable-placeholder ui-state-highlight").removeClass("ui-sortable-helper")[0] }, update: function (e, t) { t.height(e.currentItem.innerHeight() - parseInt(e.currentItem.css("paddingTop") || 0, 10) - parseInt(e.currentItem.css("paddingBottom") || 0, 10)), t.width(e.currentItem.innerWidth() - parseInt(e.currentItem.css("paddingLeft") || 0, 10) - parseInt(e.currentItem.css("paddingRight") || 0, 10)) } }, update: function (e, t) { var r = $(t.item).parent(), t = $(">th", r), r = n.p.colModel, i = {}, o = n.p.id + "_"; $.each(r, function (e) { i[this.name] = e }); var a = []; t.each(function () { var e = $(">div", this).get(0).id.replace(/^jqgh_/, "").replace(o, ""); i.hasOwnProperty(e) && a.push(i[e]) }), $(n).jqGrid("remapColumns", a, !0, !0), $.isFunction(n.p.sortable.update) && n.p.sortable.update(a) } }; n.p.sortable.options ? $.extend(e, n.p.sortable.options) : $.isFunction(n.p.sortable) && (n.p.sortable = { update: n.p.sortable }), e.start ? (o = e.start, e.start = function (e, t) { r(), o.call(this, e, t) }) : e.start = r, e.stop ? (a = e.stop, e.stop = function (e, t) { i(), a.call(this, e, t) }) : e.stop = i, n.p.sortable.exclude && (e.items += ":not(" + n.p.sortable.exclude + ")"); e = l.sortable(e), e = e.data("sortable") || e.data("uiSortable"); null != e && (e.data("sortable").floating = !0) }) }, columnChooser: function (t) { var r, i, e, o = this, n = {}, a = [], l = o.jqGrid("getGridParam", "colModel"), s = o.jqGrid("getGridParam", "colNames"), d = function (e) { return $.ui.multiselect.prototype && e.data($.ui.multiselect.prototype.widgetFullName || $.ui.multiselect.prototype.widgetName) || e.data("ui-multiselect") || e.data("multiselect") }, p = $.jgrid.getRegional(this[0], "col"); if (!$("#colchooser_" + $.jgrid.jqID(o[0].p.id)).length) { if (r = $('<div id="colchooser_' + o[0].p.id + '" style="position:relative;overflow:hidden"><div><select multiple="multiple"></select></div></div>'), i = $("select", r), t = $.extend({ width: 400, height: 240, classname: null, done: function (e) { e && o.jqGrid("remapColumns", e, !0) }, msel: "multiselect", dlog: "dialog", dialog_opts: { minWidth: 470, dialogClass: "ui-jqdialog" }, dlog_opts: function (e) { var t = {}; return t[e.bSubmit] = function () { e.apply_perm(), e.cleanup(!1) }, t[e.bCancel] = function () { e.cleanup(!0) }, $.extend(!0, { buttons: t, close: function () { e.cleanup(!0) }, modal: e.modal || !1, resizable: e.resizable || !0, width: e.width + 70, resize: u }, e.dialog_opts || {}) }, apply_perm: function () { var a = []; $("option", i).each(function () { $(this).is(":selected") ? o.jqGrid("showCol", l[this.value].name) : o.jqGrid("hideCol", l[this.value].name) }), $("option[selected]", i).each(function () { a.push(parseInt(this.value, 10)) }), $.each(a, function () { delete n[l[parseInt(this, 10)].name] }), $.each(n, function () { var e, t, r, i, o = parseInt(this, 10); e = a, r = t = o, a = 0 <= t ? (o = (i = e.slice()).splice(t, Math.max(e.length - t, t)), t > e.length && (t = e.length), i[t] = r, i.concat(o)) : e }), t.done && t.done.call(o, a), o.jqGrid("setGridWidth", o[0].p.width, o[0].p.shrinkToFit) }, cleanup: function (e) { c(t.dlog, r, "destroy"), c(t.msel, i, "destroy"), r.remove(), e && t.done && t.done.call(o) }, msel_opts: {} }, p, t || {}), $.ui && $.ui.multiselect && $.ui.multiselect.defaults) { if (!$.jgrid._multiselect) return void alert("Multiselect plugin loaded after jqGrid. Please load the plugin before the jqGrid!"); t.msel_opts = $.extend($.ui.multiselect.defaults, t.msel_opts) } t.caption && r.attr("title", t.caption), t.classname && (r.addClass(t.classname), i.addClass(t.classname)), t.width && ($(">div", r).css({ width: t.width, margin: "0 auto" }), i.css("width", t.width)), t.height && ($(">div", r).css("height", t.height), i.css("height", t.height - 10)), i.empty(), $.each(l, function (e) { n[this.name] = e, this.hidedlg ? this.hidden || a.push(e) : i.append("<option value='" + e + "' " + (this.hidden ? "" : "selected='selected'") + ">" + $.jgrid.stripHtml(s[e]) + "</option>") }), e = $.isFunction(t.dlog_opts) ? t.dlog_opts.call(o, t) : t.dlog_opts, c(t.dlog, r, e), p = $.isFunction(t.msel_opts) ? t.msel_opts.call(o, t) : t.msel_opts, c(t.msel, i, p), e = $("#colchooser_" + $.jgrid.jqID(o[0].p.id)); var p = $(".ui-jqgrid").css("font-size") || "11px"; e.parent().css("font-size", p), e.css({ margin: "auto" }), e.find(">div").css({ width: "100%", height: "100%", margin: "auto" }), (p = d(i)).container.css({ width: "100%", height: "100%", margin: "auto" }), p.selectedContainer.css({ width: 100 * p.options.dividerLocation + "%", height: "100%", margin: "auto", boxSizing: "border-box" }), p.availableContainer.css({ width: 100 - 100 * p.options.dividerLocation + "%", height: "100%", margin: "auto", boxSizing: "border-box" }), p.selectedList.css("height", "auto"), p.availableList.css("height", "auto"), e = Math.max(p.selectedList.height(), p.availableList.height()), e = Math.min(e, $(window).height()), p.selectedList.css("height", e), p.availableList.css("height", e), u() } function c(e, t) { e && ("string" == typeof e ? $.fn[e] && $.fn[e].apply(t, $.makeArray(arguments).slice(2)) : $.isFunction(e) && e.apply(t, $.makeArray(arguments).slice(2))) } function u() { var e = d(i), t = e.container.closest(".ui-dialog-content"); 0 < t.length && "object" == typeof t[0].style ? t[0].style.width = "" : t.css("width", ""), e.selectedList.height(Math.max(e.selectedContainer.height() - e.selectedActions.outerHeight() - 1, 1)), e.availableList.height(Math.max(e.availableContainer.height() - e.availableActions.outerHeight() - 1, 1)) } }, sortableRows: function (o) { return this.each(function () { var i = this; i.grid && (i.p.treeGrid || $.fn.sortable && ((o = $.extend({ cursor: "move", axis: "y", items: " > .jqgrow" }, o || {})).start && $.isFunction(o.start) ? (o._start_ = o.start, delete o.start) : o._start_ = !1, o.update && $.isFunction(o.update) ? (o._update_ = o.update, delete o.update) : o._update_ = !1, o.start = function (e, t) { if ($(t.item).css("border-width", "0"), $("td", t.item).each(function (e) { this.style.width = i.grid.cols[e].style.width }), i.p.subGrid) { var r = $(t.item).attr("id"); try { $(i).jqGrid("collapseSubGridRow", r) } catch (e) { } } o._start_ && o._start_.apply(this, [e, t]) }, o.update = function (e, t) { $(t.item).css("border-width", ""), !0 === i.p.rownumbers && $("td.jqgrid-rownum", i.rows).each(function (e) { $(this).html(e + 1 + (parseInt(i.p.page, 10) - 1) * parseInt(i.p.rowNum, 10)) }), o._update_ && o._update_.apply(this, [e, t]) }, $("tbody:first", i).sortable(o), $("tbody:first > .jqgrow", i).disableSelection())) }) }, gridDnD: function (i) { return this.each(function () { var e, t, a = this; if (a.grid && !a.p.treeGrid && $.fn.draggable && $.fn.droppable) { var h; if (void 0 === $("#jqgrid_dnd")[0] && $("body").append("<table id='jqgrid_dnd' class='ui-jqgrid-dnd'></table>"), "string" != typeof i || "updateDnD" !== i || !0 !== a.p.jqgdnd) { if ((i = $.extend({ drag: function (o) { return $.extend({ start: function (e, t) { var r, i; if (a.p.subGrid) { i = $(t.helper).attr("id"); try { $(a).jqGrid("collapseSubGridRow", i) } catch (e) { } } for (r = 0; r < $.data(a, "dnd").connectWith.length; r++)0 === $($.data(a, "dnd").connectWith[r]).jqGrid("getGridParam", "reccount") && $($.data(a, "dnd").connectWith[r]).jqGrid("addRowData", "jqg_empty_row", {}); t.helper.addClass("ui-state-highlight"), $("td", t.helper).each(function (e) { this.style.width = a.grid.headers[e].width + "px" }), o.onstart && $.isFunction(o.onstart) && o.onstart.call($(a), e, t) }, stop: function (e, t) { var r, i; for (t.helper.dropped && !o.dragcopy && (void 0 === (i = $(t.helper).attr("id")) && (i = $(this).attr("id")), $(a).jqGrid("delRowData", i)), r = 0; r < $.data(a, "dnd").connectWith.length; r++)$($.data(a, "dnd").connectWith[r]).jqGrid("delRowData", "jqg_empty_row"); o.onstop && $.isFunction(o.onstop) && o.onstop.call($(a), e, t) } }, o.drag_opts || {}) }, drop: function (u) { return $.extend({ accept: function (e) { if (!$(e).hasClass("jqgrow")) return e; h = $(e).closest("table.ui-jqgrid-btable"); var t = $(this).find("table.ui-jqgrid-btable:first")[0]; if (0 < h.length && void 0 !== $.data(h[0], "dnd")) { e = $.data(h[0], "dnd").connectWith; return -1 !== $.inArray("#" + $.jgrid.jqID(t.id), e) } return !1 }, drop: function (e, t) { if ($(t.draggable).hasClass("jqgrow")) { var r, i = $(t.draggable).attr("id"), o = t.draggable.parent().parent().jqGrid("getRowData", i), a = [], n = $(this).find("table.ui-jqgrid-btable:first")[0]; if ($.isPlainObject(o) && (a = Object.keys(o)), !u.dropbyname) { var l, s, d = {}, p = 0, c = $("#" + $.jgrid.jqID(n.id)).jqGrid("getGridParam", "colModel"); try { for (l = 0; l < c.length; l++)"cb" !== (s = c[l].name) && "rn" !== s && "subgrid" !== s && (void 0 !== a[p] && (d[s] = o[a[p]]), p++); o = d } catch (e) { } } t.helper.dropped = !0, $.data(h[0], "dnd").beforedrop && $.isFunction($.data(h[0], "dnd").beforedrop) && (null != (i = $.data(h[0], "dnd").beforedrop.call(n, e, t, o, $(h[0]), $(n))) && "object" == typeof i && (o = i)), t.helper.dropped && (u.autoid && (r = $.isFunction(u.autoid) ? u.autoid.call(n, o) : (r = Math.ceil(1e3 * Math.random()), u.autoidprefix + r)), $("#" + $.jgrid.jqID(n.id)).jqGrid("addRowData", r, o, u.droppos)), u.ondrop && $.isFunction(u.ondrop) && u.ondrop.call(n, e, t, o) } } }, u.drop_opts || {}) }, onstart: null, onstop: null, beforedrop: null, ondrop: null, drop_opts: { activeClass: "ui-state-active", hoverClass: "ui-state-hover", tolerance: "intersect" }, drag_opts: { revert: "invalid", helper: "clone", cursor: "move", appendTo: "#jqgrid_dnd", zIndex: 5e3 }, dragcopy: !1, dropbyname: !1, droppos: "first", autoid: !0, autoidprefix: "dnd_" }, i || {})).connectWith) for (i.connectWith = i.connectWith.split(","), i.connectWith = $.map(i.connectWith, function (e) { return $.trim(e) }), $.data(a, "dnd", i), 0 === a.p.reccount || a.p.jqgdnd || r(), a.p.jqgdnd = !0, e = 0; e < i.connectWith.length; e++)t = i.connectWith[e], $(t).closest(".ui-jqgrid-bdiv").droppable($.isFunction(i.drop) ? i.drop.call($(a), i) : i.drop) } else r() } function r() { var e = $.data(a, "dnd"); $("tr.jqgrow:not(.ui-draggable)", a).draggable($.isFunction(e.drag) ? e.drag.call($(a), e) : e.drag) } }) }, gridResize: function (opts) { return this.each(function () { var $t = this, gID = $.jgrid.jqID($t.p.id), req, optstest; $t.grid && $.fn.resizable && (opts = $.extend({}, opts || {}), opts.alsoResize ? (opts._alsoResize_ = opts.alsoResize, delete opts.alsoResize) : opts._alsoResize_ = !1, opts.stop && $.isFunction(opts.stop) ? (opts._stop_ = opts.stop, delete opts.stop) : opts._stop_ = !1, opts.stop = function (e, t) { $($t).jqGrid("setGridParam", { height: $("#gview_" + gID + " .ui-jqgrid-bdiv").height() }), $($t).jqGrid("setGridWidth", t.size.width, opts.shrinkToFit), opts._stop_ && opts._stop_.call($t, e, t), $t.p.caption && $("#gbox_" + gID).css({ height: "auto" }), $t.p.frozenColumns && (req && clearTimeout(req), req = setTimeout(function () { req && clearTimeout(req), $("#" + gID).jqGrid("destroyFrozenColumns"), $("#" + gID).jqGrid("setFrozenColumns") })) }, opts._alsoResize_ ? (optstest = "{'#gview_" + gID + " .ui-jqgrid-bdiv':true,'" + opts._alsoResize_ + "':true}", opts.alsoResize = eval("(" + optstest + ")")) : opts.alsoResize = $(".ui-jqgrid-bdiv", "#gview_" + gID), delete opts._alsoResize_, $("#gbox_" + gID).resizable(opts)) }) } }), $.assocArraySize = function (e) { var t, r = 0; for (t in e) e.hasOwnProperty(t) && r++; return r }, $.jgrid.extend({ pivotSetup: function (M, e) { var N = [], O = [], T = [], A = [], P = [], E = { grouping: !0, groupingView: { groupField: [], groupSummary: [], groupSummaryPos: [] } }, B = [], H = $.extend({ rowTotals: !1, rowTotalsText: "Total", colTotals: !1, groupSummary: !0, groupSummaryPos: "header", frozenStaticCols: !1 }, e || {}); return this.each(function () { var e, u, h, g, t, r, i, m = this, o = M.length, a = 0; function n(e, t) { var r, i = 0, o = !0; for (r in e) if (e.hasOwnProperty(r)) { if (e[r] != this[i]) { o = !1; break } if (++i >= this.length) break } return o && (_ = t), o } function l(e, t, r, i) { var o, a, n, l, s, d = t.length, p = "", c = [], u = 1; for ($.isArray(r) ? (n = r.length, c = r) : (n = 1, c[0] = r), P = [], a = (A = []).root = 0; a < n; a++) { for (var h, g = [], f = 0; f < d; f++) { if (l = "string" == typeof t[f].aggregator ? t[f].aggregator : "cust", null == r) h = o = $.trim(t[f].member) + "_" + l, c[0] = t[f].label || l + " " + $.trim(t[f].member); else { h = r[a].replace(/\s+/g, ""); try { o = 1 === d ? p + h : p + h + "_" + l + "_" + String(f) } catch (e) { } c[a] = r[a] } o = isNaN(parseInt(o, 10)) ? o : o + " ", "avg" === t[f].aggregator && (s = -1 === _ ? O.length + "_" + o : _ + "_" + o, v[s] ? v[s]++ : v[s] = 1, u = v[s]), i[o] = g[o] = function (e, t, r, i, o) { var a; if ($.isFunction(e)) a = e.call(m, t, r, i); else switch (e) { case "sum": a = parseFloat(t || 0) + parseFloat(i[r] || 0); break; case "count": "" !== t && null != t || (t = 0), a = i.hasOwnProperty(r) ? t + 1 : 0; break; case "min": a = "" === t || null == t ? parseFloat(i[r] || 0) : Math.min(parseFloat(t), parseFloat(i[r] || 0)); break; case "max": a = "" === t || null == t ? parseFloat(i[r] || 0) : Math.max(parseFloat(t), parseFloat(i[r] || 0)); break; case "avg": a = (parseFloat(t || 0) * (o - 1) + parseFloat(i[r] || 0)) / o }return a }(t[f].aggregator, i[o], t[f].member, e, u) } p += r && null != r[a] ? r[a].replace(/\s+/g, "") : "", A[o] = g, P[o] = c[a] } return i } if (H.rowTotals && 0 < H.yDimension.length && (r = H.yDimension[0].dataName, H.yDimension.splice(0, 0, { dataName: r }), H.yDimension[0].converter = function () { return "_r_Totals" }), u = $.isArray(H.xDimension) ? H.xDimension.length : 0, h = H.yDimension.length, g = $.isArray(H.aggregates) ? H.aggregates.length : 0, 0 === u || 0 === g) throw "xDimension or aggregates optiona are not set!"; for (w = 0; w < u; w++)i = { name: H.xDimension[w].dataName, frozen: H.frozenStaticCols }, null == H.xDimension[w].isGroupField && (H.xDimension[w].isGroupField = !0), i = $.extend(!0, i, H.xDimension[w]), N.push(i); for (var s, d, p, c = u - 1, f = {}, v = []; a < o;) { e = M[a]; for (var b = [], j = [], y = {}, w = 0; b[w] = $.trim(e[H.xDimension[w].dataName]), y[H.xDimension[w].dataName] = b[w], w++, w < u;); var x = 0, _ = -1; if (s = O, d = n, p = b, t = 0 < (p = _pivotfilter.call(s, d, p)).length ? p[0] : null) { if (0 <= _) { if (x = 0, 1 <= h) { for (x = 0; x < h; x++)j[x] = $.trim(e[H.yDimension[x].dataName]), H.yDimension[x].converter && $.isFunction(H.yDimension[x].converter) && (j[x] = H.yDimension[x].converter.call(this, j[x], b, j)); t = l(e, H.aggregates, j, t) } else 0 === h && (t = l(e, H.aggregates, null, t)); O[_] = t } } else { if (x = 0, 1 <= h) { for (x = 0; x < h; x++)j[x] = $.trim(e[H.yDimension[x].dataName]), H.yDimension[x].converter && $.isFunction(H.yDimension[x].converter) && (j[x] = H.yDimension[x].converter.call(this, j[x], b, j)); y = l(e, H.aggregates, j, y) } else 0 === h && (y = l(e, H.aggregates, null, y)); O.push(y) } var q, I = 0, D = null, C = null; for (q in A) if (A.hasOwnProperty(q)) { if (0 === I) f.children && void 0 !== f.children || (f = { text: q, level: 0, children: [], label: q }), D = f.children; else { for (C = null, w = 0; w < D.length; w++)if (D[w].text === q) { C = D[w]; break } D = C ? C.children : (D.push({ children: [], text: q, level: I, fields: A[q], label: P[q] }), D[D.length - 1].children) } I++ } a++ } v = null; var F, G = [], k = N.length, S = k; if (0 < h && (B[h - 1] = { useColSpanStyle: !1, groupHeaders: [] }), function e(t) { var r, i, o, a, n; for (o in t) if (t.hasOwnProperty(o)) { if ("object" != typeof t[o]) { if ("level" === o) { if (void 0 === G[t.level] && (G[t.level] = "", 0 < t.level && -1 === t.text.indexOf("_r_Totals") && (B[t.level - 1] = { useColSpanStyle: !1, groupHeaders: [] })), G[t.level] !== t.text && t.children.length && -1 === t.text.indexOf("_r_Totals") && 0 < t.level) { B[t.level - 1].groupHeaders.push({ titleText: t.label, numberOfColumns: 0 }); var l = B[t.level - 1].groupHeaders.length - 1, s = 0 == l ? S : k; if (t.level - 1 == (H.rowTotals ? 1 : 0) && 0 < l) { for (var d = 0, p = 0; p < l; p++)d += B[t.level - 1].groupHeaders[p].numberOfColumns; d && (s = d + u) } N[s] && (B[t.level - 1].groupHeaders[l].startColumnName = N[s].name, B[t.level - 1].groupHeaders[l].numberOfColumns = N.length - s), k = N.length } G[t.level] = t.text } if (t.level === h && "level" === o && 0 < h) if (1 < g) { var c = 1; for (r in t.fields) t.fields.hasOwnProperty(r) && (1 === c && B[h - 1].groupHeaders.push({ startColumnName: r, numberOfColumns: 1, titleText: t.label || t.text }), c++); B[h - 1].groupHeaders[B[h - 1].groupHeaders.length - 1].numberOfColumns = c - 1 } else B.splice(h - 1, 1) } if (null != t[o] && "object" == typeof t[o] && e(t[o]), "level" === o && 0 < t.level && (t.level === (0 === h ? t.level : h) || -1 !== G[t.level].indexOf("_r_Totals"))) for (r in i = 0, t.fields) if (t.fields.hasOwnProperty(r)) { for (a in n = {}, H.aggregates[i]) if (H.aggregates[i].hasOwnProperty(a)) switch (a) { case "member": case "label": case "aggregator": break; default: n[a] = H.aggregates[i][a] }1 < g ? (n.name = r, n.label = H.aggregates[i].label || t.label) : (n.name = t.text, n.label = "_r_Totals" === t.text ? H.rowTotalsText : t.label), N.push(n), i++ } } }(f), H.colTotals) for (var R = O.length; R--;)for (w = u; w < N.length; w++)F = N[w].name, T[F] ? T[F] += parseFloat(O[R][F] || 0) : T[F] = parseFloat(O[R][F] || 0); if (0 < c) for (w = 0; w < c; w++)N[w].isGroupField && (E.groupingView.groupField.push(N[w].name), E.groupingView.groupSummary.push(H.groupSummary), E.groupingView.groupSummaryPos.push(H.groupSummaryPos)); else E.grouping = !1; E.sortname = N[c].name, E.groupingView.hideFirstGroupCol = !0 }), { colModel: N, rows: O, groupOptions: E, groupHeaders: B, summary: T } }, jqPivot: function (r, d, p, i) { return this.each(function () { var s = this, e = p.regional || "en"; function t(e) { $.isFunction(d.onInitPivot) && d.onInitPivot.call(s), $.isArray(e) || (e = []); var t, r, i, o, a = jQuery(s).jqGrid("pivotSetup", e, d), e = 0 < $.assocArraySize(a.summary), n = $.jgrid.from.call(s, a.rows); for (d.ignoreCase && (n = n.ignoreCase()), t = 0; t < a.groupOptions.groupingView.groupField.length; t++)r = d.xDimension[t].sortorder || "asc", i = d.xDimension[t].sorttype || "text", n.orderBy(a.groupOptions.groupingView.groupField[t], r, i, "", i); if (o = d.xDimension.length, p.sortname) { for (r = p.sortorder || "asc", i = "text", t = 0; t < o; t++)if (d.xDimension[t].dataName === p.sortname) { i = d.xDimension[t].sorttype || "text"; break } n.orderBy(p.sortname, r, i, "", i) } else a.groupOptions.sortname && o && (r = d.xDimension[o - 1].sortorder || "asc", i = d.xDimension[o - 1].sorttype || "text", n.orderBy(a.groupOptions.sortname, r, i, "", i)); jQuery(s).jqGrid($.extend(!0, { datastr: $.extend(n.select(), e ? { userdata: a.summary } : {}), datatype: "jsonstring", footerrow: e, userDataOnFooter: e, colModel: a.colModel, viewrecords: !0, formatFooterData: !0 === d.colTotals, sortname: d.xDimension[0].dataName }, a.groupOptions, p || {})); var l = a.groupHeaders; if (l.length) for (t = 0; t < l.length; t++)l[t] && l[t].groupHeaders.length && jQuery(s).jqGrid("setGroupHeaders", l[t]); d.frozenStaticCols && jQuery(s).jqGrid("setFrozenColumns"), $.isFunction(d.onCompletePivot) && d.onCompletePivot.call(s), d.loadMsg && $(".loading_pivot").remove() } void 0 === d.loadMsg && (d.loadMsg = !0), d.loadMsg && $("<div class='loading_pivot ui-state-default ui-state-active row'>" + $.jgrid.getRegional(s, "regional." + e + ".defaults.loadtext") + "</div>").insertBefore(s).show(), "string" == typeof r ? $.ajax($.extend({ url: r, dataType: "json", success: function (e) { t($.jgrid.getAccessor(e, i && i.reader ? i.reader : "rows")) } }, i || {})) : t(r) }) } }), $.jgrid.extend({ setSubGrid: function () { return this.each(function () { var e, t, r = this, i = $.jgrid.styleUI[r.p.styleUI || "jQueryUI"].subgrid, i = { plusicon: i.icon_plus, minusicon: i.icon_minus, openicon: i.icon_open, expandOnLoad: !1, selectOnExpand: !1, selectOnCollapse: !1, reloadOnExpand: !0 }; if (r.p.subGridOptions = $.extend(i, r.p.subGridOptions || {}), r.p.colNames.unshift(""), r.p.colModel.unshift({ name: "subgrid", width: $.jgrid.cell_width ? r.p.subGridWidth + r.p.cellLayout : r.p.subGridWidth, sortable: !1, resizable: !1, hidedlg: !0, search: !1, fixed: !0 }), (e = r.p.subGridModel)[0]) for (e[0].align = $.extend([], e[0].align || []), t = 0; t < e[0].name.length; t++)e[0].align[t] = e[0].align[t] || "left" }) }, addSubGridCell: function (e, t) { var r, i, o, a = ""; return this.each(function () { a = this.formatCol(e, t), i = this.p.id, r = this.p.subGridOptions.plusicon, o = $.jgrid.styleUI[this.p.styleUI || "jQueryUI"].common }), '<td role="gridcell" aria-describedby="' + i + '_subgrid" class="ui-sgcollapsed sgcollapsed" ' + a + "><a style='cursor:pointer;' class='ui-sghref'><span class='" + o.icon_base + " " + r + "'></span></a></td>" }, addSubGrid: function (v, b) { return this.each(function () { var c = this; if (c.grid) { var t, r, i, o, a, u = $.jgrid.styleUI[c.p.styleUI || "jQueryUI"].base, h = $.jgrid.styleUI[c.p.styleUI || "jQueryUI"].common, g = function (e, t, r) { t = $("<td align='" + c.p.subGridModel[0].align[r] + "'></td>").html(t); $(e).append(t) }, n = function (e, t) { for (var r, i, o = $("<table class='" + u.rowTable + " ui-common-table'><tbody></tbody></table>"), a = $("<tr></tr>"), n = 0; n < c.p.subGridModel[0].name.length; n++)r = $("<th class='" + u.headerBox + " ui-th-subgrid ui-th-column ui-th-" + c.p.direction + "'></th>"), $(r).html(c.p.subGridModel[0].name[n]), $(r).width(c.p.subGridModel[0].width[n]), $(a).append(r); $(o).append(a), e && (i = c.p.xmlReader.subgrid, $(i.root + " " + i.row, e).each(function () { if (a = $("<tr class='" + h.content + " ui-subtblcell'></tr>"), !0 === i.repeatitems) $(i.cell, this).each(function (e) { g(a, $(this).text() || "&#160;", e) }); else { var e = c.p.subGridModel[0].mapping || c.p.subGridModel[0].name; if (e) for (n = 0; n < e.length; n++)g(a, $.jgrid.getXmlData(this, e[n]) || "&#160;", n) } $(o).append(a) })); e = $("table:first", c.grid.bDiv).attr("id") + "_"; return $("#" + $.jgrid.jqID(e + t)).append(o), c.grid.hDiv.loading = !1, $("#load_" + $.jgrid.jqID(c.p.id)).hide(), !1 }, l = function (e, t) { for (var r, i, o, a, n, l = $("<table class='" + u.rowTable + " ui-common-table'><tbody></tbody></table>"), s = $("<tr></tr>"), d = 0; d < c.p.subGridModel[0].name.length; d++)r = $("<th class='" + u.headerBox + " ui-th-subgrid ui-th-column ui-th-" + c.p.direction + "'></th>"), $(r).html(c.p.subGridModel[0].name[d]), $(r).width(c.p.subGridModel[0].width[d]), $(s).append(r); if ($(l).append(s), e && (a = c.p.jsonReader.subgrid, void 0 !== (i = $.jgrid.getAccessor(e, a.root)))) for (d = 0; d < i.length; d++) { if (o = i[d], s = $("<tr class='" + h.content + " ui-subtblcell'></tr>"), !0 === a.repeatitems) for (a.cell && (o = o[a.cell]), n = 0; n < o.length; n++)g(s, o[n] || "&#160;", n); else { var p = c.p.subGridModel[0].mapping || c.p.subGridModel[0].name; if (p.length) for (n = 0; n < p.length; n++)g(s, $.jgrid.getAccessor(o, p[n]) || "&#160;", n) } $(l).append(s) } e = $("table:first", c.grid.bDiv).attr("id") + "_"; return $("#" + $.jgrid.jqID(e + t)).append(l), c.grid.hDiv.loading = !1, $("#load_" + $.jgrid.jqID(c.p.id)).hide(), !1 }, s = 0; $.each(c.p.colModel, function () { !0 !== this.hidden && "rn" !== this.name && "cb" !== this.name || s++ }); var e, d, p = c.rows.length, f = 1, m = $.isFunction(c.p.isHasSubGrid); for (void 0 !== b && 0 < b && (p = (f = b) + 1); f < p;)$(c.rows[f]).hasClass("jqgrow") && (c.p.scroll && $(c.rows[f].cells[v]).off("click"), e = null, m && (e = c.p.isHasSubGrid.call(c, c.rows[f].id)), !1 === e ? c.rows[f].cells[v].innerHTML = "" : $(c.rows[f].cells[v]).on("click", function () { var e = $(this).parent("tr")[0]; if (r = c.p.id, t = e.id, a = $("#" + r + "_" + t + "_expandedContent"), $(this).hasClass("sgcollapsed")) { if ((o = !1 !== (o = $(c).triggerHandler("jqGridSubGridBeforeExpand", [r + "_" + t, t])) && "stop" !== o) && $.isFunction(c.p.subGridBeforeExpand) && (o = c.p.subGridBeforeExpand.call(c, r + "_" + t, t)), !1 === o) return !1; !0 === c.p.subGridOptions.reloadOnExpand || !1 === c.p.subGridOptions.reloadOnExpand && !a.hasClass("ui-subgrid") ? (i = 1 <= v ? "<td colspan='" + v + "'>&#160;</td>" : "", $(e).after("<tr role='row' id='" + r + "_" + t + "_expandedContent' class='ui-subgrid ui-sg-expanded'>" + i + "<td class='" + h.content + " subgrid-cell'><span class='" + h.icon_base + " " + c.p.subGridOptions.openicon + "'></span></td><td colspan='" + parseInt(c.p.colNames.length - 1 - s, 10) + "' class='" + h.content + " subgrid-data'><div id=" + r + "_" + t + " class='tablediv'></div></td></tr>"), $(c).triggerHandler("jqGridSubGridRowExpanded", [r + "_" + t, t]), $.isFunction(c.p.subGridRowExpanded) ? c.p.subGridRowExpanded.call(c, r + "_" + t, t) : function (e) { var t, r, i = $(e).attr("id"), o = { nd_: (new Date).getTime() }; if (o[c.p.prmNames.subgridid] = i, c.p.subGridModel[0]) { if (c.p.subGridModel[0].params) for (r = 0; r < c.p.subGridModel[0].params.length; r++)for (t = 0; t < c.p.colModel.length; t++)c.p.colModel[t].name === c.p.subGridModel[0].params[r] && (o[c.p.colModel[t].name] = $("td:eq(" + t + ")", e).text().replace(/\&#160\;/gi, "")); if (!c.grid.hDiv.loading) switch (c.grid.hDiv.loading = !0, $("#load_" + $.jgrid.jqID(c.p.id)).show(), c.p.subgridtype || (c.p.subgridtype = c.p.datatype), $.isFunction(c.p.subgridtype) ? c.p.subgridtype.call(c, o) : c.p.subgridtype = c.p.subgridtype.toLowerCase(), c.p.subgridtype) { case "xml": case "json": $.ajax($.extend({ type: c.p.mtype, url: $.isFunction(c.p.subGridUrl) ? c.p.subGridUrl.call(c, o) : c.p.subGridUrl, dataType: c.p.subgridtype, data: $.isFunction(c.p.serializeSubGridData) ? c.p.serializeSubGridData.call(c, o) : o, complete: function (e) { "xml" === c.p.subgridtype ? n(e.responseXML, i) : l($.jgrid.parse(e.responseText), i), e = null } }, $.jgrid.ajaxOptions, c.p.ajaxSubgridOptions || {})) } } }(e)) : a.show().removeClass("ui-sg-collapsed").addClass("ui-sg-expanded"), $(this).html("<a style='cursor:pointer;' class='ui-sghref'><span class='" + h.icon_base + " " + c.p.subGridOptions.minusicon + "'></span></a>").removeClass("sgcollapsed").addClass("sgexpanded"), c.p.subGridOptions.selectOnExpand && $(c).jqGrid("setSelection", t) } else if ($(this).hasClass("sgexpanded")) { if ((o = !1 !== (o = $(c).triggerHandler("jqGridSubGridRowColapsed", [r + "_" + t, t])) && "stop" !== o) && $.isFunction(c.p.subGridRowColapsed) && (o = c.p.subGridRowColapsed.call(c, r + "_" + t, t)), !1 === o) return !1; !0 === c.p.subGridOptions.reloadOnExpand ? a.remove(".ui-subgrid") : a.hasClass("ui-subgrid") && a.hide().addClass("ui-sg-collapsed").removeClass("ui-sg-expanded"), $(this).html("<a style='cursor:pointer;' class='ui-sghref'><span class='" + h.icon_base + " " + c.p.subGridOptions.plusicon + "'></span></a>").removeClass("sgexpanded").addClass("sgcollapsed"), c.p.subGridOptions.selectOnCollapse && $(c).jqGrid("setSelection", t) } return !1 })), f++; !0 === c.p.subGridOptions.expandOnLoad && (d = 0, c.p.multiselect && d++, c.p.rownumbers && d++, $(c.rows).filter(".jqgrow").each(function (e, t) { $(t.cells[d]).click() })), c.subGridXml = function (e, t) { n(e, t) }, c.subGridJson = function (e, t) { l(e, t) } } }) }, expandSubGridRow: function (t) { return this.each(function () { var e; (this.grid || t) && !0 === this.p.subGrid && (!(e = $(this).jqGrid("getInd", t, !0)) || (e = $("td.sgcollapsed", e)[0]) && $(e).trigger("click")) }) }, collapseSubGridRow: function (t) { return this.each(function () { var e; (this.grid || t) && !0 === this.p.subGrid && (!(e = $(this).jqGrid("getInd", t, !0)) || (e = $("td.sgexpanded", e)[0]) && $(e).trigger("click")) }) }, toggleSubGridRow: function (r) { return this.each(function () { var e, t; (this.grid || r) && !0 === this.p.subGrid && (!(e = $(this).jqGrid("getInd", r, !0)) || (t = (t = $("td.sgcollapsed", e)[0]) || $("td.sgexpanded", e)[0]) && $(t).trigger("click")) }) } }), $.jgrid.extend({ setTreeNode: function (g, f) { return this.each(function () { var r = this; if (r.grid && r.p.treeGrid) { var e, t, i, o = r.p.expColInd, a = r.p.treeReader.expanded_field, n = r.p.treeReader.leaf_field, l = r.p.treeReader.level_field, s = r.p.treeReader.icon_field, d = r.p.treeReader.loaded, p = $.jgrid.styleUI[r.p.styleUI || "jQueryUI"].common, c = g; for ($(r).triggerHandler("jqGridBeforeSetTreeNode", [c, f]), $.isFunction(r.p.beforeSetTreeNode) && r.p.beforeSetTreeNode.call(r, c, f); g < f;) { var u = $.jgrid.stripPref(r.p.idPrefix, r.rows[g].id), h = r.p._index[u], u = r.p.data[h]; "nested" === r.p.treeGridModel && (u[n] || (t = parseInt(u[r.p.treeReader.left_field], 10), i = parseInt(u[r.p.treeReader.right_field], 10), u[n] = i === t + 1 ? "true" : "false", r.rows[g].cells[r.p._treeleafpos].innerHTML = u[n])), h = parseInt(u[l], 10), i = 0 === r.p.tree_root_level ? (e = h + 1, h) : (e = h) - 1, t = "<div class='tree-wrap tree-wrap-" + r.p.direction + "' style='width:" + 18 * e + "px;'>", t += "<div style='" + ("rtl" === r.p.direction ? "right:" : "left:") + 18 * i + "px;' class='" + p.icon_base + " ", void 0 !== u[d] && ("true" === u[d] || !0 === u[d] ? u[d] = !0 : u[d] = !1), i = "true" === u[n] || !0 === u[n] ? (t += (void 0 !== u[s] && "" !== u[s] ? u[s] : r.p.treeIcons.leaf) + " tree-leaf treeclick", u[n] = !0, "leaf") : (u[n] = !1, ""), u[a] = ("true" === u[a] || !0 === u[a]) && (u[d] || void 0 === u[d]), !1 === u[a] ? t += !0 === u[n] ? "'" : r.p.treeIcons.plus + " tree-plus treeclick'" : t += !0 === u[n] ? "'" : r.p.treeIcons.minus + " tree-minus treeclick'", t += "></div></div>", $(r.rows[g].cells[o]).wrapInner("<span class='cell-wrapper" + i + "'></span>").prepend(t), h !== parseInt(r.p.tree_root_level, 10) && ($(r).jqGrid("isVisibleNode", u) || $(r.rows[g]).css("display", "none")), $(r.rows[g].cells[o]).find("div.treeclick").on("click", function (e) { e = e.target || e.srcElement, e = $.jgrid.stripPref(r.p.idPrefix, $(e, r.rows).closest("tr.jqgrow")[0].id), e = r.p._index[e]; return r.p.data[e][n] || (r.p.data[e][a] ? ($(r).jqGrid("collapseRow", r.p.data[e]), $(r).jqGrid("collapseNode", r.p.data[e])) : ($(r).jqGrid("expandRow", r.p.data[e]), $(r).jqGrid("expandNode", r.p.data[e]))), !1 }), !0 === r.p.ExpandColClick && $(r.rows[g].cells[o]).find("span.cell-wrapper").css("cursor", "pointer").on("click", function (e) { var t = e.target || e.srcElement, e = $.jgrid.stripPref(r.p.idPrefix, $(t, r.rows).closest("tr.jqgrow")[0].id), t = r.p._index[e]; return r.p.data[t][n] || (r.p.data[t][a] ? ($(r).jqGrid("collapseRow", r.p.data[t]), $(r).jqGrid("collapseNode", r.p.data[t])) : ($(r).jqGrid("expandRow", r.p.data[t]), $(r).jqGrid("expandNode", r.p.data[t]))), $(r).jqGrid("setSelection", e), !1 }), g++ } $(r).triggerHandler("jqGridAfterSetTreeNode", [c, f]), $.isFunction(r.p.afterSetTreeNode) && r.p.afterSetTreeNode.call(r, c, f) } }) }, setTreeGrid: function () { return this.each(function () { var e, t, r, i, o = this, a = 0, n = !1, l = [], s = $.jgrid.styleUI[o.p.styleUI || "jQueryUI"].treegrid; if (o.p.treeGrid) { for (r in o.p.treedatatype || $.extend(o.p, { treedatatype: o.p.datatype }), o.p.loadonce && (o.p.treedatatype = "local"), o.p.subGrid = !1, o.p.altRows = !1, o.p.treeGrid_bigData || (o.p.pgbuttons = !1, o.p.pginput = !1, o.p.rowList = []), o.p.gridview = !0, null !== o.p.rowTotal || o.p.treeGrid_bigData || (o.p.rowNum = 1e4), o.p.multiselect = !1, o.p.expColInd = 0, e = s.icon_plus, "jQueryUI" === o.p.styleUI && (e += "rtl" === o.p.direction ? "w" : "e"), o.p.treeIcons = $.extend({ plus: e, minus: s.icon_minus, leaf: s.icon_leaf }, o.p.treeIcons || {}), "nested" === o.p.treeGridModel ? o.p.treeReader = $.extend({ level_field: "level", left_field: "lft", right_field: "rgt", leaf_field: "isLeaf", expanded_field: "expanded", loaded: "loaded", icon_field: "icon" }, o.p.treeReader) : "adjacency" === o.p.treeGridModel && (o.p.treeReader = $.extend({ level_field: "level", parent_id_field: "parent", leaf_field: "isLeaf", expanded_field: "expanded", loaded: "loaded", icon_field: "icon" }, o.p.treeReader)), o.p.colModel) if (o.p.colModel.hasOwnProperty(r)) for (i in (t = o.p.colModel[r].name) !== o.p.ExpandColumn || n || (n = !0, o.p.expColInd = a), a++, t !== o.p.treeReader.level_field && t !== o.p.treeReader.left_field && t !== o.p.treeReader.right_field || (o.p.colModel[r].sorttype = "integer"), o.p.treeReader) o.p.treeReader.hasOwnProperty(i) && o.p.treeReader[i] === t && l.push(t); $.each(o.p.treeReader, function (e, t) { t && -1 === $.inArray(t, l) && ("leaf_field" === e && (o.p._treeleafpos = a), a++, o.p.colNames.push(t), o.p.colModel.push({ name: t, width: 1, hidden: !0, sortable: !1, resizable: !1, hidedlg: !0, editable: !0, search: !1 })) }) } }) }, expandRow: function (n) { this.each(function () { var e, t, r, i, o, a = this; a.p.treeGrid_bigData || (e = a.p.lastpage), a.grid && a.p.treeGrid && (t = $(a).jqGrid("getNodeChildren", n), r = a.p.treeReader.expanded_field, i = n[a.p.localReader.id], void 0 === (o = $(a).triggerHandler("jqGridBeforeExpandTreeGridRow", [i, n, t])) && (o = !0), o && $.isFunction(a.p.beforeExpandTreeGridRow) && (o = a.p.beforeExpandTreeGridRow.call(a, i, n, t)), !1 !== o && ($(t).each(function () { var e = a.p.idPrefix + $.jgrid.getAccessor(this, a.p.localReader.id); $($(a).jqGrid("getGridRowById", e)).css("display", ""), this[r] && $(a).jqGrid("expandRow", this) }), $(a).triggerHandler("jqGridAfterExpandTreeGridRow", [i, n, t]), $.isFunction(a.p.afterExpandTreeGridRow) && a.p.afterExpandTreeGridRow.call(a, i, n, t), a.p.treeGrid_bigData || (a.p.lastpage = e))) }) }, collapseRow: function (a) { this.each(function () { var e, t, r, i, o = this; o.grid && o.p.treeGrid && (e = $(o).jqGrid("getNodeChildren", a), t = o.p.treeReader.expanded_field, r = a[o.p.localReader.id], void 0 === (i = $(o).triggerHandler("jqGridBeforeCollapseTreeGridRow", [r, a, e])) && (i = !0), i && $.isFunction(o.p.beforeCollapseTreeGridRow) && (i = o.p.beforeCollapseTreeGridRow.call(o, r, a, e)), !1 !== i && ($(e).each(function () { var e = o.p.idPrefix + $.jgrid.getAccessor(this, o.p.localReader.id); $($(o).jqGrid("getGridRowById", e)).css("display", "none"), this[t] && $(o).jqGrid("collapseRow", this) }), $(o).triggerHandler("jqGridAfterCollapseTreeGridRow", [r, a, e]), $.isFunction(o.p.afterCollapseTreeGridRow) && o.p.afterCollapseTreeGridRow.call(o, r, a, e))) }) }, getRootNodes: function () { var o = []; return this.each(function () { var e, t, r = this, i = r.p.data; if (r.grid && r.p.treeGrid) switch (r.p.treeGridModel) { case "nested": e = r.p.treeReader.level_field, $(i).each(function () { parseInt(this[e], 10) === parseInt(r.p.tree_root_level, 10) && o.push(this) }); break; case "adjacency": t = r.p.treeReader.parent_id_field, $(i).each(function () { null !== this[t] && "null" !== String(this[t]).toLowerCase() || o.push(this) }) } }), o }, getNodeDepth: function (t) { var r = null; return this.each(function () { if (this.grid && this.p.treeGrid) switch (this.p.treeGridModel) { case "nested": var e = this.p.treeReader.level_field; r = parseInt(t[e], 10) - parseInt(this.p.tree_root_level, 10); break; case "adjacency": r = $(this).jqGrid("getNodeAncestors", t).length } }), r }, getNodeParent: function (c) { var u = null; return this.each(function () { var e = this; if (e.grid && e.p.treeGrid) switch (e.p.treeGridModel) { case "nested": var t = e.p.treeReader.left_field, r = e.p.treeReader.right_field, i = e.p.treeReader.level_field, o = parseInt(c[t], 10), a = parseInt(c[r], 10), n = parseInt(c[i], 10); $(this.p.data).each(function () { if (parseInt(this[i], 10) === n - 1 && parseInt(this[t], 10) < o && parseInt(this[r], 10) > a) return u = this, !1 }); break; case "adjacency": for (var l = e.p.treeReader.parent_id_field, s = e.p.localReader.id, d = c[s], p = e.p._index[d]; p--;)if (String(e.p.data[p][s]) === String($.jgrid.stripPref(e.p.idPrefix, c[l]))) { u = e.p.data[p]; break } } }), u }, getNodeChildren: function (u) { var h = []; return this.each(function () { var e = this; if (e.grid && e.p.treeGrid) { var t, r = this.p.data.length; switch (e.p.treeGridModel) { case "nested": for (var i = e.p.treeReader.left_field, o = e.p.treeReader.right_field, a = e.p.treeReader.level_field, n = parseInt(u[i], 10), l = parseInt(u[o], 10), s = parseInt(u[a], 10), d = 0; d < r; d++)(t = e.p.data[d]) && parseInt(t[a], 10) === s + 1 && parseInt(t[i], 10) > n && parseInt(t[o], 10) < l && h.push(t); break; case "adjacency": var p = e.p.treeReader.parent_id_field, c = e.p.localReader.id; for (d = 0; d < r; d++)(t = e.p.data[d]) && String(t[p]) === String($.jgrid.stripPref(e.p.idPrefix, u[c])) && h.push(t) } } }), h }, getFullTreeNode: function (c, u) { var h = []; return this.each(function () { var t, r, i, o = this, a = o.p.treeReader.expanded_field; if (o.grid && o.p.treeGrid) switch (null != u && "boolean" == typeof u || (u = !1), o.p.treeGridModel) { case "nested": var e = o.p.treeReader.left_field, n = o.p.treeReader.right_field, l = o.p.treeReader.level_field, s = parseInt(c[e], 10), d = parseInt(c[n], 10), p = parseInt(c[l], 10); $(this.p.data).each(function () { parseInt(this[l], 10) >= p && parseInt(this[e], 10) >= s && parseInt(this[e], 10) <= d && (u && (this[a] = !0), h.push(this)) }); break; case "adjacency": c && (h.push(c), r = o.p.treeReader.parent_id_field, i = o.p.localReader.id, $(this.p.data).each(function (e) { for (t = h.length, e = 0; e < t; e++)if (String($.jgrid.stripPref(o.p.idPrefix, h[e][i])) === String(this[r])) { u && (this[a] = !0), h.push(this); break } })) } }), h }, getNodeAncestors: function (t, r, i) { var o = []; return void 0 === r && (r = !1), this.each(function () { if (this.grid && this.p.treeGrid) { i = void 0 !== i && this.p.treeReader.expanded_field; for (var e = $(this).jqGrid("getNodeParent", t); e;) { if (i) try { e[i] = !0 } catch (e) { } r ? o.unshift(e) : o.push(e), e = $(this).jqGrid("getNodeParent", e) } } }), o }, isVisibleNode: function (r) { var i = !0; return this.each(function () { var e, t; this.grid && this.p.treeGrid && (e = $(this).jqGrid("getNodeAncestors", r), t = this.p.treeReader.expanded_field, $(e).each(function () { if (!(i = i && this[t])) return !1 })) }), i }, isNodeLoaded: function (i) { var o; return this.each(function () { var e, t, r = this; r.grid && r.p.treeGrid && (e = r.p.treeReader.leaf_field, t = r.p.treeReader.loaded, o = void 0 !== i && (void 0 !== i[t] ? i[t] : !!(i[e] || 0 < $(r).jqGrid("getNodeChildren", i).length))) }), o }, setLeaf: function (a, n, l) { return this.each(function () { var e, t = $.jgrid.getAccessor(a, this.p.localReader.id), r = $("#" + t, this.grid.bDiv)[0], i = this.p.treeReader.leaf_field; try { var o = this.p._index[t]; null != o && (this.p.data[o][i] = n) } catch (e) { } !0 === n ? $("div.treeclick", r).removeClass(this.p.treeIcons.minus + " tree-minus " + this.p.treeIcons.plus + " tree-plus").addClass(this.p.treeIcons.leaf + " tree-leaf") : !1 === n && (e = this.p.treeIcons.minus + " tree-minus", l && (e = this.p.treeIcons.plus + " tree-plus"), $("div.treeclick", r).removeClass(this.p.treeIcons.leaf + " tree-leaf").addClass(e)) }) }, reloadNode: function (p, c) { return this.each(function () { var e, t, r, i, o, a, n, l, s, d; this.grid && this.p.treeGrid && (d = this.p.localReader.id, e = this.p.selrow, $(this).jqGrid("delChildren", p[d]), void 0 === c && (c = !1), c || jQuery._data(this, "events").jqGridAfterSetTreeNode || $(this).on("jqGridAfterSetTreeNode.reloadNode", function () { var e, t, r = this.p.treeReader.leaf_field; this.p.reloadnode && (e = this.p.reloadnode, t = $(this).jqGrid("getNodeChildren", e), e[r] && t.length ? $(this).jqGrid("setLeaf", e, !1) : e[r] || 0 !== t.length || $(this).jqGrid("setLeaf", e, !0)), this.p.reloadnode = !1 }), t = this.p.treeReader.expanded_field, r = this.p.treeReader.parent_id_field, i = this.p.treeReader.loaded, o = this.p.treeReader.level_field, a = this.p.treeReader.leaf_field, n = this.p.treeReader.left_field, l = this.p.treeReader.right_field, s = $.jgrid.getAccessor(p, this.p.localReader.id), d = $("#" + s, this.grid.bDiv)[0], p[t] = !0, p[a] || $("div.treeclick", d).removeClass(this.p.treeIcons.plus + " tree-plus").addClass(this.p.treeIcons.minus + " tree-minus"), this.p.treeANode = d.rowIndex, this.p.datatype = this.p.treedatatype, this.p.reloadnode = p, c && (this.p.treeANode = 0 < d.rowIndex ? d.rowIndex - 1 : 1, $(this).jqGrid("delRowData", s)), "nested" === this.p.treeGridModel ? $(this).jqGrid("setGridParam", { postData: { nodeid: s, n_left: p[n], n_right: p[l], n_level: p[o] } }) : $(this).jqGrid("setGridParam", { postData: { nodeid: s, parentid: p[r], n_level: p[o] } }), $(this).trigger("reloadGrid"), p[i] = !0, "nested" === this.p.treeGridModel ? $(this).jqGrid("setGridParam", { selrow: e, postData: { nodeid: "", n_left: "", n_right: "", n_level: "" } }) : $(this).jqGrid("setGridParam", { selrow: e, postData: { nodeid: "", parentid: "", n_level: "" } })) }) }, expandNode: function (p) { return this.each(function () { var e, t, r, i, o, a, n, l, s, d; this.grid && this.p.treeGrid && (e = this.p.treeReader.expanded_field, t = this.p.treeReader.parent_id_field, r = this.p.treeReader.loaded, i = this.p.treeReader.level_field, o = this.p.treeReader.left_field, a = this.p.treeReader.right_field, p[e] || (n = $.jgrid.getAccessor(p, this.p.localReader.id), l = $("#" + this.p.idPrefix + $.jgrid.jqID(n), this.grid.bDiv)[0], s = this.p._index[n], void 0 === (d = $(this).triggerHandler("jqGridBeforeExpandTreeGridNode", [n, p])) && (d = !0), d && $.isFunction(this.p.beforeExpandTreeGridNode) && (d = this.p.beforeExpandTreeGridNode.call(this, n, p)), !1 !== d && ($(this).jqGrid("isNodeLoaded", this.p.data[s]) ? (p[e] = !0, $("div.treeclick", l).removeClass(this.p.treeIcons.plus + " tree-plus").addClass(this.p.treeIcons.minus + " tree-minus")) : this.grid.hDiv.loading || (p[e] = !0, $("div.treeclick", l).removeClass(this.p.treeIcons.plus + " tree-plus").addClass(this.p.treeIcons.minus + " tree-minus"), this.p.treeANode = l.rowIndex, this.p.datatype = this.p.treedatatype, "nested" === this.p.treeGridModel ? $(this).jqGrid("setGridParam", { postData: { nodeid: n, n_left: p[o], n_right: p[a], n_level: p[i] } }) : $(this).jqGrid("setGridParam", { postData: { nodeid: n, parentid: p[t], n_level: p[i] } }), $(this).trigger("reloadGrid"), p[r] = !0, "nested" === this.p.treeGridModel ? $(this).jqGrid("setGridParam", { postData: { nodeid: "", n_left: "", n_right: "", n_level: "" } }) : $(this).jqGrid("setGridParam", { postData: { nodeid: "", parentid: "", n_level: "" } })), $(this).triggerHandler("jqGridAfterExpandTreeGridNode", [n, p]), $.isFunction(this.p.afterExpandTreeGridNode) && this.p.afterExpandTreeGridNode.call(this, n, p)))) }) }, collapseNode: function (o) { return this.each(function () { var e, t, r, i; this.grid && this.p.treeGrid && (e = this.p.treeReader.expanded_field, o[e] && (t = $.jgrid.getAccessor(o, this.p.localReader.id), r = $("#" + this.p.idPrefix + $.jgrid.jqID(t), this.grid.bDiv)[0], void 0 === (i = $(this).triggerHandler("jqGridBeforeCollapseTreeGridNode", [t, o])) && (i = !0), i && $.isFunction(this.p.beforeCollapseTreeGridNode) && (i = this.p.beforeCollapseTreeGridNode.call(this, t, o)), (o[e] = !1) !== i && ($("div.treeclick", r).removeClass(this.p.treeIcons.minus + " tree-minus").addClass(this.p.treeIcons.plus + " tree-plus"), $(this).triggerHandler("jqGridAfterCollapseTreeGridNode", [t, o]), $.isFunction(this.p.afterCollapseTreeGridNode) && this.p.afterCollapseTreeGridNode.call(this, t, o)))) }) }, SortTree: function (p, c, u, h) { return this.each(function () { if (this.grid && this.p.treeGrid) { var e, t, r, i, o = [], a = this, n = $(this).jqGrid("getRootNodes", a.p.search), l = $.jgrid.from.call(this, n); for (Boolean(a.p.sortTreeByNodeType) && (n = a.p.sortTreeNodeOrder && "desc" === a.p.sortTreeNodeOrder.toLowerCase() ? "d" : "a", l.orderBy(a.p.treeReader.leaf_field, n, u, h)), l.orderBy(p, c, u, h), e = 0, t = (i = l.select()).length; e < t; e++)r = i[e], o.push(r), $(this).jqGrid("collectChildrenSortTree", o, r, p, c, u, h); var s = $(this).jqGrid("getDataIDs"), d = 1; $.each(o, function (e) { var t = $.jgrid.getAccessor(this, a.p.localReader.id); -1 !== $.inArray(t, s) && ($("#" + $.jgrid.jqID(a.p.id) + " tbody tr:eq(" + d + ")").after($("#" + $.jgrid.jqID(a.p.id) + " tbody tr#" + $.jgrid.jqID(t))), d++) }), o = i = l = null } }) }, searchTree: function (r) { var i, o, a, n, l, s, d, p = r.length || 0, c = [], u = [], h = []; return this.each(function () { if (this.grid && this.p.treeGrid && p) for (i = this.p.localReader.id, d = 0; d < p; d++) { var e; if (c = $(this).jqGrid("getNodeAncestors", r[d], !0, !0), Boolean(this.p.FullTreeSearchResult) ? (e = $(this).jqGrid("getFullTreeNode", r[d], !0), c = c.concat(e)) : c.push(r[d]), o = c[0][i], -1 === $.inArray(o, u)) u.push(o), h = h.concat(c); else for (l = 0, a = c.length; l < a; l++) { var t = !1; for (s = 0, n = h.length; s < n; s++)if (c[l][i] === h[s][i]) { t = !0; break } t || h.push(c[l]) } } }), h }, collectChildrenSortTree: function (a, n, l, s, d, p) { return this.each(function () { if (this.grid && this.p.treeGrid) { var e, t, r, i, o = $(this).jqGrid("getNodeChildren", n, this.p.search), o = $.jgrid.from.call(this, o); for (o.orderBy(l, s, d, p), e = 0, t = (i = o.select()).length; e < t; e++)r = i[e], a.push(r), $(this).jqGrid("collectChildrenSortTree", a, r, l, s, d, p) } }) }, setTreeRow: function (e, t) { var r = !1; return this.each(function () { this.grid && this.p.treeGrid && (r = $(this).jqGrid("setRowData", e, t)) }), r }, delTreeNode: function (c) { return this.each(function () { var e, t, r, i, o, a = this, n = a.p.localReader.id, l = a.p.treeReader.left_field, s = a.p.treeReader.right_field; if (a.grid && a.p.treeGrid) { c = $.jgrid.stripPref(a.p.idPrefix, c); var d = a.p._index[c]; if (void 0 !== d) { r = (t = parseInt(a.p.data[d][s], 10)) - parseInt(a.p.data[d][l], 10) + 1; var p = $(a).jqGrid("getFullTreeNode", a.p.data[d]); if (0 < p.length) for (e = 0; e < p.length; e++)$(a).jqGrid("delRowData", a.p.idPrefix + p[e][n]); if ("nested" === a.p.treeGridModel) { if ((i = $.jgrid.from.call(a, a.p.data).greater(l, t, { stype: "integer" }).select()).length) for (o in i) i.hasOwnProperty(o) && (i[o][l] = parseInt(i[o][l], 10) - r); if ((i = $.jgrid.from.call(a, a.p.data).greater(s, t, { stype: "integer" }).select()).length) for (o in i) i.hasOwnProperty(o) && (i[o][s] = parseInt(i[o][s], 10) - r) } } } }) }, delChildren: function (c) { return this.each(function () { var e, t, r, i, o = this, a = o.p.localReader.id, n = o.p.treeReader.left_field, l = o.p.treeReader.right_field; if (o.grid && o.p.treeGrid) { c = $.jgrid.stripPref(o.p.idPrefix, c); var s = o.p._index[c]; if (void 0 !== s) { t = (e = parseInt(o.p.data[s][l], 10)) - parseInt(o.p.data[s][n], 10) + 1; var d = $(o).jqGrid("getFullTreeNode", o.p.data[s]); if (0 < d.length) for (var p = 0; p < d.length; p++)d[p][a] !== c && $(o).jqGrid("delRowData", o.p.idPrefix + d[p][a]); if ("nested" === o.p.treeGridModel) { if ((r = $.jgrid.from(o.p.data).greater(n, e, { stype: "integer" }).select()).length) for (i in r) r.hasOwnProperty(i) && (r[i][n] = parseInt(r[i][n], 10) - t); if ((r = $.jgrid.from(o.p.data).greater(l, e, { stype: "integer" }).select()).length) for (i in r) r.hasOwnProperty(i) && (r[i][l] = parseInt(r[i][l], 10) - t) } } } }) }, addChildNode: function (e, t, r, i) { var o = this[0]; if (r) { var a, n, l, s = o.p.treeReader.expanded_field, d = o.p.treeReader.leaf_field, p = o.p.treeReader.level_field, c = o.p.treeReader.parent_id_field, u = o.p.treeReader.left_field, h = o.p.treeReader.right_field, g = o.p.treeReader.loaded, f = 0, m = t; if (void 0 === i && (i = !1), null == e) { if (0 <= (q = o.p.data.length - 1)) for (; 0 <= q;)f = Math.max(f, parseInt(o.p.data[q][o.p.localReader.id], 10)), q--; e = f + 1 } var v, b, j = $(o).jqGrid("getInd", t), y = !1; if (null == t || "" === t) m = t = null, a = "last", n = o.p.tree_root_level, q = o.p.data.length + 1; else { a = "after"; var w, x = $.jgrid.stripPref(o.p.idPrefix, t), _ = o.p._index[x]; t = (w = o.p.data[_])[o.p.localReader.id], n = parseInt(w[p], 10) + 1; var x = $(o).jqGrid("getFullTreeNode", w), q = x.length ? (m = q = x[x.length - 1][o.p.localReader.id], $(o).jqGrid("getInd", o.p.idPrefix + m)) : $(o).jqGrid("getInd", o.p.idPrefix + t); if (w[d] && (y = !0, w[s] = !0, $(o.rows[j]).find("span.cell-wrapperleaf").removeClass("cell-wrapperleaf").addClass("cell-wrapper").end().find("div.tree-leaf").removeClass(o.p.treeIcons.leaf + " tree-leaf").addClass(o.p.treeIcons.minus + " tree-minus"), o.p.data[_][d] = !1, w[g] = !0), !1 === q) throw "Parent item with id: " + m + " (" + t + ") can't be found"; q++ } if (_ = q + 1, void 0 === r[s] && (r[s] = !1), void 0 === r[g] && (r[g] = !1), r[p] = n, void 0 === r[d] && (r[d] = !0), "adjacency" === o.p.treeGridModel && (r[c] = t), "nested" === o.p.treeGridModel) if (null !== t) { if (l = parseInt(w[h], 10), (v = $.jgrid.from.call(o, o.p.data).greaterOrEquals(h, l, { stype: "integer" }).select()).length) for (b in v) v.hasOwnProperty(b) && (v[b][u] = v[b][u] > l ? parseInt(v[b][u], 10) + 2 : v[b][u], v[b][h] = v[b][h] >= l ? parseInt(v[b][h], 10) + 2 : v[b][h]); r[u] = l, r[h] = l + 1 } else { if (l = parseInt($(o).jqGrid("getCol", h, !1, "max"), 10), (v = $.jgrid.from.call(o, o.p.data).greater(u, l, { stype: "integer" }).select()).length) for (b in v) v.hasOwnProperty(b) && (v[b][u] = parseInt(v[b][u], 10) + 2); if ((v = $.jgrid.from.call(o, o.p.data).greater(h, l, { stype: "integer" }).select()).length) for (b in v) v.hasOwnProperty(b) && (v[b][h] = parseInt(v[b][h], 10) + 2); r[u] = l + 1, r[h] = l + 2 } (null === t || $(o).jqGrid("isNodeLoaded", w) || y) && ($(o).jqGrid("addRowData", e, r, a, o.p.idPrefix + m), $(o).jqGrid("setTreeNode", q, _)), w && !w[s] && i && $(o.rows[j]).find("div.treeclick").click() } } }), $.fn.jqDrag = function (e) { return i(this, e, "d") }, $.fn.jqResize = function (e, t) { return i(this, e, "r", t) }, $.jqDnR = { dnr: {}, e: 0, drag: function (e) { return "d" == M.k ? E.css({ left: M.X + e.pageX - M.pX, top: M.Y + e.pageY - M.pY }) : (E.css({ width: Math.max(e.pageX - M.pX + M.W, 0), height: Math.max(e.pageY - M.pY + M.H, 0) }), M1 && E1.css({ width: Math.max(e.pageX - M1.pX + M1.W, 0), height: Math.max(e.pageY - M1.pY + M1.H, 0) })), !1 }, stop: function () { $(document).off("mousemove", J.drag).off("mouseup", J.stop) } }; var J = $.jqDnR, M = J.dnr, E = J.e, E1, M1, i = function (e, t, r, i) { return e.each(function () { (t = t ? $(t, e) : e).on("mousedown", { e: e, k: r }, function (e) { var t = e.data, r = {}; if (E = t.e, E1 = !!i && $(i), "relative" != E.css("position")) try { E.position(r) } catch (e) { } if (M = { X: r.left || f("left") || 0, Y: r.top || f("top") || 0, W: f("width") || E[0].scrollWidth || 0, H: f("height") || E[0].scrollHeight || 0, pX: e.pageX, pY: e.pageY, k: t.k }, M1 = !(!E1 || "d" == t.k) && { X: r.left || f1("left") || 0, Y: r.top || f1("top") || 0, W: E1[0].offsetWidth || f1("width") || 0, H: E1[0].offsetHeight || f1("height") || 0, pX: e.pageX, pY: e.pageY, k: t.k }, $("input.hasDatepicker", E[0])[0]) try { $("input.hasDatepicker", E[0]).datepicker("hide") } catch (e) { } return $(document).mousemove($.jqDnR.drag).mouseup($.jqDnR.stop), !1 }) }) }, f = function (e) { return parseInt(E.css(e), 10) || !1 }, f1 = function (e) { return parseInt(E1.css(e), 10) || !1 }; $.fn.tinyDraggable = function (e) { var a = $.extend({ handle: 0, exclude: 0 }, e); return this.each(function () { var r, i, o = $(this); (a.handle ? $(a.handle, o) : o).on({ mousedown: function (e) { var t; a.exclude && ~$.inArray(e.target, $(a.exclude, o)) || (e.preventDefault(), t = o.offset(), r = e.pageX - t.left, i = e.pageY - t.top, $(document).on("mousemove.drag", function (e) { o.offset({ top: e.pageY - i, left: e.pageX - r }) })) }, mouseup: function (e) { $(document).off("mousemove.drag") } }) }) }, $.fn.jqm = function (e) { var t = { overlay: 50, closeoverlay: !0, overlayClass: "jqmOverlay", closeClass: "jqmClose", trigger: ".jqModal", ajax: F, ajaxText: "", target: F, modal: F, toTop: F, onShow: F, onHide: F, onLoad: F }; return this.each(function () { return this._jqm ? H[this._jqm].c = $.extend({}, H[this._jqm].c, e) : (s++, this._jqm = s, H[s] = { c: $.extend(t, $.jqm.params, e), a: F, w: $(this).addClass("jqmID" + s), s: s }, void (t.trigger && $(this).jqmAddTrigger(t.trigger))) }) }, $.fn.jqmAddClose = function (e) { return hs(this, e, "jqmHide") }, $.fn.jqmAddTrigger = function (e) { return hs(this, e, "jqmShow") }, $.fn.jqmShow = function (e) { return this.each(function () { $.jqm.open(this._jqm, e) }) }, $.fn.jqmHide = function (e) { return this.each(function () { $.jqm.close(this._jqm, e) }) }, $.jqm = { hash: {}, open: function (t, r) { var i = H[t], o = i.c, a = "." + o.closeClass, n = 0 < (n = parseInt(i.w.css("z-index"))) ? n : 3e3, l = $("<div></div>").css({ height: "100%", width: "100%", position: "fixed", left: 0, top: 0, "z-index": n - 1, opacity: o.overlay / 100 }); return i.a || (i.t = r, i.a = !0, i.w.css("z-index", n), o.modal ? (A[0] || setTimeout(function () { new L("bind") }, 1), A.push(t)) : 0 < o.overlay ? o.closeoverlay && i.w.jqmAddClose(l) : l = F, i.o = l ? l.addClass(o.overlayClass).prependTo("body") : F, o.ajax ? (t = o.target || i.w, l = o.ajax, t = "string" == typeof t ? $(t, i.w) : $(t), l = "@" === l.substr(0, 1) ? $(r).attr(l.substring(1)) : l, t.html(o.ajaxText).load(l, function () { o.onLoad && o.onLoad.call(this, i), a && i.w.jqmAddClose($(a, i.w)), e(i) })) : a && i.w.jqmAddClose($(a, i.w)), o.toTop && i.o && i.w.before('<span id="jqmP' + i.w[0]._jqm + '"></span>').insertAfter(i.o), o.onShow ? o.onShow(i) : i.w.show(), e(i)), F }, close: function (e) { e = H[e]; return e.a && (e.a = F, A[0] && (A.pop(), A[0] || new L("unbind")), e.c.toTop && e.o && $("#jqmP" + e.w[0]._jqm).after(e.w).remove(), e.c.onHide ? e.c.onHide(e) : (e.w.hide(), e.o && e.o.remove())), F }, params: {} }; var s = 0, H = $.jqm.hash, A = [], F = !1, e = function (e) { void 0 === e.c.focusField && (e.c.focusField = 0), 0 <= e.c.focusField && f(e) }, f = function (e) { try { $(":input:visible", e.w)[parseInt(e.c.focusField, 10)].focus() } catch (e) { } }, L = function (e) { $(document)[e]("keypress", m)[e]("keydown", m)[e]("mousedown", m) }, m = function (r) { var e = H[A[A.length - 1]], i = !$(r.target).parents(".jqmID" + e.s)[0]; return i && $(".jqmID" + e.s).each(function () { var e = $(this), t = e.offset(); if (t.top <= r.pageY && r.pageY <= t.top + e.height() && t.left <= r.pageX && r.pageX <= t.left + e.width()) return i = !1 }), !i }, hs = function (e, t, r) { return e.each(function () { var e = this._jqm; $(t).each(function () { this[r] || (this[r] = [], $(this).click(function () { for (var e in { jqmShow: 1, jqmHide: 1 }) for (var t in this[e]) H[this[e][t]] && H[this[e][t]].w[e](this); return F })), this[r].push(e) }) }) }; $.fmatter = {}, $.extend($.fmatter, { isBoolean: function (e) { return "boolean" == typeof e }, isObject: function (e) { return e && ("object" == typeof e || $.isFunction(e)) || !1 }, isString: function (e) { return "string" == typeof e }, isNumber: function (e) { return "number" == typeof e && isFinite(e) }, isValue: function (e) { return this.isObject(e) || this.isString(e) || this.isNumber(e) || this.isBoolean(e) }, isEmpty: function (e) { return !(!this.isString(e) && this.isValue(e)) && (!this.isValue(e) || "" === (e = $.trim(e).replace(/\&nbsp\;/gi, "").replace(/\&#160\;/gi, ""))) } }), $.fn.fmatter = function (e, t, r, i, o) { var a = t; r = $.extend({}, $.jgrid.getRegional(this, "formatter"), r); try { a = $.fn.fmatter[e].call(this, t, r, i, o) } catch (e) { } return a }, $.fmatter.util = { NumberFormat: function (e, t) { if ($.fmatter.isNumber(e) || (e *= 1), $.fmatter.isNumber(e)) { var r = e < 0, i = String(e), o = t.decimalSeparator || "."; if ($.fmatter.isNumber(t.decimalPlaces)) { var a = t.decimalPlaces, n = (i = String(Number(Math.round(e + "e" + a) + "e-" + a))).lastIndexOf("."); if (0 < a) for (n < 0 ? n = (i += o).length - 1 : "." !== o && (i = i.replace(".", o)); i.length - 1 - n < a;)i += "0" } if (t.thousandsSeparator) { var l = t.thousandsSeparator; n = -1 < (n = i.lastIndexOf(o)) ? n : i.length; for (var s = i.substring(n), d = -1, p = n; 0 < p; p--)++d % 3 == 0 && p !== n && (!r || 1 < p) && (s = l + s), s = i.charAt(p - 1) + s; i = s } return i = t.prefix ? t.prefix + i : i, i = t.suffix ? i + t.suffix : i } return e } }, $.fn.fmatter.defaultFormat = function (e, t) { return $.fmatter.isValue(e) && "" !== e ? e : t.defaultValue || "&#160;" }, $.fn.fmatter.email = function (e, t) { return $.fmatter.isEmpty(e) ? $.fn.fmatter.defaultFormat(e, t) : '<a href="mailto:' + e + '">' + e + "</a>" }, $.fn.fmatter.checkbox = function (e, t) { var r = $.extend({}, t.checkbox); return void 0 !== t.colModel && void 0 !== t.colModel.formatoptions && (r = $.extend({}, r, t.colModel.formatoptions)), t = !0 === r.disabled ? 'disabled="disabled"' : "", !$.fmatter.isEmpty(e) && void 0 !== e || (e = $.fn.fmatter.defaultFormat(e, r)), '<input type="checkbox" ' + ((e = ((e = String(e)) + "").toLowerCase()).search(/(false|f|0|no|n|off|undefined)/i) < 0 ? " checked='checked' " : "") + ' value="' + e + '" offval="no" ' + t + "/>" }, $.fn.fmatter.link = function (e, t) { var r = { target: t.target }, i = ""; return void 0 !== t.colModel && void 0 !== t.colModel.formatoptions && (r = $.extend({}, r, t.colModel.formatoptions)), r.target && (i = "target=" + r.target), $.fmatter.isEmpty(e) ? $.fn.fmatter.defaultFormat(e, t) : "<a " + i + ' href="' + e + '">' + e + "</a>" }, $.fn.fmatter.showlink = function (e, t) { var r = { baseLinkUrl: t.baseLinkUrl, showAction: t.showAction, addParam: t.addParam || "", target: t.target, idName: t.idName }, i = ""; return void 0 !== t.colModel && void 0 !== t.colModel.formatoptions && (r = $.extend({}, r, t.colModel.formatoptions)), r.target && (i = "target=" + r.target), r = r.baseLinkUrl + r.showAction + "?" + r.idName + "=" + t.rowId + r.addParam, $.fmatter.isString(e) || $.fmatter.isNumber(e) ? "<a " + i + ' href="' + r + '">' + e + "</a>" : $.fn.fmatter.defaultFormat(e, t) }, $.fn.fmatter.integer = function (e, t) { var r = $.extend({}, t.integer); return void 0 !== t.colModel && void 0 !== t.colModel.formatoptions && (r = $.extend({}, r, t.colModel.formatoptions)), $.fmatter.isEmpty(e) ? r.defaultValue : $.fmatter.util.NumberFormat(e, r) }, $.fn.fmatter.number = function (e, t) { var r = $.extend({}, t.number); return void 0 !== t.colModel && void 0 !== t.colModel.formatoptions && (r = $.extend({}, r, t.colModel.formatoptions)), $.fmatter.isEmpty(e) ? r.defaultValue : $.fmatter.util.NumberFormat(e, r) }, $.fn.fmatter.currency = function (e, t) { var r = $.extend({}, t.currency); return void 0 !== t.colModel && void 0 !== t.colModel.formatoptions && (r = $.extend({}, r, t.colModel.formatoptions)), $.fmatter.isEmpty(e) ? r.defaultValue : $.fmatter.util.NumberFormat(e, r) }, $.fn.fmatter.date = function (e, t, r, i) { var o = $.extend({}, t.date); return void 0 !== t.colModel && void 0 !== t.colModel.formatoptions && (o = $.extend({}, o, t.colModel.formatoptions)), !o.reformatAfterEdit && "edit" === i || $.fmatter.isEmpty(e) ? $.fn.fmatter.defaultFormat(e, t) : $.jgrid.parseDate.call(this, o.srcformat, e, o.newformat, o) }, $.fn.fmatter.select = function (e, t) { e = String(e); var r, i, o = !1, a = []; if (void 0 !== t.colModel.formatoptions ? (o = t.colModel.formatoptions.value, r = void 0 === t.colModel.formatoptions.separator ? ":" : t.colModel.formatoptions.separator, i = void 0 === t.colModel.formatoptions.delimiter ? ";" : t.colModel.formatoptions.delimiter) : void 0 !== t.colModel.editoptions && (o = t.colModel.editoptions.value, r = void 0 === t.colModel.editoptions.separator ? ":" : t.colModel.editoptions.separator, i = void 0 === t.colModel.editoptions.delimiter ? ";" : t.colModel.editoptions.delimiter), o) { var n, l = !0 == (null != t.colModel.editoptions && !0 === t.colModel.editoptions.multiple), s = []; if (l && (s = e.split(","), s = $.map(s, function (e) { return $.trim(e) })), $.fmatter.isString(o)) { for (var d = o.split(i), p = 0, c = 0; c < d.length; c++)if (2 < (n = d[c].split(r)).length && (n[1] = $.map(n, function (e, t) { if (0 < t) return e }).join(r)), l) -1 < $.inArray(n[0], s) && (a[p] = n[1], p++); else if ($.trim(n[0]) === $.trim(e)) { a[0] = n[1]; break } } else $.fmatter.isObject(o) && (l ? a = $.map(s, function (e) { return o[e] }) : a[0] = o[e] || "") } return "" === (e = a.join(", ")) ? $.fn.fmatter.defaultFormat(e, t) : e }, $.fn.fmatter.rowactions = function (e) { function t(e) { $.isFunction(d.afterRestore) && d.afterRestore.call(n, e), s.find("div.ui-inline-edit,div.ui-inline-del").show(), s.find("div.ui-inline-save,div.ui-inline-cancel").hide() } var r = $(this).closest("tr.jqgrow"), i = r.attr("id"), o = $(this).closest("table.ui-jqgrid-btable").attr("id").replace(/_frozen([^_]*)$/, "$1"), a = $("#" + o), n = a[0], l = n.p, o = l.colModel[$.jgrid.getCellIndex(this)], s = o.frozen ? $("tr#" + i + " td:eq(" + $.jgrid.getCellIndex(this) + ") > div", a) : $(this).parent(), d = { extraparam: {} }; void 0 !== o.formatoptions && (o = $.extend(!0, {}, o.formatoptions), d = $.extend(d, o)), void 0 !== l.editOptions && (d.editOptions = l.editOptions), void 0 !== l.delOptions && (d.delOptions = l.delOptions), r.hasClass("jqgrid-new-row") && (d.extraparam[l.prmNames.oper] = l.prmNames.addoper); var p = { keys: d.keys, oneditfunc: d.onEdit, successfunc: d.onSuccess, url: d.url, extraparam: d.extraparam, aftersavefunc: function (e, t) { $.isFunction(d.afterSave) && d.afterSave.call(n, e, t), s.find("div.ui-inline-edit,div.ui-inline-del").show(), s.find("div.ui-inline-save,div.ui-inline-cancel").hide() }, errorfunc: d.onError, afterrestorefunc: t, restoreAfterError: d.restoreAfterError, mtype: d.mtype }; switch (e) { case "edit": a.jqGrid("editRow", i, p), s.find("div.ui-inline-edit,div.ui-inline-del").hide(), s.find("div.ui-inline-save,div.ui-inline-cancel").show(), a.triggerHandler("jqGridAfterGridComplete"); break; case "save": a.jqGrid("saveRow", i, p) && (s.find("div.ui-inline-edit,div.ui-inline-del").show(), s.find("div.ui-inline-save,div.ui-inline-cancel").hide(), a.triggerHandler("jqGridAfterGridComplete")); break; case "cancel": a.jqGrid("restoreRow", i, t), s.find("div.ui-inline-edit,div.ui-inline-del").show(), s.find("div.ui-inline-save,div.ui-inline-cancel").hide(), a.triggerHandler("jqGridAfterGridComplete"); break; case "del": a.jqGrid("delGridRow", i, d.delOptions); break; case "formedit": a.jqGrid("setSelection", i), a.jqGrid("editGridRow", i, d.editOptions) } }, $.fn.fmatter.actions = function (e, t) { var r, i = { keys: !1, editbutton: !0, delbutton: !0, editformbutton: !1 }, o = t.rowId, a = "", n = $.jgrid.getRegional(this, "nav"), l = $.jgrid.styleUI[t.styleUI || "jQueryUI"].fmatter, s = $.jgrid.styleUI[t.styleUI || "jQueryUI"].common; if (void 0 !== t.colModel.formatoptions && (i = $.extend(i, t.colModel.formatoptions)), void 0 === o || $.fmatter.isEmpty(o)) return ""; t = "onmouseover=jQuery(this).addClass('" + s.hover + "'); onmouseout=jQuery(this).removeClass('" + s.hover + "');  "; return i.editformbutton ? (r = "id='jEditButton_" + o + "' onclick=jQuery.fn.fmatter.rowactions.call(this,'formedit'); " + t, a += "<div title='" + n.edittitle + "' style='float:left;cursor:pointer;' class='ui-pg-div ui-inline-edit' " + r + "><span class='" + s.icon_base + " " + l.icon_edit + "'></span></div>") : i.editbutton && (r = "id='jEditButton_" + o + "' onclick=jQuery.fn.fmatter.rowactions.call(this,'edit'); " + t, a += "<div title='" + n.edittitle + "' style='float:left;cursor:pointer;' class='ui-pg-div ui-inline-edit' " + r + "><span class='" + s.icon_base + " " + l.icon_edit + "'></span></div>"), i.delbutton && (r = "id='jDeleteButton_" + o + "' onclick=jQuery.fn.fmatter.rowactions.call(this,'del'); " + t, a += "<div title='" + n.deltitle + "' style='float:left;' class='ui-pg-div ui-inline-del' " + r + "><span class='" + s.icon_base + " " + l.icon_del + "'></span></div>"), r = "id='jSaveButton_" + o + "' onclick=jQuery.fn.fmatter.rowactions.call(this,'save'); " + t, a += "<div title='" + n.savetitle + "' style='float:left;display:none' class='ui-pg-div ui-inline-save' " + r + "><span class='" + s.icon_base + " " + l.icon_save + "'></span></div>", r = "id='jCancelButton_" + o + "' onclick=jQuery.fn.fmatter.rowactions.call(this,'cancel'); " + t, "<div style='margin-left:8px;'>" + (a += "<div title='" + n.canceltitle + "' style='float:left;display:none;' class='ui-pg-div ui-inline-cancel' " + r + "><span class='" + s.icon_base + " " + l.icon_cancel + "'></span></div>") + "</div>" }, $.unformat = function (e, t, r, i) { var o, a = t.colModel.formatter, n = t.colModel.formatoptions || {}, l = /([\.\*\_\'\(\)\{\}\+\?\\])/g, s = t.colModel.unformat || $.fn.fmatter[a] && $.fn.fmatter[a].unformat; if (void 0 !== s && $.isFunction(s)) c = s.call(this, $(e).text(), t, e); else if (void 0 !== a && $.fmatter.isString(a)) { var d = $.jgrid.getRegional(this, "formatter") || {}; switch (a) { case "integer": o = (n = $.extend({}, d.integer, n)).thousandsSeparator.replace(l, "\\$1"), p = new RegExp(o, "g"), c = $(e).text().replace(p, ""); break; case "number": o = (n = $.extend({}, d.number, n)).thousandsSeparator.replace(l, "\\$1"), p = new RegExp(o, "g"), c = $(e).text().replace(p, "").replace(n.decimalSeparator, "."); break; case "currency": o = (n = $.extend({}, d.currency, n)).thousandsSeparator.replace(l, "\\$1"), p = new RegExp(o, "g"), c = $(e).text(), n.prefix && n.prefix.length && (c = c.substr(n.prefix.length)), n.suffix && n.suffix.length && (c = c.substr(0, c.length - n.suffix.length)), c = c.replace(p, "").replace(n.decimalSeparator, "."); break; case "checkbox": var p = t.colModel.editoptions ? t.colModel.editoptions.value.split(":") : ["Yes", "No"], c = $("input", e).is(":checked") ? p[0] : p[1]; break; case "select": c = $.unformat.select(e, t, r, i); break; case "actions": return ""; default: c = $(e).text() } } return void 0 !== c ? c : !0 === i ? $(e).text() : $.jgrid.htmlDecode($(e).html()) }, $.unformat.select = function (e, t, r, i) { var o = [], a = $(e).text(); if (!0 === i) return a; var n = $.extend({}, void 0 !== t.colModel.formatoptions ? t.colModel.formatoptions : t.colModel.editoptions), l = void 0 === n.separator ? ":" : n.separator, t = void 0 === n.delimiter ? ";" : n.delimiter; if (n.value) { var s, d = n.value, p = !0 === n.multiple, c = []; if (p && (c = a.split(","), c = $.map(c, function (e) { return $.trim(e) })), $.fmatter.isString(d)) { for (var u = d.split(t), h = 0, g = 0; g < u.length; g++)if (2 < (s = u[g].split(l)).length && (s[1] = $.map(s, function (e, t) { if (0 < t) return e }).join(l)), n.decodeValue && !0 === n.decodeValue && (s[1] = $.jgrid.htmlDecode(s[1])), p) -1 < $.inArray($.trim(s[1]), c) && (o[h] = s[0], h++); else if ($.trim(s[1]) === $.trim(a)) { o[0] = s[0]; break } } else ($.fmatter.isObject(d) || $.isArray(d)) && (p || (c[0] = a), o = $.map(c, function (r) { var i; if ($.each(d, function (e, t) { if (t === r) return i = e, !1 }), void 0 !== i) return i })); return o.join(", ") } return a || "" }, $.unformat.date = function (e, t) { var r = $.jgrid.getRegional(this, "formatter.date") || {}; return void 0 !== t.formatoptions && (r = $.extend({}, r, t.formatoptions)), $.fmatter.isEmpty(e) ? $.fn.fmatter.defaultFormat(e, t) : $.jgrid.parseDate.call(this, r.newformat, e, r.srcformat, r) }; var dragging, placeholders = $(); $.fn.html5sortable = function (a) { var e = String(a); return a = $.extend({ connectWith: !1 }, a), this.each(function () { var t, r, i; if (/^enable|disable|destroy$/.test(e)) return t = $(this).children($(this).data("items")).attr("draggable", "enable" === e), void ("destroy" === e && t.add(this).removeData("connectWith items").off("dragstart.h5s dragend.h5s selectstart.h5s dragover.h5s dragenter.h5s drop.h5s")); t = $(this).children(a.items); var o = $("<" + (/^ul|ol$/i.test(this.tagName) ? "li" : /^tbody$/i.test(this.tagName) ? "tr" : "div") + ' class="sortable-placeholder ' + a.placeholderClass + '">').html("&nbsp;"); t.find(a.handle).mousedown(function () { r = !0 }).mouseup(function () { r = !1 }), $(this).data("items", a.items), placeholders = placeholders.add(o), a.connectWith && $(a.connectWith).add(this).data("connectWith", a.connectWith), t.attr("draggable", "true").on("dragstart.h5s", function (e) { if (a.handle && !r) return !1; r = !1; e = e.originalEvent.dataTransfer; e.effectAllowed = "move", e.setData("Text", "dummy"), i = (dragging = $(this)).addClass("sortable-dragging").index() }).on("dragend.h5s", function () { dragging && (dragging.removeClass("sortable-dragging").show(), placeholders.detach(), i !== dragging.index() && dragging.parent().trigger("sortupdate", { item: dragging, startindex: i, endindex: dragging.index() }), dragging = null) }).not("a[href], img").on("selectstart.h5s", function () { return this.dragDrop && this.dragDrop(), !1 }).end().add([this, o]).on("dragover.h5s dragenter.h5s drop.h5s", function (e) { return !t.is(dragging) && a.connectWith !== $(dragging).parent().data("connectWith") || ("drop" === e.type ? (e.stopPropagation(), placeholders.filter(":visible").after(dragging), dragging.trigger("dragend.h5s")) : (e.preventDefault(), e.originalEvent.dataTransfer.dropEffect = "move", t.is(this) ? (a.forcePlaceholderSize && o.height(dragging.outerHeight()), dragging.hide(), $(this)[o.index() < $(this).index() ? "after" : "before"](o), placeholders.not(o).detach()) : placeholders.is(this) || $(this).children(a.items).length || (placeholders.detach(), $(this).append(o))), !1) }) }) }, $.extend($.jgrid, { stringify: function (e) { return JSON.stringify(e, function (e, t) { return "function" == typeof t ? t.toString() : t }) }, parseFunc: function (str) { return JSON.parse(str, function (key, value) { if ("string" != typeof value || -1 === value.indexOf("function")) return value; var sv = value.split(" "); return sv[0] = $.trim(sv[0].toLowerCase()), 0 === sv[0].indexOf("function") && "}" === value.trim().slice(-1) ? eval("(" + value + ")") : value }) }, encode: function (e) { return String(e).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;") }, jsonToXML: function (e, t) { function s(e, t) { return "#text" === e ? d.encode ? p.encode(t) : t : "function" == typeof t ? "<" + e + "><![CDATA[" + t + "]]></" + e + ">\n" : "" === t ? "<" + e + ">__EMPTY_STRING_</" + e + ">\n" : "<" + e + ">" + (d.encode ? p.encode(t) : t) + "</" + e + ">\n" } var d = $.extend({ xmlDecl: '<?xml version="1.0" encoding="UTF-8" ?>\n', attr_prefix: "-", encode: !0 }, t || {}), p = this, c = function (e, t) { for (var r = [], i = 0; i < t.length; i++) { var o = t[i]; void 0 === o || null == o ? r[r.length] = "<" + e + " />" : "object" == typeof o && o.constructor == Array ? r[r.length] = c(e, o) : r[r.length] = ("object" == typeof o ? u : s)(e, o) } return r.length || (r[0] = "<" + e + ">__EMPTY_ARRAY_</" + e + ">\n"), r.join("") }, u = function (e, t) { var r, i, o = [], a = []; for (r in t) t.hasOwnProperty(r) && (i = t[r], r.charAt(0) !== d.attr_prefix ? null == i ? o[o.length] = "<" + r + " />" : "object" == typeof i && i.constructor === Array ? o[o.length] = c(r, i) : o[o.length] = ("object" == typeof i ? u : s)(r, i) : a[a.length] = " " + r.substring(1) + '="' + (d.encode ? p.encode(i) : i) + '"'); var n = a.join(""), l = o.join(""); return null == e || (l = 0 < o.length ? l.match(/\n/) ? "<" + e + n + ">\n" + l + "</" + e + ">\n" : "<" + e + n + ">" + l + "</" + e + ">\n" : "<" + e + n + " />\n"), l }, e = u(null, e); return d.xmlDecl + e }, xmlToJSON: function (root, options) { var o = $.extend({ force_array: [], attr_prefix: "-" }, options || {}); if (root) { var __force_array = {}; if (o.force_array) for (var i = 0; i < o.force_array.length; i++)__force_array[o.force_array[i]] = 1; "string" == typeof root && (root = $.parseXML(root)), root.documentElement && (root = root.documentElement); var addNode = function (hash, key, cnts, val) { if ("string" == typeof val) if (-1 !== val.indexOf("function")) val = eval("(" + val + ")"); else switch (val) { case "__EMPTY_ARRAY_": val = []; break; case "__EMPTY_STRING_": val = ""; break; case "false": val = !1; break; case "true": val = !0 }__force_array[key] ? (1 === cnts && (hash[key] = []), hash[key][hash[key].length] = val) : 1 === cnts ? hash[key] = val : 2 === cnts ? hash[key] = [hash[key], val] : hash[key][hash[key].length] = val }, parseElement = function (e) { if (7 !== e.nodeType) { if (3 === e.nodeType || 4 === e.nodeType) return null == e.nodeValue.match(/[^\x00-\x20]/) ? void 0 : e.nodeValue; var t, r, i, a = {}; if (e.attributes && e.attributes.length) for (t = {}, l = 0; l < e.attributes.length; l++)"string" == typeof (r = e.attributes[l].nodeName) && (i = e.attributes[l].nodeValue) && (void 0 === a[r = o.attr_prefix + r] && (a[r] = 0), a[r]++, addNode(t, r, a[r], i)); if (e.childNodes && e.childNodes.length) { for (var n = t ? !1 : !0, l = 0; l < e.childNodes.length && n; l++) { var s = e.childNodes[l].nodeType; 3 !== s && 4 !== s && (n = !1) } if (n) for (t = t || "", l = 0; l < e.childNodes.length; l++)t += e.childNodes[l].nodeValue; else for (t = t || {}, l = 0; l < e.childNodes.length; l++)"string" == typeof (r = e.childNodes[l].nodeName) && (i = parseElement(e.childNodes[l])) && (void 0 === a[r] && (a[r] = 0), a[r]++, addNode(t, r, a[r], i)) } return t } }, json = parseElement(root), tmp; return __force_array[root.nodeName] && (json = [json]), 11 !== root.nodeType && (tmp = {}, tmp[root.nodeName] = json, json = tmp), json } }, saveAs: function (e, t, r) { r = $.extend(!0, { type: "plain/text;charset=utf-8" }, r || {}); var i, o, a, n = []; t = null == t || "" === t ? "jqGridFile.txt" : t, $.isArray(e) ? n = e : n[0] = e; try { i = new File(n, t, r) } catch (e) { i = new Blob(n, r) } window.navigator && window.navigator.msSaveOrOpenBlob ? window.navigator.msSaveOrOpenBlob(i, t) : (o = URL.createObjectURL(i), (a = document.createElement("a")).href = o, a.download = t, document.body.appendChild(a), a.click(), setTimeout(function () { document.body.removeChild(a), window.URL.revokeObjectURL(o) }, 0)) } }), $.jgrid = $.jgrid || {}, $.extend($.jgrid, { formatCell: function (e, t, r, i, o, a) { return void 0 !== i.formatter ? (a = { rowId: "", colModel: i, gid: o.p.id, pos: t, styleUI: "", isExported: !0, exporttype: a }, $.isFunction(i.formatter) ? i.formatter.call(o, e, a, r) : $.fmatter ? $.fn.fmatter.call(o, i.formatter, e, a, r) : e) : e }, formatCellCsv: function (t, e) { t = null == t ? "" : String(t); try { t = $.jgrid.stripHtml(t.replace(e._regexsep, e.separatorReplace).replace(/\r\n/g, e.replaceNewLine).replace(/\n/g, e.replaceNewLine)) } catch (e) { t = "" } return e.escquote && (t = t.replace(e._regexquot, e.escquote + e.quote)), -1 !== t.indexOf(e.separator) && -1 !== t.indexOf(e.qoute) || (t = e.quote + t + e.quote), t }, excelCellPos: function (e) { for (var t = "A".charCodeAt(0), r = "Z".charCodeAt(0) - t + 1, i = ""; 0 <= e;)i = String.fromCharCode(e % r + t) + i, e = Math.floor(e / r) - 1; return i }, makeNode: function (e, t, r) { var i = e.createElement(t); return r && (r.attr && $(i).attr(r.attr), r.children && $.each(r.children, function (e, t) { i.appendChild(t) }), r.hasOwnProperty("text") && i.appendChild(e.createTextNode(r.text))), i }, xmlToZip: function (o, e) { var a, n, l, s, d, p = this, c = new XMLSerializer, u = -1 === c.serializeToString($.parseXML($.jgrid.excelStrings["xl/worksheets/sheet1.xml"])).indexOf("xmlns:r"), h = []; $.each(e, function (e, t) { if ($.isPlainObject(t)) d = o.folder(e), p.xmlToZip(d, t); else { if (u) { for (a = t.childNodes[0], n = a.attributes.length - 1; 0 <= n; n--) { var r = a.attributes[n].nodeName, i = a.attributes[n].nodeValue; -1 !== r.indexOf(":") && (h.push({ name: r, value: i }), a.removeAttribute(r)) } for (n = 0, l = h.length; n < l; n++)(s = t.createAttribute(h[n].name.replace(":", "_dt_b_namespace_token_"))).value = h[n].value, a.setAttributeNode(s) } d = c.serializeToString(t), u && (-1 === d.indexOf("<?xml") && (d = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' + d), d = d.replace(/_dt_b_namespace_token_/g, ":")), d = d.replace(/<row xmlns="" /g, "<row ").replace(/<cols xmlns="">/g, "<cols>").replace(/<mergeCells xmlns="" /g, "<mergeCells ").replace(/<numFmt xmlns="" /g, "<numFmt ").replace(/<xf xmlns="" /g, "<xf "), o.file(e, d) } }) }, excelStrings: { "_rels/.rels": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>', "xl/_rels/workbook.xml.rels": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>', "[Content_Types].xml": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml" /><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" /><Default Extension="jpeg" ContentType="image/jpeg" /><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml" /><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" /><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml" /></Types>', "xl/workbook.xml": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><fileVersion appName="xl" lastEdited="5" lowestEdited="5" rupBuild="24816"/><workbookPr showInkAnnotation="0" autoCompressPictures="0"/><bookViews><workbookView xWindow="0" yWindow="0" windowWidth="25600" windowHeight="19020" tabRatio="500"/></bookViews><sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets></workbook>', "xl/worksheets/sheet1.xml": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"><sheetData/></worksheet>', "xl/styles.xml": '<?xml version="1.0" encoding="UTF-8"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"><numFmts count="7"><numFmt numFmtId="164" formatCode="#,##0.00_- [$$-45C]"/><numFmt numFmtId="165" formatCode="&quot;�&quot;#,##0.00"/><numFmt numFmtId="166" formatCode="[$�-2] #,##0.00"/><numFmt numFmtId="167" formatCode="0.0%"/><numFmt numFmtId="168" formatCode="#,##0;(#,##0)"/><numFmt numFmtId="169" formatCode="#,##0.00;(#,##0.00)"/><numFmt numFmtId="170" formatCode="yyyy/mm/dd;@"/></numFmts><fonts count="5" x14ac:knownFonts="1"><font><sz val="11" /><name val="Calibri" /></font><font><sz val="11" /><name val="Calibri" /><color rgb="FFFFFFFF" /></font><font><sz val="11" /><name val="Calibri" /><b /></font><font><sz val="11" /><name val="Calibri" /><i /></font><font><sz val="11" /><name val="Calibri" /><u /></font></fonts><fills count="6"><fill><patternFill patternType="none" /></fill><fill/><fill><patternFill patternType="solid"><fgColor rgb="FFD9D9D9" /><bgColor indexed="64" /></patternFill></fill><fill><patternFill patternType="solid"><fgColor rgb="FFD99795" /><bgColor indexed="64" /></patternFill></fill><fill><patternFill patternType="solid"><fgColor rgb="ffc6efce" /><bgColor indexed="64" /></patternFill></fill><fill><patternFill patternType="solid"><fgColor rgb="ffc6cfef" /><bgColor indexed="64" /></patternFill></fill></fills><borders count="2"><border><left /><right /><top /><bottom /><diagonal /></border><border diagonalUp="false" diagonalDown="false"><left style="thin"><color auto="1" /></left><right style="thin"><color auto="1" /></right><top style="thin"><color auto="1" /></top><bottom style="thin"><color auto="1" /></bottom><diagonal /></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" /></cellStyleXfs><cellXfs count="67"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1"><alignment horizontal="left"/></xf><xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1"><alignment horizontal="center"/></xf><xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1"><alignment horizontal="right"/></xf><xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1"><alignment horizontal="fill"/></xf><xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1"><alignment textRotation="90"/></xf><xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1"><alignment wrapText="1"/></xf><xf numFmtId="9"   fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="164" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="165" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="166" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="167" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="168" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="169" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="3" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="4" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="1" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="2" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="170" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/></cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0" /></cellStyles><dxfs count="0" /><tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleMedium4" /></styleSheet>' }, excelParsers: [{ match: /^\-?\d+\.\d%$/, style: 60, fmt: function (e) { return e / 100 } }, { match: /^\-?\d+\.?\d*%$/, style: 56, fmt: function (e) { return e / 100 } }, { match: /^\-?\$[\d,]+.?\d*$/, style: 57 }, { match: /^\-?�[\d,]+.?\d*$/, style: 58 }, { match: /^\-?�[\d,]+.?\d*$/, style: 59 }, { match: /^\-?\d+$/, style: 65 }, { match: /^\-?\d+\.\d{2}$/, style: 66 }, { match: /^\([\d,]+\)$/, style: 61, fmt: function (e) { return -1 * e.replace(/[\(\)]/g, "") } }, { match: /^\([\d,]+\.\d{2}\)$/, style: 62, fmt: function (e) { return -1 * e.replace(/[\(\)]/g, "") } }, { match: /^\-?[\d,]+$/, style: 63 }, { match: /^\-?[\d,]+\.\d{2}$/, style: 64 }, { match: /^\d{4}\-\d{2}\-\d{2}$/, style: 67 }, { match: /(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/gi, style: 4 }] }), $.jgrid.extend({ exportToCsv: function (C) { C = $.extend(!0, { separator: ",", separatorReplace: " ", quote: '"', escquote: '"', newLine: "\r\n", replaceNewLine: " ", includeCaption: !0, includeLabels: !0, includeGroupHeader: !0, includeFooter: !0, includeHeader: !0, fileName: "jqGridExport.csv", mimetype: "text/csv;charset=utf-8", returnAsString: !1, onBeforeExport: null, treeindent: " ", loadIndicator: !0 }, C || {}); var F = ""; if (this.each(function () { C._regexsep = new RegExp(C.separator, "g"), C._regexquot = new RegExp(C.quote, "g"); var e, t, _ = this, r = _.p.treeGrid ? $(_).jqGrid("getRowData", null, !0, C.treeindent) : _.addLocalData(!0), i = r.length, o = _.p.colModel, a = o.length, n = _.p.colNames, l = 0, s = "", d = "", p = "", c = "", u = "", h = [], g = ""; $.isFunction(C.loadIndicator) ? C.loadIndicator("show") : C.loadIndicator && $(_).jqGrid("progressBar", { method: "show", loadtype: _.p.loadui, htmlcontent: $.jgrid.getRegional(_, "defaults.loadtext") }); var f = []; if ($.each(o, function (e, t) { t._expcol = !0, void 0 === t.exportcol ? t.hidden && (t._expcol = !1) : t._expcol = t.exportcol, "cb" !== t.name && "rn" !== t.name && "subgrid" !== t.name || (t._expcol = !1), t._expcol && (h.push($.jgrid.formatCellCsv(n[e], C)), f.push(t.name)) }), C.includeLabels && (u = h.join(C.separator) + C.newLine), C.collen = h.length, _.p.grouping) { var m = !!_.p.groupingView._locgr; _.p.groupingView._locgr = !1, s += function (p, c) { var u = "", h = _.p.groupingView, g = [], f = h.groupField.length, m = _.p.colModel, v = m.length, b = 0; function j(e, t, r, i) { for (var o, a, n = function (e, t, r) { var i, o = !1; if (0 === t) o = r[e]; else { var a = r[e].idx; if (0 === a) o = r[e]; else for (i = e; 0 <= i; i--)if (r[i].idx === a - t) { o = r[i]; break } } return o }(e, t, r), l = n.cnt, s = new Array(c.collen), d = 0, p = i; p < v; p++)m[p]._excol && (a = "{0}", $.each(n.summary, function () { if (this.nm === m[p].name) { m[p].summaryTpl && (a = m[p].summaryTpl), "string" == typeof this.st && "avg" === this.st.toLowerCase() && (this.sd && this.vd ? this.v = this.v / this.vd : this.v && 0 < l && (this.v = this.v / l)); try { this.groupCount = n.cnt, this.groupIndex = n.dataIndex, this.groupValue = n.value, o = this.v } catch (e) { o = this.v } return s[d] = $.jgrid.formatCellCsv($.jgrid.stripHtml($.jgrid.template(a, o)), c), !1 } }), d++); return s } $.each(m, function (e, t) { for (var r = 0; r < f; r++)if (h.groupField[r] === t.name) { g[r] = e; break } }); var y, w, x = $.makeArray(h.groupSummary); if (x.reverse(), "local" === _.p.datatype && !_.p.loadonce) { $(_).jqGrid("groupingSetup"); for (var e = $.jgrid.getMethod("groupingPrepare"), t = 0; t < i; t++)e.call($(_), r[t], t) } return $.each(h.groups, function (e, t) { b++; try { y = $.isArray(h.formatDisplayField) && $.isFunction(h.formatDisplayField[t.idx]) ? h.formatDisplayField[t.idx].call(_, t.displayValue, t.value, _.p.colModel[g[t.idx]], t.idx, h) : _.formatter("", t.displayValue, g[t.idx], t.value) } catch (e) { y = t.displayValue } var r, i = ""; if ("string" != typeof (i = $.isFunction(h.groupText[t.idx]) ? h.groupText[t.idx].call(_, y, t.cnt, t.summary) : $.jgrid.template(h.groupText[t.idx], y, t.cnt, t.summary)) && "number" != typeof i && (i = y), (r = "header" === h.groupSummaryPos[t.idx] ? j(e, 0, h.groups, 0) : new Array(c.collen))[0] = $.jgrid.formatCellCsv($.jgrid.stripHtml(i), c), u += r.join(c.separator) + c.newLine, f - 1 === t.idx) { for (var o, a, n, l = h.groups[e + 1], i = t.startRow, s = void 0 !== l ? l.startRow : h.groups[e].startRow + h.groups[e].cnt, d = i; d < s && p[+d]; d++) { for (a = p[+d], o = w = 0; o < m.length; o++)m[o]._expcol && (r[w] = $.jgrid.formatCellCsv($.jgrid.formatCell($.jgrid.getAccessor(a, m[o].name), o, a, m[o], _, "csv"), c), w++); u += r.join(c.separator) + c.newLine } if ("header" !== h.groupSummaryPos[t.idx]) { if (void 0 !== l) { for (n = 0; n < h.groupField.length && l.dataIndex !== h.groupField[n]; n++); b = h.groupField.length - n } for (o = 0; o < b; o++)x[o] && (r = j(e, o, h.groups, 0), u += r.join(c.separator) + c.newLine); b = n } } }), u }(r, C), _.p.groupingView._locgr = m } else for (; l < i;) { for (e = r[l], y = [], b = t = 0; b < a; b++)o[b]._expcol && (y[t] = $.jgrid.formatCellCsv($.jgrid.formatCell($.jgrid.getAccessor(e, o[b].name), b, e, o[b], _, "csv"), C), t++); s += y.join(C.separator) + C.newLine, l++ } if (r = null, y = new Array(C.collen), C.includeCaption && _.p.caption) { for (l = C.collen; --l;)y[l] = ""; y[0] = $.jgrid.formatCellCsv(_.p.caption, C), d += y.join(C.separator) + C.newLine } if (C.includeGroupHeader && $(_).jqGrid("isGroupHeaderOn")) for (var v = _.p.groupHeader, b = 0; b < v.length; b++) { for (var j = v[b].groupHeaders, l = 0, y = [], w = 0; w < f.length; w++) { for (y[l] = "", t = 0; t < j.length; t++)j[t].startColumnName === f[w] && (y[l] = $.jgrid.formatCellCsv(j[t].titleText, C)); l++ } p += y.join(C.separator) + C.newLine } if (C.includeFooter && _.p.footerrow && $(".ui-jqgrid-ftable", this.sDiv).length) { var x = $(_).jqGrid("footerData", "get"); for (b = 0, y = []; b < C.collen;) { var q = f[b]; x.hasOwnProperty(q) && y.push($.jgrid.formatCellCsv($.jgrid.stripHtml(x[q]), C)), b++ } c += y.join(C.separator) + C.newLine } if (C.includeHeader && _.p.headerrow) { var I = $(_).jqGrid("headerData", "get"); for (b = 0, y = []; b < C.collen;) { var D = f[b]; I.hasOwnProperty(D) && y.push($.jgrid.formatCellCsv($.jgrid.stripHtml(I[D]), C)), b++ } g += y.join(C.separator) + C.newLine } F = d + p + u + g + s + c, $.isFunction(C.loadIndicator) ? C.loadIndicator("hide") : C.loadIndicator && $(_).jqGrid("progressBar", { method: "hide", loadtype: _.p.loadui }) }), C.returnAsString) return F; if (-1 !== C.mimetype.toUpperCase().indexOf("UTF-8") && (F = "\ufeff" + F), $.isFunction(C.onBeforeExport) && !(F = C.onBeforeExport(F))) throw "Before export does not return data!"; $.jgrid.saveAs(F, C.fileName, { type: C.mimetype }) }, exportToExcel: function (P) { P = $.extend(!0, { includeLabels: !0, includeGroupHeader: !0, includeFooter: !0, includeHeader: !0, fileName: "jqGridExport.xlsx", mimetype: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", maxlength: 40, onBeforeExport: null, replaceStr: null, treeindent: " ", loadIndicator: !0 }, P || {}), this.each(function () { for (var y = this, e = $.jgrid.excelStrings, g = 0, f = $.parseXML(e["xl/worksheets/sheet1.xml"]), m = f.getElementsByTagName("sheetData")[0], o = $.parseXML(e["xl/styles.xml"]), a = o.getElementsByTagName("numFmts")[0], n = $(a.getElementsByTagName("numFmt")), l = o.getElementsByTagName("cellXfs")[0], t = { _rels: { ".rels": $.parseXML(e["_rels/.rels"]) }, xl: { _rels: { "workbook.xml.rels": $.parseXML(e["xl/_rels/workbook.xml.rels"]) }, "workbook.xml": $.parseXML(e["xl/workbook.xml"]), "styles.xml": o, worksheets: { "sheet1.xml": f } }, "[Content_Types].xml": $.parseXML(e["[Content_Types].xml"]) }, w = y.p.colModel, r = 0, x = { body: y.p.treeGrid ? $(y).jqGrid("getRowData", null, !0, P.treeindent) : y.addLocalData(!0), header: [], footer: [], width: [], map: [], parser: [] }, i = 0, s = w.length; i < s; i++)w[i]._expcol = !0, void 0 === w[i].exportcol ? w[i].hidden && (w[i]._expcol = !1) : w[i]._expcol = w[i].exportcol, "cb" !== w[i].name && "rn" !== w[i].name && "subgrid" !== w[i].name && w[i]._expcol && (x.header[r] = w[i].name, x.width[r] = 5, x.map[r] = i, x.parser[i] = function (e) { var r, i, t; return $.isEmptyObject(e) ? e.excel_parsers = !0 : e.excel_format && !e.excel_style && (i = r = 0, $.each(n, function (e, t) { r++, i = Math.max(i, parseInt($(t).attr("numFmtId"), 10)) }), t = $.jgrid.makeNode(o, "numFmt", { attr: { numFmtId: i + 1, formatCode: e.excel_format } }), a.appendChild(t), $(a).attr("count", r + 1), r = 0, t = $.jgrid.makeNode(o, "xf", { attr: { numFmtId: i + 1 + "", fontId: "0", fillId: "0", borderId: "0", applyFont: "1", applyFill: "1", applyBorder: "1", xfId: "0", applyNumberFormat: "1" } }), l.appendChild(t), r = parseInt($(l).attr("count"), 10), $(l).attr("count", r + 1), e.excel_style = r + 1), e }(w[i].hasOwnProperty("exportoptions") ? w[i].exportoptions : {}), r++); function v(e, t) { return $.jgrid.makeNode(f, "c", { attr: e, children: [$.jgrid.makeNode(f, "v", { text: t })] }) } function b(e, t) { return $.jgrid.makeNode(f, "c", { attr: { t: "inlineStr", r: e }, children: { row: $.jgrid.makeNode(f, "is", { children: { row: $.jgrid.makeNode(f, "t", { text: t }) } }) } }) } var j, _, q = $.isFunction(P.replaceStr) ? P.replaceStr : function (e) { return e.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, "") }, I = function (e, t) { j = g + 1, _ = $.jgrid.makeNode(f, "row", { attr: { r: j } }); for (var r, i, o = 0; o < x.header.length; o++) { var a, n, l = $.jgrid.excelCellPos(o) + "" + j; null == (h = $.isArray(e) && t ? y.p.colNames[x.map[o]] : $.jgrid.getAccessor(e, x.header[o])) && (h = ""), t || (h = $.jgrid.formatCell(h, x.map[o], e, w[x.map[o]], y, "excel")), x.width[o] = Math.max(x.width[o], Math.min(parseInt(h.toString().length, 10), P.maxlength)), a = null; var s = x.parser[x.map[o]]; if (!0 === s.excel_parsers) for (var d = 0, p = $.jgrid.excelParsers.length; d < p; d++) { var c = $.jgrid.excelParsers[d]; if (h.match && !h.match(/^0\d+/) && h.match(c.match)) { var u = h, h = h.replace(/[^\d\.\-]/g, ""); if (c.fmt && (h = c.fmt(h)), 67 === c.style) a = v({ t: "d", r: l, s: c.style }, h); else if (4 === c.style) r = u, i = void 0, (i = document.createElement("div")).innerHTML = r, a = (h = "A" === (i = i.firstChild).nodeName ? [i.href, i.text] : "#text" === i.nodeName && [i.textContent, i.textContent]) ? (r = { t: "str", r: l, s: c.style }, i = 'HYPERLINK("' + h[0] + '","' + h[1] + '")', $.jgrid.makeNode(f, "c", { attr: r, children: [$.jgrid.makeNode(f, "f", { text: i })] })) : b(l, u); else { if ($.inArray(c.style, ["63", "64", "65", "66"]) && 15 < h.toString().length) { a = b(l, u.replace ? q(u) : u), _.appendChild(a); break } a = v({ r: l, s: c.style }, h) } _.appendChild(a); break } } else void 0 === s.excel_format || void 0 === s.excel_style || t || a || (s.replace_format && (h = s.replace_format(h)), a = v({ r: l, s: s.excel_style }, h), _.appendChild(a)); a || (h.match && (n = h.match(/^-?([1-9]\d+)(\.(\d+))?$/)), a = "number" == typeof h && h.toString().length <= 15 || n && n[1].length + (n[2] ? n[3].length : 0) <= 15 ? v({ t: "n", r: l }, h) : b(l, h.replace ? q(h) : h), _.appendChild(a)) } m.appendChild(_), g++ }; if ($.isFunction(P.loadIndicator) ? P.loadIndicator("show") : P.loadIndicator && $(y).jqGrid("progressBar", { method: "show", loadtype: y.p.loadui, htmlcontent: $.jgrid.getRegional(y, "defaults.loadtext") }), $("sheets sheet", t.xl["workbook.xml"]).attr("name", P.sheetName), P.includeGroupHeader && $(y).jqGrid("isGroupHeaderOn")) { for (var d, p = y.p.groupHeader, c = [], u = 0, h = 0; h < p.length; h++) { var D = p[h].groupHeaders, C = {}; for (u++, i = i = 0; i < x.header.length; i++) { C[d = x.header[i]] = ""; for (var F, G, k = 0; k < D.length; k++)D[k].startColumnName === d && (C[d] = D[k].titleText, F = $.jgrid.excelCellPos(i) + u, G = $.jgrid.excelCellPos(i + D[k].numberOfColumns - 1) + u, c.push({ ref: F + ":" + G })) } I(C, !0) } $("row c", f).attr("s", "2"); var S = $.jgrid.makeNode(f, "mergeCells", { attr: { count: c.length } }); for ($("worksheet", f).append(S), r = 0; r < c.length; r++)S.appendChild($.jgrid.makeNode(f, "mergeCell", { attr: c[r] })) } if (P.includeLabels && (I(x.header, !0), $("row:last c", f).attr("s", "2")), P.includeHeader || y.p.headerrow) { var R = $(y).jqGrid("headerData", "get"); for (r in R) R.hasOwnProperty(r) && (R[r] = $.jgrid.stripHtml(R[r])); $.isEmptyObject(R) || (I(R, !0), $("row:last c", f).attr("s", "2")) } if (y.p.grouping) { e = !!y.p.groupingView._locgr; y.p.groupingView._locgr = !1, function (p) { var c = y.p.groupingView, u = [], h = c.groupField.length, g = w.length, f = 0; function m(e, t, r, i) { for (var o, a, n = function (e, t, r) { var i, o = !1; if (0 === t) o = r[e]; else { var a = r[e].idx; if (0 === a) o = r[e]; else for (i = e; 0 <= i; i--)if (r[i].idx === a - t) { o = r[i]; break } } return o }(e, t, r), l = n.cnt, s = v(x.header), d = i; d < g; d++)w[d]._expcol && (a = "{0}", $.each(n.summary, function () { if (this.nm === w[d].name) { w[d].summaryTpl && (a = w[d].summaryTpl), "string" == typeof this.st && "avg" === this.st.toLowerCase() && (this.sd && this.vd ? this.v = this.v / this.vd : this.v && 0 < l && (this.v = this.v / l)); try { this.groupCount = n.cnt, this.groupIndex = n.dataIndex, this.groupValue = n.value, o = this.v } catch (e) { o = this.v } return s[this.nm] = $.jgrid.stripHtml($.jgrid.template(a, o)), !1 } })); return s } function v(e) { for (var t = {}, r = 0; r < e.length; r++)t[e[r]] = ""; return t } $.each(w, function (e, t) { for (var r = 0; r < h; r++)if (c.groupField[r] === t.name) { u[r] = e; break } }); var b, j = $.makeArray(c.groupSummary); if (j.reverse(), "local" === y.p.datatype && !y.p.loadonce) { $(y).jqGrid("groupingSetup"); for (var e = $.jgrid.getMethod("groupingPrepare"), t = 0; t < x.body.length; t++)e.call($(y), x.body[t], t) } $.each(c.groups, function (e, t) { f++; try { b = $.isArray(c.formatDisplayField) && $.isFunction(c.formatDisplayField[t.idx]) ? c.formatDisplayField[t.idx].call(y, t.displayValue, t.value, y.p.colModel[u[t.idx]], t.idx, c) : y.formatter("", t.displayValue, u[t.idx], t.value) } catch (e) { b = t.displayValue } var r, i = ""; if ("string" != typeof (i = $.isFunction(c.groupText[t.idx]) ? c.groupText[t.idx].call(y, b, t.cnt, t.summary) : $.jgrid.template(c.groupText[t.idx], b, t.cnt, t.summary)) && "number" != typeof i && (i = b), (r = "header" === c.groupSummaryPos[t.idx] ? m(e, 0, c.groups, 0) : v(x.header))[Object.keys(r)[0]] = $.jgrid.stripHtml(new Array(5 * t.idx).join(" ") + i), I(r, !1), h - 1 === t.idx) { for (var o, a, n = c.groups[e + 1], i = t.startRow, l = void 0 !== n ? n.startRow : c.groups[e].startRow + c.groups[e].cnt, s = i; s < l && p[+s]; s++) { var d = p[+s]; I(d, !1) } if ("header" !== c.groupSummaryPos[t.idx]) { if (void 0 !== n) { for (a = 0; a < c.groupField.length && n.dataIndex !== c.groupField[a]; a++); f = c.groupField.length - a } for (o = 0; o < f; o++)j[o] && (r = m(e, o, c.groups, 0), I(r, !1)); f = a } } }) }(x.body), y.p.groupingView._locgr = e } else for (var M = 0, N = x.body.length; M < N; M++)I(x.body[M], !1); if (P.includeFooter || y.p.footerrow) { for (r in x.footer = $(y).jqGrid("footerData", "get"), x.footer) x.footer.hasOwnProperty(r) && (x.footer[r] = $.jgrid.stripHtml(x.footer[r])); $.isEmptyObject(x.footer) || (I(x.footer, !0), $("row:last c", f).attr("s", "2")) } var O = $.jgrid.makeNode(f, "cols"); for ($("worksheet", f).prepend(O), r = 0, s = x.width.length; r < s; r++)O.appendChild($.jgrid.makeNode(f, "col", { attr: { min: r + 1, max: r + 1, width: x.width[r], customWidth: 1 } })); $.isFunction(P.onBeforeExport) && P.onBeforeExport(t, g), x = null; try { var T = new JSZip, A = { type: "blob", mimeType: P.mimetype }; $.jgrid.xmlToZip(T, t), T.generateAsync ? T.generateAsync(A).then(function (e) { $.jgrid.saveAs(e, P.fileName, { type: P.mimetype }) }) : $.jgrid.saveAs(T.generate(A), P.fileName, { type: P.mimetype }) } catch (e) { throw e } finally { $.isFunction(P.loadIndicator) ? P.loadIndicator("hide") : P.loadIndicator && $(y).jqGrid("progressBar", { method: "hide", loadtype: y.p.loadui }) } }) }, exportToPdf: function (y) { return y = $.extend(!0, { title: null, orientation: "portrait", pageSize: "A4", description: null, onBeforeExport: null, download: "download", includeLabels: !0, includeGroupHeader: !0, includeFooter: !0, includeHeader: !0, fileName: "jqGridExport.pdf", mimetype: "application/pdf", treeindent: "-", loadIndicator: !0 }, y || {}), this.each(function () { var e, t, r, x = this, _ = [], i = x.p.colModel, a = {}, n = x.p.treeGrid ? $(x).jqGrid("getRowData", null, !0, y.treeindent) : x.addLocalData(!0), q = [], l = 0, s = [], o = [], d = [], I = {}; for ($.isFunction(y.loadIndicator) ? y.loadIndicator("show") : y.loadIndicator && $(x).jqGrid("progressBar", { method: "show", loadtype: x.p.loadui, htmlcontent: $.jgrid.getRegional(x, "defaults.loadtext") }), e = 0, m = i.length; e < m; e++)i[e]._expcol = !0, void 0 === i[e].exportcol ? i[e].hidden && (i[e]._expcol = !1) : i[e]._expcol = i[e].exportcol, "cb" !== i[e].name && "rn" !== i[e].name && "subgrid" !== i[e].name && i[e]._expcol && (a = { text: x.p.colNames[e], style: "tableHeader" }, o.push(a), q[l] = i[e].name, s[l] = e, d.push(i[e].width), I[i[e].name] = i[e].align || "left", l++); if (y.includeGroupHeader && $(x).jqGrid("isGroupHeaderOn")) for (r = x.p.groupHeader, l = 0; l < r.length; l++) { for (var p = [], c = r[l].groupHeaders, u = 0; u < q.length; u++) { for (a = { text: "", style: "tableHeader" }, t = 0; t < c.length; t++)c[t].startColumnName === q[u] && (a = { text: c[t].titleText, colSpan: c[t].numberOfColumns, style: "tableHeader" }); p.push(a), e++ } _.push(p) } if (y.includeLabels && _.push(o), y.includeHeader && x.p.headerrow) { var h = $(x).jqGrid("headerData", "get"), o = []; for (u = 0; u < q.length; u++)a = { text: $.jgrid.stripHtml($.jgrid.getAccessor(h, q[u])), style: "tableFooter", alignment: I[q[u]] }, o.push(a); _.push(o) } if (x.p.grouping) { var g = !!x.p.groupingView._locgr; x.p.groupingView._locgr = !1, function (p) { var c = x.p.groupingView, u = [], h = c.groupField.length, g = x.p.colModel, f = g.length, m = 0; function v(e, t) { for (var r = 0, i = [], o = 0; o < q.length; o++)a = { text: null == e[q[o]] ? "" : t ? $.jgrid.formatCell(e[q[o]] + "", s[r], n[l], g[s[r]], x, "pdf") : e[q[o]], alignment: I[o], style: "tableBody" }, i.push(a), r++; return i } function b(e, t, r, i) { for (var o, a, n = function (e, t, r) { var i, o = !1; if (0 === t) o = r[e]; else { var a = r[e].idx; if (0 === a) o = r[e]; else for (i = e; 0 <= i; i--)if (r[i].idx === a - t) { o = r[i]; break } } return o }(e, t, r), l = n.cnt, s = j(q), d = i; d < f; d++)g[d]._expcol && (a = "{0}", $.each(n.summary, function () { if (this.nm === g[d].name) { g[d].summaryTpl && (a = g[d].summaryTpl), "string" == typeof this.st && "avg" === this.st.toLowerCase() && (this.sd && this.vd ? this.v = this.v / this.vd : this.v && 0 < l && (this.v = this.v / l)); try { this.groupCount = n.cnt, this.groupIndex = n.dataIndex, this.groupValue = n.value, o = this.v } catch (e) { o = this.v } return s[this.nm] = $.jgrid.stripHtml($.jgrid.template(a, o)), !1 } })); return s } function j(e) { for (var t = {}, r = 0; r < e.length; r++)t[e[r]] = ""; return t } $.each(g, function (e, t) { for (var r = 0; r < h; r++)if (c.groupField[r] === t.name) { u[r] = e; break } }); var y, w = $.makeArray(c.groupSummary); if (w.reverse(), "local" === x.p.datatype && !x.p.loadonce) { $(x).jqGrid("groupingSetup"); for (var e = $.jgrid.getMethod("groupingPrepare"), t = 0; t < n.length; t++)e.call($(x), n[t], t) } $.each(c.groups, function (e, t) { m++; try { y = $.isArray(c.formatDisplayField) && $.isFunction(c.formatDisplayField[t.idx]) ? c.formatDisplayField[t.idx].call(x, t.displayValue, t.value, x.p.colModel[u[t.idx]], t.idx, c) : x.formatter("", t.displayValue, u[t.idx], t.value) } catch (e) { y = t.displayValue } var r, i = ""; if ("string" != typeof (i = $.isFunction(c.groupText[t.idx]) ? c.groupText[t.idx].call(x, y, t.cnt, t.summary) : $.jgrid.template(c.groupText[t.idx], y, t.cnt, t.summary)) && "number" != typeof i && (i = y), (r = "header" === c.groupSummaryPos[t.idx] ? b(e, 0, c.groups, 0) : j(q))[Object.keys(r)[0]] = $.jgrid.stripHtml(new Array(5 * t.idx).join(" ") + i), _.push(v(r, !0)), h - 1 === t.idx) { for (var o, a, n = c.groups[e + 1], i = t.startRow, l = void 0 !== n ? n.startRow : c.groups[e].startRow + c.groups[e].cnt, s = i; s < l && p[+s]; s++) { var d = p[+s]; _.push(v(d, !0)) } if ("header" !== c.groupSummaryPos[t.idx]) { if (void 0 !== n) { for (a = 0; a < c.groupField.length && n.dataIndex !== c.groupField[a]; a++); m = c.groupField.length - a } for (o = 0; o < m; o++)w[o] && (r = b(e, o, c.groups, 0), _.push(v(r, !0))); m = a } } }) }(n), x.p.groupingView._locgr = g } else for (var f, l = 0, m = n.length; l < m; l++) { for (t = 0, o = [], f = n[l], u = 0; u < q.length; u++)a = { text: null == f[q[u]] ? "" : $.jgrid.stripHtml($.jgrid.formatCell($.jgrid.getAccessor(f, q[u]) + "", s[t], n[l], i[s[t]], x, "pdf")), alignment: I[q[u]], style: "tableBody" }, o.push(a), t++; _.push(o) } if (y.includeFooter && x.p.footerrow) { var v = $(x).jqGrid("footerData", "get"); for (o = [], u = 0; u < q.length; u++)a = { text: $.jgrid.stripHtml($.jgrid.getAccessor(v, q[u])), style: "tableFooter", alignment: I[q[u]] }, o.push(a); _.push(o) } var b = { pageSize: y.pageSize, pageOrientation: y.orientation, content: [{ style: "tableExample", widths: d, table: { headerRows: null != r ? 0 : 1, body: _ } }], styles: { tableHeader: { bold: !0, fontSize: 11, color: "#2e6e9e", fillColor: "#dfeffc", alignment: "center" }, tableBody: { fontSize: 10 }, tableFooter: { bold: !0, fontSize: 11, color: "#2e6e9e", fillColor: "#dfeffc" }, title: { alignment: "center", fontSize: 15 }, description: {} }, defaultStyle: { fontSize: 10 } }; y.description && b.content.unshift({ text: y.description, style: "description", margin: [0, 0, 0, 12] }), y.title && b.content.unshift({ text: y.title, style: "title", margin: [0, 0, 0, 12] }), $.isFunction(y.onBeforeExport) && y.onBeforeExport.call(x, b); try { var j = pdfMake.createPdf(b); j.getDataUrl(function (e) { $.isFunction(y.loadIndicator) ? y.loadIndicator("hide") : y.loadIndicator && $(x).jqGrid("progressBar", { method: "hide", loadtype: x.p.loadui }) }), "open" === y.download ? j.open() : j.getBuffer(function (e) { $.jgrid.saveAs(e, y.fileName, { type: y.mimetype }) }) } catch (e) { throw e } }) }, exportToHtml: function (d) { var p; return d = $.extend(!0, { title: "", onBeforeExport: null, includeLabels: !0, includeGroupHeader: !0, includeFooter: !0, includeHeader: !0, tableClass: "jqgridprint", autoPrint: !1, topText: "", bottomText: "", returnAsString: !1, treeindent: "&nbsp;", loadIndicator: !0 }, d || {}), this.each(function () { var w = this, x = w.p.colModel, e = 0, _ = { body: w.p.treeGrid ? $(w).jqGrid("getRowData", null, !0, d.treeindent) : w.addLocalData(!0), header: [], footer: [], width: [], map: [], align: [] }, t = 0; for (n = x.length; t < n; t++)x[t]._expcol = !0, void 0 === x[t].exportcol ? x[t].hidden && (x[t]._expcol = !1) : x[t]._expcol = x[t].exportcol, "cb" !== x[t].name && "rn" !== x[t].name && "subgrid" !== x[t].name && x[t]._expcol && (_.header[e] = x[t].name, _.width[e] = x[t].width, _.map[e] = t, _.align[e] = x[t].align || "left", e++); var r = document.createElement("a"), i = function (e) { r.href = e; e = r.host; return -1 === e.indexOf("/") && 0 !== r.pathname.indexOf("/") && (e += "/"), r.protocol + "//" + e + r.pathname + r.search }, q = function (e, t, r, i, o) { for (var a, n, l = "<tr>", s = 0, d = _.header.length; s < d && (n = o ? ' colspan= "' + _.header.length + '" style=text-align:left' : !0 === i ? " style=width:" + _.width[s] + "px;text-align:" + _.align[s] + ";" : " style=text-align:" + _.align[s] + ";", a = _.header[s], e.hasOwnProperty(a) && (l += "<" + t + n + ">" + (r ? $.jgrid.formatCell($.jgrid.getAccessor(e, a), _.map[s], e, x[_.map[s]], w, "html") : e[a]) + "</" + t + ">"), !o); s++); return l + "</tr>" }; $.isFunction(d.loadIndicator) ? d.loadIndicator("show") : d.loadIndicator && $(w).jqGrid("progressBar", { method: "show", loadtype: w.p.loadui, htmlcontent: $.jgrid.getRegional(w, "defaults.loadtext") }); var o = '<table class="' + d.tableClass + '">'; if (d.includeLabels && (o += "<thead>" + function (e, t, r) { for (var i = "<tr>", o = 0, a = e.length; o < a; o++)i += "<" + t + (!0 === r ? " style=width:" + _.width[o] + "px;" : "") + ">" + w.p.colNames[_.map[o]] + "</" + t + ">"; return i + "</tr>" }(_.header, "th", !0) + "</thead>"), o += "<tbody>", d.includeHeader && w.p.headerrow && (a = $(w).jqGrid("headerData", "get", null, !1), o += q(a, "td", !1)), w.p.grouping) { var a = !!w.p.groupingView._locgr; w.p.groupingView._locgr = !1, o += function (c) { var u = w.p.groupingView, h = [], g = u.groupField.length, p = x.length, f = 0, m = ""; function v(e, t, r, i) { for (var o, a, n = function (e, t, r) { var i, o = !1; if (0 === t) o = r[e]; else { var a = r[e].idx; if (0 === a) o = r[e]; else for (i = e; 0 <= i; i--)if (r[i].idx === a - t) { o = r[i]; break } } return o }(e, t, r), l = n.cnt, s = b(_.header), d = i; d < p; d++)x[d]._expcol && (a = "{0}", $.each(n.summary, function () { if (this.nm === x[d].name) { x[d].summaryTpl && (a = x[d].summaryTpl), "string" == typeof this.st && "avg" === this.st.toLowerCase() && (this.sd && this.vd ? this.v = this.v / this.vd : this.v && 0 < l && (this.v = this.v / l)); try { this.groupCount = n.cnt, this.groupIndex = n.dataIndex, this.groupValue = n.value, o = this.v } catch (e) { o = this.v } return s[this.nm] = $.jgrid.stripHtml($.jgrid.template(a, o)), !1 } })); return s } function b(e) { for (var t = {}, r = 0; r < e.length; r++)t[e[r]] = ""; return t } $.each(x, function (e, t) { for (var r = 0; r < g; r++)if (u.groupField[r] === t.name) { h[r] = e; break } }); var j, y = $.makeArray(u.groupSummary); if (y.reverse(), "local" === w.p.datatype && !w.p.loadonce) { $(w).jqGrid("groupingSetup"); for (var e = $.jgrid.getMethod("groupingPrepare"), t = 0; t < _.body.length; t++)e.call($(w), _.body[t], t) } return $.each(u.groups, function (e, t) { f++; try { j = $.isArray(u.formatDisplayField) && $.isFunction(u.formatDisplayField[t.idx]) ? u.formatDisplayField[t.idx].call(w, t.displayValue, t.value, w.p.colModel[h[t.idx]], t.idx, u) : w.formatter("", t.displayValue, h[t.idx], t.value) } catch (e) { j = t.displayValue } var r = ""; "string" != typeof (r = $.isFunction(u.groupText[t.idx]) ? u.groupText[t.idx].call(w, j, t.cnt, t.summary) : $.jgrid.template(u.groupText[t.idx], j, t.cnt, t.summary)) && "number" != typeof r && (r = j); var i, o = !1; if ("header" === u.groupSummaryPos[t.idx] ? i = v(e, 0, u.groups, 0) : (i = b(_.header), o = !0), i[Object.keys(i)[0]] = new Array(5 * t.idx).join(" ") + r, m += q(i, "td", !0, 1 === f, o), g - 1 === t.idx) { for (var a, n, l = u.groups[e + 1], o = t.startRow, s = void 0 !== l ? l.startRow : u.groups[e].startRow + u.groups[e].cnt, d = o; d < s && c[+d]; d++) { var p = c[+d]; m += q(p, "td", !0) } if ("header" !== u.groupSummaryPos[t.idx]) { if (void 0 !== l) { for (n = 0; n < u.groupField.length && l.dataIndex !== u.groupField[n]; n++); f = u.groupField.length - n } for (a = 0; a < f; a++)y[a] && (i = v(e, a, u.groups, 0), m += q(i, "td", !0)); f = n } } }), m }(_.body), w.p.groupingView._locgr = a } else for (var e = 0, n = _.body.length; e < n; e++)o += q(_.body[e], "td", !0, 0 === e); if (d.includeFooter && w.p.footerrow && (_.footer = $(w).jqGrid("footerData", "get", null, !1), o += q(_.footer, "td", !1)), o += "</tbody>", o += "</table>", d.returnAsString) p = o; else { var l = window.open("", ""); l.document.close(); var s = d.title ? "<title>" + d.title + "</title>" : ""; $("style, link").each(function () { s += function (e) { e = $(e).clone()[0]; return "link" === e.nodeName.toLowerCase() && (e.href = i(e.href)), e.outerHTML }(this) }); try { l.document.head.innerHTML = s } catch (e) { $(l.document.head).html(s) } l.document.body.innerHTML = (d.title ? "<h1>" + d.title + "</h1>" : "") + "<div>" + (d.topText || "") + "</div>" + o + "<div>" + (d.bottomText || "") + "</div>", $(l.document.body).addClass("html-view"), $("img", l.document.body).each(function (e, t) { t.setAttribute("src", i(t.getAttribute("src"))) }), d.onBeforeExport && d.onBeforeExport(l), Boolean(l.chrome) ? d.autoPrint && (l.print(), l.close()) : setTimeout(function () { d.autoPrint && (l.print(), l.close()) }, 1e3) } $.isFunction(d.loadIndicator) ? d.loadIndicator("hide") : d.loadIndicator && $(w).jqGrid("progressBar", { method: "hide", loadtype: w.p.loadui }) }), p } }), $.extend($.jgrid, { focusableElementsList: [">a[href]", ">button:not([disabled])", ">area[href]", ">input:not([disabled])", ">select:not([disabled])", ">textarea:not([disabled])", ">iframe", ">object", ">embed", ">*[tabindex]", ">*[contenteditable]"] }), $.jgrid.extend({ ariaBodyGrid: function (e) { var c = $.extend({ onEnterCell: null }, e || {}); return this.each(function () { var n = this, r = $.jgrid.getMethod("getStyleUI"), l = r(n.p.styleUI + ".common", "highlight", !0); function a(e, t) { return !isNaN(e) && !isNaN(t) && 0 <= e && 0 <= t && n.rows.length && e < n.rows.length && t < n.p.colModel.length } function i(e, t) { var r = n.p.iRow + t, i = n.p.iCol + e, o = n.rows.length, t = 0 !== e; if (!o) return !1; e = n.p.colModel.length; return t && (i < 0 && 2 <= r && (i = e - 1, r--), e <= i && (i = 0, r++)), t || (r < 1 ? (i--, r = o - 1, n.rows[r] && 0 <= i && !n.rows[r].cells[i] && r--) : (o <= r || !n.rows[r].cells[i]) && (r = 1, i++)), a(r, i) ? { row: r, col: i } : !!a(n.p.iRow, n.p.iCol) && { row: n.p.iRow, col: n.p.iCol } } function o(e, t) { var r = i(e, t); if (!r) return !1; for (; $(n.rows[r.row].cells[r.col]).is(":hidden");)if (n.p.iRow = r.row, n.p.iCol = r.col, r = i(e, t), n.p.iRow === r.row && n.p.iCol === r.col) return !1; return 0 !== t && $(n).jqGrid("setSelection", n.rows[r.row].id, !1, null, !1), r } function s(e) { var t = n.p.page, r = n.p.lastpage; (t += e) <= 0 && (t = 1), r < t && (t = r), n.p.page !== t && (n.p.page = t, n.grid.populate()) } var t = $.jgrid.focusableElementsList.join(); $(n).removeAttr("tabindex"), $(n).on("jqGridAfterGridComplete.setAriaGrid", function (e) { $("tbody:first>tr:not(.jqgfirstrow)>td:not(:hidden, :has(" + t + "))", n).attr("tabindex", -1), $("tbody:first>tr:not(.jqgfirstrow)", n).removeAttr("tabindex"), void 0 !== n.p.iRow && void 0 !== n.p.iCol && n.rows[n.p.iRow] && $(n.rows[n.p.iRow].cells[n.p.iCol]).attr("tabindex", 0).focus(function () { $(this).addClass(l) }).blur(function () { $(this).removeClass(l) }) }), n.p.iRow = 1, n.p.iCol = $.jgrid.getFirstVisibleCol(n); var d = 0, p = 0; $(n).on("keydown", function (e) { if (!n.p.navigationDisabled || !0 !== n.p.navigationDisabled) { var t; switch (e.which || e.keyCode) { case 38: t = o(0, -1), d = t.row, p = t.col, e.preventDefault(); break; case 40: t = o(0, 1), d = t.row, p = t.col, e.preventDefault(); break; case 37: t = o(-1, 0), d = t.row, p = t.col, e.preventDefault(); break; case 39: t = o(1, 0), d = t.row, p = t.col, e.preventDefault(); break; case 36: d = e.ctrlKey ? 1 : n.p.iRow, p = 0, e.preventDefault(); break; case 35: d = e.ctrlKey ? n.rows.length - 1 : n.p.iRow, p = n.p.colModel.length - 1, e.preventDefault(); break; case 33: s(-1), p = n.p.iCol, d = n.p.iRow, e.preventDefault(); break; case 34: s(1), p = n.p.iCol, (d = n.p.iRow) > n.rows.length - 1 && (d = n.rows.length - 1, n.p.iRow = n.rows.length - 1), e.preventDefault(); break; case 13: return void ($.isFunction(c.onEnterCell) && (c.onEnterCell.call(n, n.rows[n.p.iRow].id, n.p.iRow, n.p.iCol, e), e.preventDefault())); default: return }$(n).jqGrid("focusBodyCell", d, p, r, l) } }), $(n).on("jqGridBeforeSelectRow.ariaGridClick", function () { return !1 }), $(n).on("jqGridCellSelect.ariaGridClick", function (e, t, r, i, o) { var a = o.target; 0 < n.p.iRow && 0 <= n.p.iCol && $(n.rows[n.p.iRow].cells[n.p.iCol]).attr("tabindex", -1), ($(a).is("td") || $(a).is("th")) && (n.p.iCol = a.cellIndex, o = $(a).closest("tr.jqgrow"), n.p.iRow = o[0].rowIndex, $(a).attr("tabindex", 0).addClass(l).focus().blur(function () { $(this).removeClass(l) })) }) }) }, focusBodyCell: function (n, l, s, d) { return this.each(function () { var e, t = this, r = s || $.jgrid.getMethod("getStyleUI"), i = d || r(t.p.styleUI + ".common", "highlight", !0), o = $.jgrid.focusableElementsList.join(); function a(e) { return $(o, e)[0] } void 0 !== n && void 0 !== l ? !isNaN(t.p.iRow) && !isNaN(t.p.iCol) && 0 <= t.p.iCol && (e = a(t.rows[t.p.iRow].cells[t.p.iCol]), $(e || t.rows[t.p.iRow].cells[t.p.iCol]).attr("tabindex", -1)) : (n = t.p.iRow, l = t.p.iCol), n = parseInt(n, 10), l = parseInt(l, 10), 0 < n && 0 <= l && (e = a(t.rows[n].cells[l]), $(e || t.rows[n].cells[l]).attr("tabindex", 0).addClass(i).focus().blur(function () { $(this).removeClass(i) }), t.p.iRow = n, t.p.iCol = l) }) }, resetAriaBody: function () { return this.each(function () { $(this).attr("tabindex", "0").off("keydown").off("jqGridBeforeSelectRow.ariaGridClick").off("jqGridCellSelect.ariaGridClick").off("jqGridAfterGridComplete.setAriaGrid"); var e = $.jgrid.focusableElementsList.join(); $("tbody:first>tr:not(.jqgfirstrow)>td:not(:hidden, :has(" + e + "))", this).removeAttr("tabindex").off("focus"), $("tbody:first>tr:not(.jqgfirstrow)", this).attr("tabindex", -1) }) }, ariaHeaderGrid: function () { return this.each(function () { var o = this, e = $.jgrid.getMethod("getStyleUI")(o.p.styleUI + ".common", "highlight", !0), t = $(".ui-jqgrid-hbox>table:first", "#gbox_" + o.p.id); $("tr.ui-jqgrid-labels", t).on("keydown", function (e) { var t = o.p.selHeadInd, r = e.which || e.keyCode, i = o.grid.headers.length; switch (r) { case 37: if (0 <= t - 1) { for (t--; $(o.grid.headers[t].el).is(":hidden") && 0 <= t - 1 && !(--t < 0);); 0 <= t && ($(o.grid.headers[t].el).focus(), $(o.grid.headers[o.p.selHeadInd].el).attr("tabindex", "-1"), o.p.selHeadInd = t, e.preventDefault()) } break; case 39: if (t + 1 < i) { for (t++; $(o.grid.headers[t].el).is(":hidden") && t + 1 < i && !(i - 1 < ++t);); t < i && ($(o.grid.headers[t].el).focus(), $(o.grid.headers[o.p.selHeadInd].el).attr("tabindex", "-1"), o.p.selHeadInd = t, e.preventDefault()) } break; case 13: $("div:first", o.grid.headers[t].el).trigger("click"), e.preventDefault(); break; default: return } }), $("tr.ui-jqgrid-labels>th:not(:hidden)", t).attr("tabindex", -1).focus(function () { $(this).addClass(e).attr("tabindex", "0") }).blur(function () { $(this).removeClass(e) }), o.p.selHeadInd = $.jgrid.getFirstVisibleCol(o), $(o.grid.headers[o.p.selHeadInd].el).attr("tabindex", "0") }) }, focusHeaderCell: function (e) { return this.each(function () { void 0 === e && (e = this.p.selHeadInd), 0 <= e && e < this.p.colModel.length && ($(this.grid.headers[this.p.selHeadInd].el).attr("tabindex", "-1"), $(this.grid.headers[e].el).focus(), this.p.selHeadInd = e) }) }, resetAriaHeader: function () { return this.each(function () { var e = $(".ui-jqgrid-hbox>table:first", "#gbox_" + this.p.id); $("tr.ui-jqgrid-labels", e).off("keydown"), $("tr.ui-jqgrid-labels>th:not(:hidden)", e).removeAttr("tabindex").off("focus blur") }) }, ariaPagerGrid: function () { return this.each(function () { var i = this, e = $.jgrid.getMethod("getStyleUI"), t = e(i.p.styleUI + ".common", "highlight", !0), o = "." + e(i.p.styleUI + ".common", "disabled", !0), a = $(".ui-pg-button", i.p.pager), n = a.length; a.attr("tabindex", "-1").focus(function () { $(this).addClass(t) }).blur(function () { $(this).removeClass(t) }), i.p.navIndex = 0, setTimeout(function () { var e = a.not(o).first().attr("tabindex", "0"); i.p.navIndex = e[0].cellIndex ? e[0].cellIndex - 1 : 0 }, 100), $("table.ui-pager-table tr:first", i.p.pager).on("keydown", function (e) { var t = e.which || e.keyCode, r = i.p.navIndex; switch (t) { case 37: if (0 <= r - 1) { for (r--; $(a[r]).is(o) && 0 <= r - 1 && !(--r < 0);); 0 <= r && ($(a[i.p.navIndex]).attr("tabindex", "-1"), $(a[r]).attr("tabindex", "0").focus(), i.p.navIndex = r), e.preventDefault() } break; case 39: if (r + 1 < n) { for (r++; $(a[r]).is(o) && r + 1 < n + 1 && !(n - 1 < ++r);); r < n && ($(a[i.p.navIndex]).attr("tabindex", "-1"), $(a[r]).attr("tabindex", "0").focus(), i.p.navIndex = r), e.preventDefault() } break; case 13: $(a[r]).trigger("click"), e.preventDefault(); break; default: return } }) }) }, focusPagerCell: function (r) { return this.each(function () { var e = $(".ui-pg-button", this.p.pager), t = e.length; void 0 === r && (r = this.p.navIndex), 0 <= r && r < t && ($(e[this.p.navIndex]).attr("tabindex", "-1"), $(e[r]).attr("tabindex", "0").focus(), this.p.navIndex = r) }) }, resetAriaPager: function () { return this.each(function () { $(".ui-pg-button", this.p.pager).removeAttr("tabindex").off("focus"), $("table.ui-pager-table tr:first", this.p.pager).off("keydown") }) }, setAriaGrid: function (e) { var t = $.extend({ header: !0, body: !0, pager: !0, onEnterCell: null }, e || {}); return this.each(function () { t.header && $(this).jqGrid("ariaHeaderGrid"), t.body && $(this).jqGrid("ariaBodyGrid", { onEnterCell: t.onEnterCell }), t.pager && $(this).jqGrid("ariaPagerGrid") }) }, resetAriaGrid: function (e) { var t = $.extend({ header: !0, body: !0, pager: !0 }, e || {}); return this.each(function () { t.body && $(this).jqGrid("resetAriaBody"), t.header && $(this).jqGrid("resetAriaHeader"), t.pager && $(this).jqGrid("resetAriaPager") }) } }) });
//# sourceMappingURL=jquery.jqGrid.min.js.map;
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};;
/*
 * Treeview 1.5pre - jQuery plugin to hide and show branches of a tree
 * 
 * http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
 * http://docs.jquery.com/Plugins/Treeview
 *
 * Copyright (c) 2007 Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.treeview.js 5759 2008-07-01 07:50:28Z joern.zaefferer $
 *
 */

;(function($) {

	// TODO rewrite as a widget, removing all the extra plugins
	$.extend($.fn, {
		swapClass: function(c1, c2) {
			var c1Elements = this.filter('.' + c1);
			this.filter('.' + c2).removeClass(c2).addClass(c1);
			c1Elements.removeClass(c1).addClass(c2);
			return this;
		},
		replaceClass: function(c1, c2) {
			return this.filter('.' + c1).removeClass(c1).addClass(c2).end();
		},
		hoverClass: function(className) {
			className = className || "hover";
			return this.hover(function() {
				$(this).addClass(className);
			}, function() {
				$(this).removeClass(className);
			});
		},
		heightToggle: function(animated, callback) {
			animated ?
				this.animate({ height: "toggle" }, animated, callback) :
				this.each(function(){
					jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
					if(callback)
						callback.apply(this, arguments);
				});
		},
		heightHide: function(animated, callback) {
			if (animated) {
				this.animate({ height: "hide" }, animated, callback);
			} else {
				this.hide();
				if (callback)
					this.each(callback);				
			}
		},
		prepareBranches: function(settings) {
			if (!settings.prerendered) {
				// mark last tree items
				this.filter(":last-child:not(ul)").addClass(CLASSES.last);
				// collapse whole tree, or only those marked as closed, anyway except those marked as open
				this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide();
			}
			// return all items with sublists
			return this.filter(":has(>ul)");
		},
		applyClasses: function(settings, toggler) {
			// TODO use event delegation
			this.filter(":has(>ul):not(:has(>a))").find(">span").unbind("click.treeview").bind("click.treeview", function(event) {
				// don't handle click events on children, eg. checkboxes
				if ( this == event.target )
					toggler.apply($(this).next());
			}).add( $("a", this) ).hoverClass();
			
			if (!settings.prerendered) {
				// handle closed ones first
				this.filter(":has(>ul:hidden)")
						.addClass(CLASSES.expandable)
						.replaceClass(CLASSES.last, CLASSES.lastExpandable);
						
				// handle open ones
				this.not(":has(>ul:hidden)")
						.addClass(CLASSES.collapsable)
						.replaceClass(CLASSES.last, CLASSES.lastCollapsable);
						
	            // create hitarea if not present
				var hitarea = this.find("div." + CLASSES.hitarea);
				if (!hitarea.length)
					hitarea = this.prepend("<div class=\"" + CLASSES.hitarea + "\"/>").find("div." + CLASSES.hitarea);
				hitarea.removeClass().addClass(CLASSES.hitarea).each(function() {
					var classes = "";
					$.each($(this).parent().attr("class").split(" "), function() {
						classes += this + "-hitarea ";
					});
					$(this).addClass( classes );
				})
			}
			
			// apply event to hitarea
			this.find("div." + CLASSES.hitarea).click( toggler );
		},
		treeview: function(settings) {
			
			settings = $.extend({
				cookieId: "treeview"
			}, settings);
			
			if ( settings.toggle ) {
				var callback = settings.toggle;
				settings.toggle = function() {
					return callback.apply($(this).parent()[0], arguments);
				};
			}
		
			// factory for treecontroller
			function treeController(tree, control) {
				// factory for click handlers
				function handler(filter) {
					return function() {
						// reuse toggle event handler, applying the elements to toggle
						// start searching for all hitareas
						toggler.apply( $("div." + CLASSES.hitarea, tree).filter(function() {
							// for plain toggle, no filter is provided, otherwise we need to check the parent element
							return filter ? $(this).parent("." + filter).length : true;
						}) );
						return false;
					};
				}
				// click on first element to collapse tree
				$("a:eq(0)", control).click( handler(CLASSES.collapsable) );
				// click on second to expand tree
				$("a:eq(1)", control).click( handler(CLASSES.expandable) );
				// click on third to toggle tree
				$("a:eq(2)", control).click( handler() ); 
			}
		
			// handle toggle event
			function toggler() {
				$(this)
					.parent()
					// swap classes for hitarea
					.find(">.hitarea")
						.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
						.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
					.end()
					// swap classes for parent li
					.swapClass( CLASSES.collapsable, CLASSES.expandable )
					.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
					// find child lists
					.find( ">ul" )
					// toggle them
					.heightToggle( settings.animated, settings.toggle );
				if ( settings.unique ) {
					$(this).parent()
						.siblings()
						// swap classes for hitarea
						.find(">.hitarea")
							.replaceClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
							.replaceClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
						.end()
						.replaceClass( CLASSES.collapsable, CLASSES.expandable )
						.replaceClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
						.find( ">ul" )
						.heightHide( settings.animated, settings.toggle );
				}
			}
			this.data("toggler", toggler);
			
			function serialize() {
				function binary(arg) {
					return arg ? 1 : 0;
				}
				var data = [];
				branches.each(function(i, e) {
					data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0;
				});
				$.cookie(settings.cookieId, data.join(""), settings.cookieOptions );
			}
			
			function deserialize() {
				var stored = $.cookie(settings.cookieId);
				if ( stored ) {
					var data = stored.split("");
					branches.each(function(i, e) {
						$(e).find(">ul")[ parseInt(data[i]) ? "show" : "hide" ]();
					});
				}
			}
			
			// add treeview class to activate styles
			this.addClass("treeview");
			
			// prepare branches and find all tree items with child lists
			var branches = this.find("li").prepareBranches(settings);
			
			switch(settings.persist) {
			case "cookie":
				var toggleCallback = settings.toggle;
				settings.toggle = function() {
					serialize();
					if (toggleCallback) {
						toggleCallback.apply(this, arguments);
					}
				};
				deserialize();
				break;
			case "location":
				var current = this.find("a").filter(function() {
					return this.href.toLowerCase() == location.href.toLowerCase();
				});
				if ( current.length ) {
					// TODO update the open/closed classes
					var items = current.addClass("selected").parents("ul, li").add( current.next() ).show();
					if (settings.prerendered) {
						// if prerendered is on, replicate the basic class swapping
						items.filter("li")
							.swapClass( CLASSES.collapsable, CLASSES.expandable )
							.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
							.find(">.hitarea")
								.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
								.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea );
					}
				}
				break;
			}
			
			branches.applyClasses(settings, toggler);
				
			// if control option is set, create the treecontroller and show it
			if ( settings.control ) {
				treeController(this, settings.control);
				$(settings.control).show();
			}
			
			return this;
		}
	});
	
	// classes used by the plugin
	// need to be styled via external stylesheet, see first example
	$.treeview = {};
	var CLASSES = ($.treeview.classes = {
		open: "open",
		closed: "closed",
		expandable: "expandable",
		expandableHitarea: "expandable-hitarea",
		lastExpandableHitarea: "lastExpandable-hitarea",
		collapsable: "collapsable",
		collapsableHitarea: "collapsable-hitarea",
		lastCollapsableHitarea: "lastCollapsable-hitarea",
		lastCollapsable: "lastCollapsable",
		lastExpandable: "lastExpandable",
		last: "last",
		hitarea: "hitarea"
	});
	
})(jQuery);;
/*
 * qTip2 - Pretty powerful tooltips - v2.2.1
 * http://qtip2.com
 *
 * Copyright (c) 2014 
 * Released under the MIT licenses
 * http://jquery.org/license
 *
 * Date: Sat Sep 6 2014 09:55 EDT-0400
 * Plugins: tips viewport
 * Styles: core basic css3
 */
/*global window: false, jQuery: false, console: false, define: false */

/* Cache window, document, undefined */
(function (window, document, undefined) {

    // Uses AMD or browser globals to create a jQuery plugin.
    (function (factory) {
        "use strict";
        if (typeof define === 'function' && define.amd) {
            define(['jquery'], factory);
        }
        else if (jQuery && !jQuery.fn.qtip) {
            factory(jQuery);
        }
    }
    (function ($) {
        "use strict"; // Enable ECMAScript "strict" operation for this function. See more: http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
        ;// Munge the primitives - Paul Irish tip
        var TRUE = true,
        FALSE = false,
        NULL = null,

        // Common variables
        X = 'x', Y = 'y',
        WIDTH = 'width',
        HEIGHT = 'height',

        // Positioning sides
        TOP = 'top',
        LEFT = 'left',
        BOTTOM = 'bottom',
        RIGHT = 'right',
        CENTER = 'center',

        // Position adjustment types
        FLIP = 'flip',
        FLIPINVERT = 'flipinvert',
        SHIFT = 'shift',

        // Shortcut vars
        QTIP, PROTOTYPE, CORNER, CHECKS,
        PLUGINS = {},
        NAMESPACE = 'qtip',
        ATTR_HAS = 'data-hasqtip',
        ATTR_ID = 'data-qtip-id',
        WIDGET = ['ui-widget', 'ui-tooltip'],
        SELECTOR = '.' + NAMESPACE,
        INACTIVE_EVENTS = 'click dblclick mousedown mouseup mousemove mouseleave mouseenter'.split(' '),

        CLASS_FIXED = NAMESPACE + '-fixed',
        CLASS_DEFAULT = NAMESPACE + '-default',
        CLASS_FOCUS = NAMESPACE + '-focus',
        CLASS_HOVER = NAMESPACE + '-hover',
        CLASS_DISABLED = NAMESPACE + '-disabled',

        replaceSuffix = '_replacedByqTip',
        oldtitle = 'oldtitle',
        trackingBound,

        // Browser detection
        BROWSER = {
            /*
             * IE version detection
             *
             * Adapted from: http://ajaxian.com/archives/attack-of-the-ie-conditional-comment
             * Credit to James Padolsey for the original implemntation!
             */
            ie: (function () {
                for (
                    var v = 4, i = document.createElement("div") ;
                    (i.innerHTML = "<!--[if gt IE " + v + "]><i></i><![endif]-->") && i.getElementsByTagName("i")[0];
                    v += 1
                ) { }
                return v > 4 ? v : NaN;
            }()),

            /*
             * iOS version detection
             */
            iOS: parseFloat(
                ('' + (/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent) || [0, ''])[1])
                .replace('undefined', '3_2').replace('_', '.').replace('_', '')
            ) || FALSE
        };
        ; function QTip(target, options, id, attr) {
            // Elements and ID
            this.id = id;
            this.target = target;
            this.tooltip = NULL;
            this.elements = { target: target };

            // Internal constructs
            this._id = NAMESPACE + '-' + id;
            this.timers = { img: {} };
            this.options = options;
            this.plugins = {};

            // Cache object
            this.cache = {
                event: {},
                target: $(),
                disabled: FALSE,
                attr: attr,
                onTooltip: FALSE,
                lastClass: ''
            };

            // Set the initial flags
            this.rendered = this.destroyed = this.disabled = this.waiting =
                this.hiddenDuringWait = this.positioning = this.triggering = FALSE;
        }
        PROTOTYPE = QTip.prototype;

        PROTOTYPE._when = function (deferreds) {
            return $.when.apply($, deferreds);
        };

        PROTOTYPE.render = function (show) {
            if (this.rendered || this.destroyed) { return this; } // If tooltip has already been rendered, exit

            var self = this,
                options = this.options,
                cache = this.cache,
                elements = this.elements,
                text = options.content.text,
                title = options.content.title,
                button = options.content.button,
                posOptions = options.position,
                namespace = '.' + this._id + ' ',
                deferreds = [],
                tooltip;

            // Add ARIA attributes to target
            $.attr(this.target[0], 'aria-describedby', this._id);

            // Create public position object that tracks current position corners
            cache.posClass = this._createPosClass(
                (this.position = { my: posOptions.my, at: posOptions.at }).my
            );

            // Create tooltip element
            this.tooltip = elements.tooltip = tooltip = $('<div/>', {
                'id': this._id,
                'class': [NAMESPACE, CLASS_DEFAULT, options.style.classes, cache.posClass].join(' '),
                'width': options.style.width || '',
                'height': options.style.height || '',
                'tracking': posOptions.target === 'mouse' && posOptions.adjust.mouse,

                /* ARIA specific attributes */
                'role': 'alert',
                'aria-live': 'polite',
                'aria-atomic': FALSE,
                'aria-describedby': this._id + '-content',
                'aria-hidden': TRUE
            })
            .toggleClass(CLASS_DISABLED, this.disabled)
            .attr(ATTR_ID, this.id)
            .data(NAMESPACE, this)
            .appendTo(posOptions.container)
            .append(
                // Create content element
                elements.content = $('<div />', {
                    'class': NAMESPACE + '-content',
                    'id': this._id + '-content',
                    'aria-atomic': TRUE
                })
            );

            // Set rendered flag and prevent redundant reposition calls for now
            this.rendered = -1;
            this.positioning = TRUE;

            // Create title...
            if (title) {
                this._createTitle();

                // Update title only if its not a callback (called in toggle if so)
                if (!$.isFunction(title)) {
                    deferreds.push(this._updateTitle(title, FALSE));
                }
            }

            // Create button
            if (button) { this._createButton(); }

            // Set proper rendered flag and update content if not a callback function (called in toggle)
            if (!$.isFunction(text)) {
                deferreds.push(this._updateContent(text, FALSE));
            }
            this.rendered = TRUE;

            // Setup widget classes
            this._setWidget();

            // Initialize 'render' plugins
            $.each(PLUGINS, function (name) {
                var instance;
                if (this.initialize === 'render' && (instance = this(self))) {
                    self.plugins[name] = instance;
                }
            });

            // Unassign initial events and assign proper events
            this._unassignEvents();
            this._assignEvents();

            // When deferreds have completed
            this._when(deferreds).then(function () {
                // tooltiprender event
                self._trigger('render');

                // Reset flags
                self.positioning = FALSE;

                // Show tooltip if not hidden during wait period
                if (!self.hiddenDuringWait && (options.show.ready || show)) {
                    self.toggle(TRUE, cache.event, FALSE);
                }
                self.hiddenDuringWait = FALSE;
            });

            // Expose API
            QTIP.api[this.id] = this;

            return this;
        };

        PROTOTYPE.destroy = function (immediate) {
            // Set flag the signify destroy is taking place to plugins
            // and ensure it only gets destroyed once!
            if (this.destroyed) { return this.target; }

            function process() {
                if (this.destroyed) { return; }
                this.destroyed = TRUE;

                var target = this.target,
                    title = target.attr(oldtitle),
                    timer;

                // Destroy tooltip if rendered
                if (this.rendered) {
                    this.tooltip.stop(1, 0).find('*').remove().end().remove();
                }

                // Destroy all plugins
                $.each(this.plugins, function (name) {
                    this.destroy && this.destroy();
                });

                // Clear timers
                for (timer in this.timers) {
                    clearTimeout(this.timers[timer]);
                }

                // Remove api object and ARIA attributes
                target.removeData(NAMESPACE)
                    .removeAttr(ATTR_ID)
                    .removeAttr(ATTR_HAS)
                    .removeAttr('aria-describedby');

                // Reset old title attribute if removed
                if (this.options.suppress && title) {
                    target.attr('title', title).removeAttr(oldtitle);
                }

                // Remove qTip events associated with this API
                this._unassignEvents();

                // Remove ID from used id objects, and delete object references
                // for better garbage collection and leak protection
                this.options = this.elements = this.cache = this.timers =
                    this.plugins = this.mouse = NULL;

                // Delete epoxsed API object
                delete QTIP.api[this.id];
            }

            // If an immediate destory is needed
            if ((immediate !== TRUE || this.triggering === 'hide') && this.rendered) {
                this.tooltip.one('tooltiphidden', $.proxy(process, this));
                !this.triggering && this.hide();
            }

                // If we're not in the process of hiding... process
            else { process.call(this); }

            return this.target;
        };
        ; function invalidOpt(a) {
            return a === NULL || $.type(a) !== 'object';
        }

        function invalidContent(c) {
            return !($.isFunction(c) || (c && c.attr) || c.length || ($.type(c) === 'object' && (c.jquery || c.then)));
        }

        // Option object sanitizer
        function sanitizeOptions(opts) {
            var content, text, ajax, once;

            if (invalidOpt(opts)) { return FALSE; }

            if (invalidOpt(opts.metadata)) {
                opts.metadata = { type: opts.metadata };
            }

            if ('content' in opts) {
                content = opts.content;

                if (invalidOpt(content) || content.jquery || content.done) {
                    content = opts.content = {
                        text: (text = invalidContent(content) ? FALSE : content)
                    };
                }
                else { text = content.text; }

                // DEPRECATED - Old content.ajax plugin functionality
                // Converts it into the proper Deferred syntax
                if ('ajax' in content) {
                    ajax = content.ajax;
                    once = ajax && ajax.once !== FALSE;
                    delete content.ajax;

                    content.text = function (event, api) {
                        var loading = text || $(this).attr(api.options.content.attr) || 'Loading...',

                        deferred = $.ajax(
                            $.extend({}, ajax, { context: api })
                        )
                        .then(ajax.success, NULL, ajax.error)
                        .then(function (content) {
                            if (content && once) { api.set('content.text', content); }
                            return content;
                        },
                        function (xhr, status, error) {
                            if (api.destroyed || xhr.status === 0) { return; }
                            api.set('content.text', status + ': ' + error);
                        });

                        return !once ? (api.set('content.text', loading), deferred) : loading;
                    };
                }

                if ('title' in content) {
                    if ($.isPlainObject(content.title)) {
                        content.button = content.title.button;
                        content.title = content.title.text;
                    }

                    if (invalidContent(content.title || FALSE)) {
                        content.title = FALSE;
                    }
                }
            }

            if ('position' in opts && invalidOpt(opts.position)) {
                opts.position = { my: opts.position, at: opts.position };
            }

            if ('show' in opts && invalidOpt(opts.show)) {
                opts.show = opts.show.jquery ? { target: opts.show } :
                    opts.show === TRUE ? { ready: TRUE } : { event: opts.show };
            }

            if ('hide' in opts && invalidOpt(opts.hide)) {
                opts.hide = opts.hide.jquery ? { target: opts.hide } : { event: opts.hide };
            }

            if ('style' in opts && invalidOpt(opts.style)) {
                opts.style = { classes: opts.style };
            }

            // Sanitize plugin options
            $.each(PLUGINS, function () {
                this.sanitize && this.sanitize(opts);
            });

            return opts;
        }

        // Setup builtin .set() option checks
        CHECKS = PROTOTYPE.checks = {
            builtin: {
                // Core checks
                '^id$': function (obj, o, v, prev) {
                    var id = v === TRUE ? QTIP.nextid : v,
                        new_id = NAMESPACE + '-' + id;

                    if (id !== FALSE && id.length > 0 && !$('#' + new_id).length) {
                        this._id = new_id;

                        if (this.rendered) {
                            this.tooltip[0].id = this._id;
                            this.elements.content[0].id = this._id + '-content';
                            this.elements.title[0].id = this._id + '-title';
                        }
                    }
                    else { obj[o] = prev; }
                },
                '^prerender': function (obj, o, v) {
                    v && !this.rendered && this.render(this.options.show.ready);
                },

                // Content checks
                '^content.text$': function (obj, o, v) {
                    this._updateContent(v);
                },
                '^content.attr$': function (obj, o, v, prev) {
                    if (this.options.content.text === this.target.attr(prev)) {
                        this._updateContent(this.target.attr(v));
                    }
                },
                '^content.title$': function (obj, o, v) {
                    // Remove title if content is null
                    if (!v) { return this._removeTitle(); }

                    // If title isn't already created, create it now and update
                    v && !this.elements.title && this._createTitle();
                    this._updateTitle(v);
                },
                '^content.button$': function (obj, o, v) {
                    this._updateButton(v);
                },
                '^content.title.(text|button)$': function (obj, o, v) {
                    this.set('content.' + o, v); // Backwards title.text/button compat
                },

                // Position checks
                '^position.(my|at)$': function (obj, o, v) {
                    'string' === typeof v && (this.position[o] = obj[o] = new CORNER(v, o === 'at'));
                },
                '^position.container$': function (obj, o, v) {
                    this.rendered && this.tooltip.appendTo(v);
                },

                // Show checks
                '^show.ready$': function (obj, o, v) {
                    v && (!this.rendered && this.render(TRUE) || this.toggle(TRUE));
                },

                // Style checks
                '^style.classes$': function (obj, o, v, p) {
                    this.rendered && this.tooltip.removeClass(p).addClass(v);
                },
                '^style.(width|height)': function (obj, o, v) {
                    this.rendered && this.tooltip.css(o, v);
                },
                '^style.widget|content.title': function () {
                    this.rendered && this._setWidget();
                },
                '^style.def': function (obj, o, v) {
                    this.rendered && this.tooltip.toggleClass(CLASS_DEFAULT, !!v);
                },

                // Events check
                '^events.(render|show|move|hide|focus|blur)$': function (obj, o, v) {
                    this.rendered && this.tooltip[($.isFunction(v) ? '' : 'un') + 'bind']('tooltip' + o, v);
                },

                // Properties which require event reassignment
                '^(show|hide|position).(event|target|fixed|inactive|leave|distance|viewport|adjust)': function () {
                    if (!this.rendered) { return; }

                    // Set tracking flag
                    var posOptions = this.options.position;
                    this.tooltip.attr('tracking', posOptions.target === 'mouse' && posOptions.adjust.mouse);

                    // Reassign events
                    this._unassignEvents();
                    this._assignEvents();
                }
            }
        };

        // Dot notation converter
        function convertNotation(options, notation) {
            var i = 0, obj, option = options,

            // Split notation into array
            levels = notation.split('.');

            // Loop through
            while (option = option[levels[i++]]) {
                if (i < levels.length) { obj = option; }
            }

            return [obj || options, levels.pop()];
        }

        PROTOTYPE.get = function (notation) {
            if (this.destroyed) { return this; }

            var o = convertNotation(this.options, notation.toLowerCase()),
                result = o[0][o[1]];

            return result.precedance ? result.string() : result;
        };

        function setCallback(notation, args) {
            var category, rule, match;

            for (category in this.checks) {
                for (rule in this.checks[category]) {
                    if (match = (new RegExp(rule, 'i')).exec(notation)) {
                        args.push(match);

                        if (category === 'builtin' || this.plugins[category]) {
                            this.checks[category][rule].apply(
                                this.plugins[category] || this, args
                            );
                        }
                    }
                }
            }
        }

        var rmove = /^position\.(my|at|adjust|target|container|viewport)|style|content|show\.ready/i,
            rrender = /^prerender|show\.ready/i;

        PROTOTYPE.set = function (option, value) {
            if (this.destroyed) { return this; }

            var rendered = this.rendered,
                reposition = FALSE,
                options = this.options,
                checks = this.checks,
                name;

            // Convert singular option/value pair into object form
            if ('string' === typeof option) {
                name = option; option = {}; option[name] = value;
            }
            else { option = $.extend({}, option); }

            // Set all of the defined options to their new values
            $.each(option, function (notation, value) {
                if (rendered && rrender.test(notation)) {
                    delete option[notation]; return;
                }

                // Set new obj value
                var obj = convertNotation(options, notation.toLowerCase()), previous;
                previous = obj[0][obj[1]];
                obj[0][obj[1]] = value && value.nodeType ? $(value) : value;

                // Also check if we need to reposition
                reposition = rmove.test(notation) || reposition;

                // Set the new params for the callback
                option[notation] = [obj[0], obj[1], value, previous];
            });

            // Re-sanitize options
            sanitizeOptions(options);

            /*
             * Execute any valid callbacks for the set options
             * Also set positioning flag so we don't get loads of redundant repositioning calls.
             */
            this.positioning = TRUE;
            $.each(option, $.proxy(setCallback, this));
            this.positioning = FALSE;

            // Update position if needed
            if (this.rendered && this.tooltip[0].offsetWidth > 0 && reposition) {
                this.reposition(options.position.target === 'mouse' ? NULL : this.cache.event);
            }

            return this;
        };
        ; PROTOTYPE._update = function (content, element, reposition) {
            var self = this,
                cache = this.cache;

            // Make sure tooltip is rendered and content is defined. If not return
            if (!this.rendered || !content) { return FALSE; }

            // Use function to parse content
            if ($.isFunction(content)) {
                content = content.call(this.elements.target, cache.event, this) || '';
            }

            // Handle deferred content
            if ($.isFunction(content.then)) {
                cache.waiting = TRUE;
                return content.then(function (c) {
                    cache.waiting = FALSE;
                    return self._update(c, element);
                }, NULL, function (e) {
                    return self._update(e, element);
                });
            }

            // If content is null... return false
            if (content === FALSE || (!content && content !== '')) { return FALSE; }

            // Append new content if its a DOM array and show it if hidden
            if (content.jquery && content.length > 0) {
                element.empty().append(
                    content.css({ display: 'block', visibility: 'visible' })
                );
            }

                // Content is a regular string, insert the new content
            else { element.html(content); }

            // Wait for content to be loaded, and reposition
            return this._waitForContent(element).then(function (images) {
                if (self.rendered && self.tooltip[0].offsetWidth > 0) {
                    self.reposition(cache.event, !images.length);
                }
            });
        };

        PROTOTYPE._waitForContent = function (element) {
            var cache = this.cache;

            // Set flag
            cache.waiting = TRUE;

            // If imagesLoaded is included, ensure images have loaded and return promise
            return ($.fn.imagesLoaded ? element.imagesLoaded() : $.Deferred().resolve([]))
                .done(function () { cache.waiting = FALSE; })
                .promise();
        };

        PROTOTYPE._updateContent = function (content, reposition) {
            this._update(content, this.elements.content, reposition);
        };

        PROTOTYPE._updateTitle = function (content, reposition) {
            if (this._update(content, this.elements.title, reposition) === FALSE) {
                this._removeTitle(FALSE);
            }
        };

        PROTOTYPE._createTitle = function () {
            var elements = this.elements,
                id = this._id + '-title';

            // Destroy previous title element, if present
            if (elements.titlebar) { this._removeTitle(); }

            // Create title bar and title elements
            elements.titlebar = $('<div />', {
                'class': NAMESPACE + '-titlebar ' + (this.options.style.widget ? createWidgetClass('header') : '')
            })
            .append(
                elements.title = $('<div />', {
                    'id': id,
                    'class': NAMESPACE + '-title',
                    'aria-atomic': TRUE
                })
            )
            .insertBefore(elements.content)

            // Button-specific events
            .delegate('.qtip-close', 'mousedown keydown mouseup keyup mouseout', function (event) {
                $(this).toggleClass('ui-state-active ui-state-focus', event.type.substr(-4) === 'down');
            })
            .delegate('.qtip-close', 'mouseover mouseout', function (event) {
                $(this).toggleClass('ui-state-hover', event.type === 'mouseover');
            });

            // Create button if enabled
            if (this.options.content.button) { this._createButton(); }
        };

        PROTOTYPE._removeTitle = function (reposition) {
            var elements = this.elements;

            if (elements.title) {
                elements.titlebar.remove();
                elements.titlebar = elements.title = elements.button = NULL;

                // Reposition if enabled
                if (reposition !== FALSE) { this.reposition(); }
            }
        };
        ; PROTOTYPE._createPosClass = function (my) {
            return NAMESPACE + '-pos-' + (my || this.options.position.my).abbrev();
        };

        PROTOTYPE.reposition = function (event, effect) {
            if (!this.rendered || this.positioning || this.destroyed) { return this; }

            // Set positioning flag
            this.positioning = TRUE;

            var cache = this.cache,
                tooltip = this.tooltip,
                posOptions = this.options.position,
                target = posOptions.target,
                my = posOptions.my,
                at = posOptions.at,
                viewport = posOptions.viewport,
                container = posOptions.container,
                adjust = posOptions.adjust,
                method = adjust.method.split(' '),
                tooltipWidth = tooltip.outerWidth(FALSE),
                tooltipHeight = tooltip.outerHeight(FALSE),
                targetWidth = 0,
                targetHeight = 0,
                type = tooltip.css('position'),
                position = { left: 0, top: 0 },
                visible = tooltip[0].offsetWidth > 0,
                isScroll = event && event.type === 'scroll',
                win = $(window),
                doc = container[0].ownerDocument,
                mouse = this.mouse,
                pluginCalculations, offset, adjusted, newClass;

            // Check if absolute position was passed
            if ($.isArray(target) && target.length === 2) {
                // Force left top and set position
                at = { x: LEFT, y: TOP };
                position = { left: target[0], top: target[1] };
            }

                // Check if mouse was the target
            else if (target === 'mouse') {
                // Force left top to allow flipping
                at = { x: LEFT, y: TOP };

                // Use the mouse origin that caused the show event, if distance hiding is enabled
                if ((!adjust.mouse || this.options.hide.distance) && cache.origin && cache.origin.pageX) {
                    event = cache.origin;
                }

                    // Use cached event for resize/scroll events
                else if (!event || (event && (event.type === 'resize' || event.type === 'scroll'))) {
                    event = cache.event;
                }

                    // Otherwise, use the cached mouse coordinates if available
                else if (mouse && mouse.pageX) {
                    event = mouse;
                }

                // Calculate body and container offset and take them into account below
                if (type !== 'static') { position = container.offset(); }
                if (doc.body.offsetWidth !== (window.innerWidth || doc.documentElement.clientWidth)) {
                    offset = $(document.body).offset();
                }

                // Use event coordinates for position
                position = {
                    left: event.pageX - position.left + (offset && offset.left || 0),
                    top: event.pageY - position.top + (offset && offset.top || 0)
                };

                // Scroll events are a pain, some browsers
                if (adjust.mouse && isScroll && mouse) {
                    position.left -= (mouse.scrollX || 0) - win.scrollLeft();
                    position.top -= (mouse.scrollY || 0) - win.scrollTop();
                }
            }

                // Target wasn't mouse or absolute...
            else {
                // Check if event targetting is being used
                if (target === 'event') {
                    if (event && event.target && event.type !== 'scroll' && event.type !== 'resize') {
                        cache.target = $(event.target);
                    }
                    else if (!event.target) {
                        cache.target = this.elements.target;
                    }
                }
                else if (target !== 'event') {
                    cache.target = $(target.jquery ? target : this.elements.target);
                }
                target = cache.target;

                // Parse the target into a jQuery object and make sure there's an element present
                target = $(target).eq(0);
                if (target.length === 0) { return this; }

                    // Check if window or document is the target
                else if (target[0] === document || target[0] === window) {
                    targetWidth = BROWSER.iOS ? window.innerWidth : target.width();
                    targetHeight = BROWSER.iOS ? window.innerHeight : target.height();

                    if (target[0] === window) {
                        position = {
                            top: (viewport || target).scrollTop(),
                            left: (viewport || target).scrollLeft()
                        };
                    }
                }

                    // Check if the target is an <AREA> element
                else if (PLUGINS.imagemap && target.is('area')) {
                    pluginCalculations = PLUGINS.imagemap(this, target, at, PLUGINS.viewport ? method : FALSE);
                }

                    // Check if the target is an SVG element
                else if (PLUGINS.svg && target && target[0].ownerSVGElement) {
                    pluginCalculations = PLUGINS.svg(this, target, at, PLUGINS.viewport ? method : FALSE);
                }

                    // Otherwise use regular jQuery methods
                else {
                    targetWidth = target.outerWidth(FALSE);
                    targetHeight = target.outerHeight(FALSE);
                    position = target.offset();
                }

                // Parse returned plugin values into proper variables
                if (pluginCalculations) {
                    targetWidth = pluginCalculations.width;
                    targetHeight = pluginCalculations.height;
                    offset = pluginCalculations.offset;
                    position = pluginCalculations.position;
                }

                // Adjust position to take into account offset parents
                position = this.reposition.offset(target, position, container);

                // Adjust for position.fixed tooltips (and also iOS scroll bug in v3.2-4.0 & v4.3-4.3.2)
                if ((BROWSER.iOS > 3.1 && BROWSER.iOS < 4.1) ||
                    (BROWSER.iOS >= 4.3 && BROWSER.iOS < 4.33) ||
                    (!BROWSER.iOS && type === 'fixed')
                ) {
                    position.left -= win.scrollLeft();
                    position.top -= win.scrollTop();
                }

                // Adjust position relative to target
                if (!pluginCalculations || (pluginCalculations && pluginCalculations.adjustable !== FALSE)) {
                    position.left += at.x === RIGHT ? targetWidth : at.x === CENTER ? targetWidth / 2 : 0;
                    position.top += at.y === BOTTOM ? targetHeight : at.y === CENTER ? targetHeight / 2 : 0;
                }
            }

            // Adjust position relative to tooltip
            position.left += adjust.x + (my.x === RIGHT ? -tooltipWidth : my.x === CENTER ? -tooltipWidth / 2 : 0);
            position.top += adjust.y + (my.y === BOTTOM ? -tooltipHeight : my.y === CENTER ? -tooltipHeight / 2 : 0);

            // Use viewport adjustment plugin if enabled
            if (PLUGINS.viewport) {
                adjusted = position.adjusted = PLUGINS.viewport(
                    this, position, posOptions, targetWidth, targetHeight, tooltipWidth, tooltipHeight
                );

                // Apply offsets supplied by positioning plugin (if used)
                if (offset && adjusted.left) { position.left += offset.left; }
                if (offset && adjusted.top) { position.top += offset.top; }

                // Apply any new 'my' position
                if (adjusted.my) { this.position.my = adjusted.my; }
            }

                // Viewport adjustment is disabled, set values to zero
            else { position.adjusted = { left: 0, top: 0 }; }

            // Set tooltip position class if it's changed
            if (cache.posClass !== (newClass = this._createPosClass(this.position.my))) {
                tooltip.removeClass(cache.posClass).addClass((cache.posClass = newClass));
            }

            // tooltipmove event
            if (!this._trigger('move', [position, viewport.elem || viewport], event)) { return this; }
            delete position.adjusted;

            // If effect is disabled, target it mouse, no animation is defined or positioning gives NaN out, set CSS directly
            if (effect === FALSE || !visible || isNaN(position.left) || isNaN(position.top) || target === 'mouse' || !$.isFunction(posOptions.effect)) {
                tooltip.css(position);
            }

                // Use custom function if provided
            else if ($.isFunction(posOptions.effect)) {
                posOptions.effect.call(tooltip, this, $.extend({}, position));
                tooltip.queue(function (next) {
                    // Reset attributes to avoid cross-browser rendering bugs
                    $(this).css({ opacity: '', height: '' });
                    if (BROWSER.ie) { this.style.removeAttribute('filter'); }

                    next();
                });
            }

            // Set positioning flag
            this.positioning = FALSE;

            return this;
        };

        // Custom (more correct for qTip!) offset calculator
        PROTOTYPE.reposition.offset = function (elem, pos, container) {
            if (!container[0]) { return pos; }

            var ownerDocument = $(elem[0].ownerDocument),
                quirks = !!BROWSER.ie && document.compatMode !== 'CSS1Compat',
                parent = container[0],
                scrolled, position, parentOffset, overflow;

            function scroll(e, i) {
                pos.left += i * e.scrollLeft();
                pos.top += i * e.scrollTop();
            }

            // Compensate for non-static containers offset
            do {
                if ((position = $.css(parent, 'position')) !== 'static') {
                    if (position === 'fixed') {
                        parentOffset = parent.getBoundingClientRect();
                        scroll(ownerDocument, -1);
                    }
                    else {
                        parentOffset = $(parent).position();
                        parentOffset.left += (parseFloat($.css(parent, 'borderLeftWidth')) || 0);
                        parentOffset.top += (parseFloat($.css(parent, 'borderTopWidth')) || 0);
                    }

                    pos.left -= parentOffset.left + (parseFloat($.css(parent, 'marginLeft')) || 0);
                    pos.top -= parentOffset.top + (parseFloat($.css(parent, 'marginTop')) || 0);

                    // If this is the first parent element with an overflow of "scroll" or "auto", store it
                    if (!scrolled && (overflow = $.css(parent, 'overflow')) !== 'hidden' && overflow !== 'visible') { scrolled = $(parent); }
                }
            }
            while ((parent = parent.offsetParent));

            // Compensate for containers scroll if it also has an offsetParent (or in IE quirks mode)
            if (scrolled && (scrolled[0] !== ownerDocument[0] || quirks)) {
                scroll(scrolled, 1);
            }

            return pos;
        };

        // Corner class
        var C = (CORNER = PROTOTYPE.reposition.Corner = function (corner, forceY) {
            corner = ('' + corner).replace(/([A-Z])/, ' $1').replace(/middle/gi, CENTER).toLowerCase();
            this.x = (corner.match(/left|right/i) || corner.match(/center/) || ['inherit'])[0].toLowerCase();
            this.y = (corner.match(/top|bottom|center/i) || ['inherit'])[0].toLowerCase();
            this.forceY = !!forceY;

            var f = corner.charAt(0);
            this.precedance = (f === 't' || f === 'b' ? Y : X);
        }).prototype;

        C.invert = function (z, center) {
            this[z] = this[z] === LEFT ? RIGHT : this[z] === RIGHT ? LEFT : center || this[z];
        };

        C.string = function (join) {
            var x = this.x, y = this.y;

            var result = x !== y ?
                (x === 'center' || y !== 'center' && (this.precedance === Y || this.forceY) ?
                    [y, x] : [x, y]
                ) :
            [x];

            return join !== false ? result.join(' ') : result;
        };

        C.abbrev = function () {
            var result = this.string(false);
            return result[0].charAt(0) + (result[1] && result[1].charAt(0) || '');
        };

        C.clone = function () {
            return new CORNER(this.string(), this.forceY);
        };

        ;
        PROTOTYPE.toggle = function (state, event) {
            var cache = this.cache,
                options = this.options,
                tooltip = this.tooltip;

            // Try to prevent flickering when tooltip overlaps show element
            if (event) {
                if ((/over|enter/).test(event.type) && cache.event && (/out|leave/).test(cache.event.type) &&
                    options.show.target.add(event.target).length === options.show.target.length &&
                    tooltip.has(event.relatedTarget).length) {
                    return this;
                }

                // Cache event
                cache.event = $.event.fix(event);
            }

            // If we're currently waiting and we've just hidden... stop it
            this.waiting && !state && (this.hiddenDuringWait = TRUE);

            // Render the tooltip if showing and it isn't already
            if (!this.rendered) { return state ? this.render(1) : this; }
            else if (this.destroyed || this.disabled) { return this; }

            var type = state ? 'show' : 'hide',
                opts = this.options[type],
                otherOpts = this.options[!state ? 'show' : 'hide'],
                posOptions = this.options.position,
                contentOptions = this.options.content,
                width = this.tooltip.css('width'),
                visible = this.tooltip.is(':visible'),
                animate = state || opts.target.length === 1,
                sameTarget = !event || opts.target.length < 2 || cache.target[0] === event.target,
                identicalState, allow, showEvent, delay, after;

            // Detect state if valid one isn't provided
            if ((typeof state).search('boolean|number')) { state = !visible; }

            // Check if the tooltip is in an identical state to the new would-be state
            identicalState = !tooltip.is(':animated') && visible === state && sameTarget;

            // Fire tooltip(show/hide) event and check if destroyed
            allow = !identicalState ? !!this._trigger(type, [90]) : NULL;

            // Check to make sure the tooltip wasn't destroyed in the callback
            if (this.destroyed) { return this; }

            // If the user didn't stop the method prematurely and we're showing the tooltip, focus it
            if (allow !== FALSE && state) { this.focus(event); }

            // If the state hasn't changed or the user stopped it, return early
            if (!allow || identicalState) { return this; }

            // Set ARIA hidden attribute
            $.attr(tooltip[0], 'aria-hidden', !!!state);

            // Execute state specific properties
            if (state) {
                // Store show origin coordinates
                this.mouse && (cache.origin = $.event.fix(this.mouse));

                // Update tooltip content & title if it's a dynamic function
                if ($.isFunction(contentOptions.text)) { this._updateContent(contentOptions.text, FALSE); }
                if ($.isFunction(contentOptions.title)) { this._updateTitle(contentOptions.title, FALSE); }

                // Cache mousemove events for positioning purposes (if not already tracking)
                if (!trackingBound && posOptions.target === 'mouse' && posOptions.adjust.mouse) {
                    $(document).bind('mousemove.' + NAMESPACE, this._storeMouse);
                    trackingBound = TRUE;
                }

                // Update the tooltip position (set width first to prevent viewport/max-width issues)
                if (!width) { tooltip.css('width', tooltip.outerWidth(FALSE)); }
                this.reposition(event, arguments[2]);
                if (!width) { tooltip.css('width', ''); }

                // Hide other tooltips if tooltip is solo
                if (!!opts.solo) {
                    (typeof opts.solo === 'string' ? $(opts.solo) : $(SELECTOR, opts.solo))
                        .not(tooltip).not(opts.target).qtip('hide', $.Event('tooltipsolo'));
                }
            }
            else {
                // Clear show timer if we're hiding
                clearTimeout(this.timers.show);

                // Remove cached origin on hide
                delete cache.origin;

                // Remove mouse tracking event if not needed (all tracking qTips are hidden)
                if (trackingBound && !$(SELECTOR + '[tracking="true"]:visible', opts.solo).not(tooltip).length) {
                    $(document).unbind('mousemove.' + NAMESPACE);
                    trackingBound = FALSE;
                }

                // Blur the tooltip
                this.blur(event);
            }

            // Define post-animation, state specific properties
            after = $.proxy(function () {
                if (state) {
                    // Prevent antialias from disappearing in IE by removing filter
                    if (BROWSER.ie) { tooltip[0].style.removeAttribute('filter'); }

                    // Remove overflow setting to prevent tip bugs
                    tooltip.css('overflow', '');

                    // Autofocus elements if enabled
                    if ('string' === typeof opts.autofocus) {
                        $(this.options.show.autofocus, tooltip).focus();
                    }

                    // If set, hide tooltip when inactive for delay period
                    this.options.show.target.trigger('qtip-' + this.id + '-inactive');
                }
                else {
                    // Reset CSS states
                    tooltip.css({
                        display: '',
                        visibility: '',
                        opacity: '',
                        left: '',
                        top: ''
                    });
                }

                // tooltipvisible/tooltiphidden events
                this._trigger(state ? 'visible' : 'hidden');
            }, this);

            // If no effect type is supplied, use a simple toggle
            if (opts.effect === FALSE || animate === FALSE) {
                tooltip[type]();
                after();
            }

                // Use custom function if provided
            else if ($.isFunction(opts.effect)) {
                tooltip.stop(1, 1);
                opts.effect.call(tooltip, this);
                tooltip.queue('fx', function (n) {
                    after(); n();
                });
            }

                // Use basic fade function by default
            else { tooltip.fadeTo(90, state ? 1 : 0, after); }

            // If inactive hide method is set, active it
            if (state) { opts.target.trigger('qtip-' + this.id + '-inactive'); }

            return this;
        };

        PROTOTYPE.show = function (event) { return this.toggle(TRUE, event); };

        PROTOTYPE.hide = function (event) { return this.toggle(FALSE, event); };
        ; PROTOTYPE.focus = function (event) {
            if (!this.rendered || this.destroyed) { return this; }

            var qtips = $(SELECTOR),
                tooltip = this.tooltip,
                curIndex = parseInt(tooltip[0].style.zIndex, 10),
                newIndex = QTIP.zindex + qtips.length,
                focusedElem;

            // Only update the z-index if it has changed and tooltip is not already focused
            if (!tooltip.hasClass(CLASS_FOCUS)) {
                // tooltipfocus event
                if (this._trigger('focus', [newIndex], event)) {
                    // Only update z-index's if they've changed
                    if (curIndex !== newIndex) {
                        // Reduce our z-index's and keep them properly ordered
                        qtips.each(function () {
                            if (this.style.zIndex > curIndex) {
                                this.style.zIndex = this.style.zIndex - 1;
                            }
                        });

                        // Fire blur event for focused tooltip
                        qtips.filter('.' + CLASS_FOCUS).qtip('blur', event);
                    }

                    // Set the new z-index
                    tooltip.addClass(CLASS_FOCUS)[0].style.zIndex = newIndex;
                }
            }

            return this;
        };

        PROTOTYPE.blur = function (event) {
            if (!this.rendered || this.destroyed) { return this; }

            // Set focused status to FALSE
            this.tooltip.removeClass(CLASS_FOCUS);

            // tooltipblur event
            this._trigger('blur', [this.tooltip.css('zIndex')], event);

            return this;
        };
        ; PROTOTYPE.disable = function (state) {
            if (this.destroyed) { return this; }

            // If 'toggle' is passed, toggle the current state
            if (state === 'toggle') {
                state = !(this.rendered ? this.tooltip.hasClass(CLASS_DISABLED) : this.disabled);
            }

                // Disable if no state passed
            else if ('boolean' !== typeof state) {
                state = TRUE;
            }

            if (this.rendered) {
                this.tooltip.toggleClass(CLASS_DISABLED, state)
                    .attr('aria-disabled', state);
            }

            this.disabled = !!state;

            return this;
        };

        PROTOTYPE.enable = function () { return this.disable(FALSE); };
        ; PROTOTYPE._createButton = function () {
            var self = this,
                elements = this.elements,
                tooltip = elements.tooltip,
                button = this.options.content.button,
                isString = typeof button === 'string',
                close = isString ? button : 'Close tooltip';

            if (elements.button) { elements.button.remove(); }

            // Use custom button if one was supplied by user, else use default
            if (button.jquery) {
                elements.button = button;
            }
            else {
                elements.button = $('<a />', {
                    'class': 'qtip-close ' + (this.options.style.widget ? '' : NAMESPACE + '-icon'),
                    'title': close,
                    'aria-label': close
                })
                .prepend(
                    $('<span />', {
                        'class': 'ui-icon ui-icon-close',
                        'html': '&times;'
                    })
                );
            }

            // Create button and setup attributes
            elements.button.appendTo(elements.titlebar || tooltip)
                .attr('role', 'button')
                .click(function (event) {
                    if (!tooltip.hasClass(CLASS_DISABLED)) { self.hide(event); }
                    return FALSE;
                });
        };

        PROTOTYPE._updateButton = function (button) {
            // Make sure tooltip is rendered and if not, return
            if (!this.rendered) { return FALSE; }

            var elem = this.elements.button;
            if (button) { this._createButton(); }
            else { elem.remove(); }
        };
        ;// Widget class creator
        function createWidgetClass(cls) {
            return WIDGET.concat('').join(cls ? '-' + cls + ' ' : ' ');
        }

        // Widget class setter method
        PROTOTYPE._setWidget = function () {
            var on = this.options.style.widget,
                elements = this.elements,
                tooltip = elements.tooltip,
                disabled = tooltip.hasClass(CLASS_DISABLED);

            tooltip.removeClass(CLASS_DISABLED);
            CLASS_DISABLED = on ? 'ui-state-disabled' : 'qtip-disabled';
            tooltip.toggleClass(CLASS_DISABLED, disabled);

            tooltip.toggleClass('ui-helper-reset ' + createWidgetClass(), on).toggleClass(CLASS_DEFAULT, this.options.style.def && !on);

            if (elements.content) {
                elements.content.toggleClass(createWidgetClass('content'), on);
            }
            if (elements.titlebar) {
                elements.titlebar.toggleClass(createWidgetClass('header'), on);
            }
            if (elements.button) {
                elements.button.toggleClass(NAMESPACE + '-icon', !on);
            }
        };
        ; function delay(callback, duration) {
            // If tooltip has displayed, start hide timer
            if (duration > 0) {
                return setTimeout(
                    $.proxy(callback, this), duration
                );
            }
            else { callback.call(this); }
        }

        function showMethod(event) {
            if (this.tooltip.hasClass(CLASS_DISABLED)) { return; }

            // Clear hide timers
            clearTimeout(this.timers.show);
            clearTimeout(this.timers.hide);

            // Start show timer
            this.timers.show = delay.call(this,
                function () { this.toggle(TRUE, event); },
                this.options.show.delay
            );
        }

        function hideMethod(event) {
            if (this.tooltip.hasClass(CLASS_DISABLED) || this.destroyed) { return; }

            // Check if new target was actually the tooltip element
            var relatedTarget = $(event.relatedTarget),
                ontoTooltip = relatedTarget.closest(SELECTOR)[0] === this.tooltip[0],
                ontoTarget = relatedTarget[0] === this.options.show.target[0];

            // Clear timers and stop animation queue
            clearTimeout(this.timers.show);
            clearTimeout(this.timers.hide);

            // Prevent hiding if tooltip is fixed and event target is the tooltip.
            // Or if mouse positioning is enabled and cursor momentarily overlaps
            if (this !== relatedTarget[0] &&
                (this.options.position.target === 'mouse' && ontoTooltip) ||
                (this.options.hide.fixed && (
                    (/mouse(out|leave|move)/).test(event.type) && (ontoTooltip || ontoTarget))
                )) {
                try {
                    event.preventDefault();
                    event.stopImmediatePropagation();
                } catch (e) { }

                return;
            }

            // If tooltip has displayed, start hide timer
            this.timers.hide = delay.call(this,
                function () { this.toggle(FALSE, event); },
                this.options.hide.delay,
                this
            );
        }

        function inactiveMethod(event) {
            if (this.tooltip.hasClass(CLASS_DISABLED) || !this.options.hide.inactive) { return; }

            // Clear timer
            clearTimeout(this.timers.inactive);

            this.timers.inactive = delay.call(this,
                function () { this.hide(event); },
                this.options.hide.inactive
            );
        }

        function repositionMethod(event) {
            if (this.rendered && this.tooltip[0].offsetWidth > 0) { this.reposition(event); }
        }

        // Store mouse coordinates
        PROTOTYPE._storeMouse = function (event) {
            (this.mouse = $.event.fix(event)).type = 'mousemove';
            return this;
        };

        // Bind events
        PROTOTYPE._bind = function (targets, events, method, suffix, context) {
            if (!targets || !method || !events.length) { return; }
            var ns = '.' + this._id + (suffix ? '-' + suffix : '');
            $(targets).bind(
                (events.split ? events : events.join(ns + ' ')) + ns,
                $.proxy(method, context || this)
            );
            return this;
        };
        PROTOTYPE._unbind = function (targets, suffix) {
            targets && $(targets).unbind('.' + this._id + (suffix ? '-' + suffix : ''));
            return this;
        };

        // Global delegation helper
        function delegate(selector, events, method) {
            $(document.body).delegate(selector,
                (events.split ? events : events.join('.' + NAMESPACE + ' ')) + '.' + NAMESPACE,
                function () {
                    var api = QTIP.api[$.attr(this, ATTR_ID)];
                    api && !api.disabled && method.apply(api, arguments);
                }
            );
        }
        // Event trigger
        PROTOTYPE._trigger = function (type, args, event) {
            var callback = $.Event('tooltip' + type);
            callback.originalEvent = (event && $.extend({}, event)) || this.cache.event || NULL;

            this.triggering = type;
            this.tooltip.trigger(callback, [this].concat(args || []));
            this.triggering = FALSE;

            return !callback.isDefaultPrevented();
        };

        PROTOTYPE._bindEvents = function (showEvents, hideEvents, showTargets, hideTargets, showMethod, hideMethod) {
            // Get tasrgets that lye within both
            var similarTargets = showTargets.filter(hideTargets).add(hideTargets.filter(showTargets)),
                toggleEvents = [];

            // If hide and show targets are the same...
            if (similarTargets.length) {

                // Filter identical show/hide events
                $.each(hideEvents, function (i, type) {
                    var showIndex = $.inArray(type, showEvents);

                    // Both events are identical, remove from both hide and show events
                    // and append to toggleEvents
                    showIndex > -1 && toggleEvents.push(showEvents.splice(showIndex, 1)[0]);
                });

                // Toggle events are special case of identical show/hide events, which happen in sequence
                if (toggleEvents.length) {
                    // Bind toggle events to the similar targets
                    this._bind(similarTargets, toggleEvents, function (event) {
                        var state = this.rendered ? this.tooltip[0].offsetWidth > 0 : false;
                        (state ? hideMethod : showMethod).call(this, event);
                    });

                    // Remove the similar targets from the regular show/hide bindings
                    showTargets = showTargets.not(similarTargets);
                    hideTargets = hideTargets.not(similarTargets);
                }
            }

            // Apply show/hide/toggle events
            this._bind(showTargets, showEvents, showMethod);
            this._bind(hideTargets, hideEvents, hideMethod);
        };

        PROTOTYPE._assignInitialEvents = function (event) {
            var options = this.options,
                showTarget = options.show.target,
                hideTarget = options.hide.target,
                showEvents = options.show.event ? $.trim('' + options.show.event).split(' ') : [],
                hideEvents = options.hide.event ? $.trim('' + options.hide.event).split(' ') : [];

            // Catch remove/removeqtip events on target element to destroy redundant tooltips
            this._bind(this.elements.target, ['remove', 'removeqtip'], function (event) {
                this.destroy(true);
            }, 'destroy');

            /*
             * Make sure hoverIntent functions properly by using mouseleave as a hide event if
             * mouseenter/mouseout is used for show.event, even if it isn't in the users options.
             */
            if (/mouse(over|enter)/i.test(options.show.event) && !/mouse(out|leave)/i.test(options.hide.event)) {
                hideEvents.push('mouseleave');
            }

            /*
             * Also make sure initial mouse targetting works correctly by caching mousemove coords
             * on show targets before the tooltip has rendered. Also set onTarget when triggered to
             * keep mouse tracking working.
             */
            this._bind(showTarget, 'mousemove', function (event) {
                this._storeMouse(event);
                this.cache.onTarget = TRUE;
            });

            // Define hoverIntent function
            function hoverIntent(event) {
                // Only continue if tooltip isn't disabled
                if (this.disabled || this.destroyed) { return FALSE; }

                // Cache the event data
                this.cache.event = event && $.event.fix(event);
                this.cache.target = event && $(event.target);

                // Start the event sequence
                clearTimeout(this.timers.show);
                this.timers.show = delay.call(this,
                    function () { this.render(typeof event === 'object' || options.show.ready); },
                    options.prerender ? 0 : options.show.delay
                );
            }

            // Filter and bind events
            this._bindEvents(showEvents, hideEvents, showTarget, hideTarget, hoverIntent, function () {
                if (!this.timers) { return FALSE; }
                clearTimeout(this.timers.show);
            });

            // Prerendering is enabled, create tooltip now
            if (options.show.ready || options.prerender) { hoverIntent.call(this, event); }
        };

        // Event assignment method
        PROTOTYPE._assignEvents = function () {
            var self = this,
                options = this.options,
                posOptions = options.position,

                tooltip = this.tooltip,
                showTarget = options.show.target,
                hideTarget = options.hide.target,
                containerTarget = posOptions.container,
                viewportTarget = posOptions.viewport,
                documentTarget = $(document),
                bodyTarget = $(document.body),
                windowTarget = $(window),

                showEvents = options.show.event ? $.trim('' + options.show.event).split(' ') : [],
                hideEvents = options.hide.event ? $.trim('' + options.hide.event).split(' ') : [];


            // Assign passed event callbacks
            $.each(options.events, function (name, callback) {
                self._bind(tooltip, name === 'toggle' ? ['tooltipshow', 'tooltiphide'] : ['tooltip' + name], callback, null, tooltip);
            });

            // Hide tooltips when leaving current window/frame (but not select/option elements)
            if (/mouse(out|leave)/i.test(options.hide.event) && options.hide.leave === 'window') {
                this._bind(documentTarget, ['mouseout', 'blur'], function (event) {
                    if (!/select|option/.test(event.target.nodeName) && !event.relatedTarget) {
                        this.hide(event);
                    }
                });
            }

            // Enable hide.fixed by adding appropriate class
            if (options.hide.fixed) {
                hideTarget = hideTarget.add(tooltip.addClass(CLASS_FIXED));
            }

                /*
                 * Make sure hoverIntent functions properly by using mouseleave to clear show timer if
                 * mouseenter/mouseout is used for show.event, even if it isn't in the users options.
                 */
            else if (/mouse(over|enter)/i.test(options.show.event)) {
                this._bind(hideTarget, 'mouseleave', function () {
                    clearTimeout(this.timers.show);
                });
            }

            // Hide tooltip on document mousedown if unfocus events are enabled
            if (('' + options.hide.event).indexOf('unfocus') > -1) {
                this._bind(containerTarget.closest('html'), ['mousedown', 'touchstart'], function (event) {
                    var elem = $(event.target),
                        enabled = this.rendered && !this.tooltip.hasClass(CLASS_DISABLED) && this.tooltip[0].offsetWidth > 0,
                        isAncestor = elem.parents(SELECTOR).filter(this.tooltip[0]).length > 0;

                    if (elem[0] !== this.target[0] && elem[0] !== this.tooltip[0] && !isAncestor &&
                        !this.target.has(elem[0]).length && enabled
                    ) {
                        this.hide(event);
                    }
                });
            }

            // Check if the tooltip hides when inactive
            if ('number' === typeof options.hide.inactive) {
                // Bind inactive method to show target(s) as a custom event
                this._bind(showTarget, 'qtip-' + this.id + '-inactive', inactiveMethod, 'inactive');

                // Define events which reset the 'inactive' event handler
                this._bind(hideTarget.add(tooltip), QTIP.inactiveEvents, inactiveMethod);
            }

            // Filter and bind events
            this._bindEvents(showEvents, hideEvents, showTarget, hideTarget, showMethod, hideMethod);

            // Mouse movement bindings
            this._bind(showTarget.add(tooltip), 'mousemove', function (event) {
                // Check if the tooltip hides when mouse is moved a certain distance
                if ('number' === typeof options.hide.distance) {
                    var origin = this.cache.origin || {},
                        limit = this.options.hide.distance,
                        abs = Math.abs;

                    // Check if the movement has gone beyond the limit, and hide it if so
                    if (abs(event.pageX - origin.pageX) >= limit || abs(event.pageY - origin.pageY) >= limit) {
                        this.hide(event);
                    }
                }

                // Cache mousemove coords on show targets
                this._storeMouse(event);
            });

            // Mouse positioning events
            if (posOptions.target === 'mouse') {
                // If mouse adjustment is on...
                if (posOptions.adjust.mouse) {
                    // Apply a mouseleave event so we don't get problems with overlapping
                    if (options.hide.event) {
                        // Track if we're on the target or not
                        this._bind(showTarget, ['mouseenter', 'mouseleave'], function (event) {
                            if (!this.cache) { return FALSE; }
                            this.cache.onTarget = event.type === 'mouseenter';
                        });
                    }

                    // Update tooltip position on mousemove
                    this._bind(documentTarget, 'mousemove', function (event) {
                        // Update the tooltip position only if the tooltip is visible and adjustment is enabled
                        if (this.rendered && this.cache.onTarget && !this.tooltip.hasClass(CLASS_DISABLED) && this.tooltip[0].offsetWidth > 0) {
                            this.reposition(event);
                        }
                    });
                }
            }

            // Adjust positions of the tooltip on window resize if enabled
            if (posOptions.adjust.resize || viewportTarget.length) {
                this._bind($.event.special.resize ? viewportTarget : windowTarget, 'resize', repositionMethod);
            }

            // Adjust tooltip position on scroll of the window or viewport element if present
            if (posOptions.adjust.scroll) {
                this._bind(windowTarget.add(posOptions.container), 'scroll', repositionMethod);
            }
        };

        // Un-assignment method
        PROTOTYPE._unassignEvents = function () {
            var options = this.options,
                showTargets = options.show.target,
                hideTargets = options.hide.target,
                targets = $.grep([
                    this.elements.target[0],
                    this.rendered && this.tooltip[0],
                    options.position.container[0],
                    options.position.viewport[0],
                    options.position.container.closest('html')[0], // unfocus
                    window,
                    document
                ], function (i) {
                    return typeof i === 'object';
                });

            // Add show and hide targets if they're valid
            if (showTargets && showTargets.toArray) {
                targets = targets.concat(showTargets.toArray());
            }
            if (hideTargets && hideTargets.toArray) {
                targets = targets.concat(hideTargets.toArray());
            }

            // Unbind the events
            this._unbind(targets)
                ._unbind(targets, 'destroy')
                ._unbind(targets, 'inactive');
        };

        // Apply common event handlers using delegate (avoids excessive .bind calls!)
        $(function () {
            delegate(SELECTOR, ['mouseenter', 'mouseleave'], function (event) {
                var state = event.type === 'mouseenter',
                    tooltip = $(event.currentTarget),
                    target = $(event.relatedTarget || event.target),
                    options = this.options;

                // On mouseenter...
                if (state) {
                    // Focus the tooltip on mouseenter (z-index stacking)
                    this.focus(event);

                    // Clear hide timer on tooltip hover to prevent it from closing
                    tooltip.hasClass(CLASS_FIXED) && !tooltip.hasClass(CLASS_DISABLED) && clearTimeout(this.timers.hide);
                }

                    // On mouseleave...
                else {
                    // When mouse tracking is enabled, hide when we leave the tooltip and not onto the show target (if a hide event is set)
                    if (options.position.target === 'mouse' && options.position.adjust.mouse &&
                        options.hide.event && options.show.target && !target.closest(options.show.target[0]).length) {
                        this.hide(event);
                    }
                }

                // Add hover class
                tooltip.toggleClass(CLASS_HOVER, state);
            });

            // Define events which reset the 'inactive' event handler
            delegate('[' + ATTR_ID + ']', INACTIVE_EVENTS, inactiveMethod);
        });
        ;// Initialization method
        function init(elem, id, opts) {
            var obj, posOptions, attr, config, title,

            // Setup element references
            docBody = $(document.body),

            // Use document body instead of document element if needed
            newTarget = elem[0] === document ? docBody : elem,

            // Grab metadata from element if plugin is present
            metadata = (elem.metadata) ? elem.metadata(opts.metadata) : NULL,

            // If metadata type if HTML5, grab 'name' from the object instead, or use the regular data object otherwise
            metadata5 = opts.metadata.type === 'html5' && metadata ? metadata[opts.metadata.name] : NULL,

            // Grab data from metadata.name (or data-qtipopts as fallback) using .data() method,
            html5 = elem.data(opts.metadata.name || 'qtipopts');

            // If we don't get an object returned attempt to parse it manualyl without parseJSON
            try { html5 = typeof html5 === 'string' ? $.parseJSON(html5) : html5; } catch (e) { }

            // Merge in and sanitize metadata
            config = $.extend(TRUE, {}, QTIP.defaults, opts,
                typeof html5 === 'object' ? sanitizeOptions(html5) : NULL,
                sanitizeOptions(metadata5 || metadata));

            // Re-grab our positioning options now we've merged our metadata and set id to passed value
            posOptions = config.position;
            config.id = id;

            // Setup missing content if none is detected
            if ('boolean' === typeof config.content.text) {
                attr = elem.attr(config.content.attr);

                // Grab from supplied attribute if available
                if (config.content.attr !== FALSE && attr) { config.content.text = attr; }

                    // No valid content was found, abort render
                else { return FALSE; }
            }

            // Setup target options
            if (!posOptions.container.length) { posOptions.container = docBody; }
            if (posOptions.target === FALSE) { posOptions.target = newTarget; }
            if (config.show.target === FALSE) { config.show.target = newTarget; }
            if (config.show.solo === TRUE) { config.show.solo = posOptions.container.closest('body'); }
            if (config.hide.target === FALSE) { config.hide.target = newTarget; }
            if (config.position.viewport === TRUE) { config.position.viewport = posOptions.container; }

            // Ensure we only use a single container
            posOptions.container = posOptions.container.eq(0);

            // Convert position corner values into x and y strings
            posOptions.at = new CORNER(posOptions.at, TRUE);
            posOptions.my = new CORNER(posOptions.my);

            // Destroy previous tooltip if overwrite is enabled, or skip element if not
            if (elem.data(NAMESPACE)) {
                if (config.overwrite) {
                    elem.qtip('destroy', true);
                }
                else if (config.overwrite === FALSE) {
                    return FALSE;
                }
            }

            // Add has-qtip attribute
            elem.attr(ATTR_HAS, id);

            // Remove title attribute and store it if present
            if (config.suppress && (title = elem.attr('title'))) {
                // Final attr call fixes event delegatiom and IE default tooltip showing problem
                elem.removeAttr('title').attr(oldtitle, title).attr('title', '');
            }

            // Initialize the tooltip and add API reference
            obj = new QTip(elem, config, id, !!attr);
            elem.data(NAMESPACE, obj);

            return obj;
        }

        // jQuery $.fn extension method
        QTIP = $.fn.qtip = function (options, notation, newValue) {
            var command = ('' + options).toLowerCase(), // Parse command
                returned = NULL,
                args = $.makeArray(arguments).slice(1),
                event = args[args.length - 1],
                opts = this[0] ? $.data(this[0], NAMESPACE) : NULL;

            // Check for API request
            if ((!arguments.length && opts) || command === 'api') {
                return opts;
            }

                // Execute API command if present
            else if ('string' === typeof options) {
                this.each(function () {
                    var api = $.data(this, NAMESPACE);
                    if (!api) { return TRUE; }

                    // Cache the event if possible
                    if (event && event.timeStamp) { api.cache.event = event; }

                    // Check for specific API commands
                    if (notation && (command === 'option' || command === 'options')) {
                        if (newValue !== undefined || $.isPlainObject(notation)) {
                            api.set(notation, newValue);
                        }
                        else {
                            returned = api.get(notation);
                            return FALSE;
                        }
                    }

                        // Execute API command
                    else if (api[command]) {
                        api[command].apply(api, args);
                    }
                });

                return returned !== NULL ? returned : this;
            }

                // No API commands. validate provided options and setup qTips
            else if ('object' === typeof options || !arguments.length) {
                // Sanitize options first
                opts = sanitizeOptions($.extend(TRUE, {}, options));

                return this.each(function (i) {
                    var api, id;

                    // Find next available ID, or use custom ID if provided
                    id = $.isArray(opts.id) ? opts.id[i] : opts.id;
                    id = !id || id === FALSE || id.length < 1 || QTIP.api[id] ? QTIP.nextid++ : id;

                    // Initialize the qTip and re-grab newly sanitized options
                    api = init($(this), id, opts);
                    if (api === FALSE) { return TRUE; }
                    else { QTIP.api[id] = api; }

                    // Initialize plugins
                    $.each(PLUGINS, function () {
                        if (this.initialize === 'initialize') { this(api); }
                    });

                    // Assign initial pre-render events
                    api._assignInitialEvents(event);
                });
            }
        };

        // Expose class
        $.qtip = QTip;

        // Populated in render method
        QTIP.api = {};
        ; $.each({
            /* Allow other plugins to successfully retrieve the title of an element with a qTip applied */
            attr: function (attr, val) {
                if (this.length) {
                    var self = this[0],
                        title = 'title',
                        api = $.data(self, 'qtip');

                    if (attr === title && api && 'object' === typeof api && api.options.suppress) {
                        if (arguments.length < 2) {
                            return $.attr(self, oldtitle);
                        }

                        // If qTip is rendered and title was originally used as content, update it
                        if (api && api.options.content.attr === title && api.cache.attr) {
                            api.set('content.text', val);
                        }

                        // Use the regular attr method to set, then cache the result
                        return this.attr(oldtitle, val);
                    }
                }

                return $.fn['attr' + replaceSuffix].apply(this, arguments);
            },

            /* Allow clone to correctly retrieve cached title attributes */
            clone: function (keepData) {
                var titles = $([]), title = 'title',

                // Clone our element using the real clone method
                elems = $.fn['clone' + replaceSuffix].apply(this, arguments);

                // Grab all elements with an oldtitle set, and change it to regular title attribute, if keepData is false
                if (!keepData) {
                    elems.filter('[' + oldtitle + ']').attr('title', function () {
                        return $.attr(this, oldtitle);
                    })
                    .removeAttr(oldtitle);
                }

                return elems;
            }
        }, function (name, func) {
            if (!func || $.fn[name + replaceSuffix]) { return TRUE; }

            var old = $.fn[name + replaceSuffix] = $.fn[name];
            $.fn[name] = function () {
                return func.apply(this, arguments) || old.apply(this, arguments);
            };
        });

        /* Fire off 'removeqtip' handler in $.cleanData if jQuery UI not present (it already does similar).
         * This snippet is taken directly from jQuery UI source code found here:
         *     http://code.jquery.com/ui/jquery-ui-git.js
         */
        if (!$.ui) {
            $['cleanData' + replaceSuffix] = $.cleanData;
            $.cleanData = function (elems) {
                for (var i = 0, elem; (elem = $(elems[i])).length; i++) {
                    if (elem.attr(ATTR_HAS)) {
                        try { elem.triggerHandler('removeqtip'); }
                        catch (e) { }
                    }
                }
                $['cleanData' + replaceSuffix].apply(this, arguments);
            };
        }
        ;// qTip version
        QTIP.version = '2.2.1';

        // Base ID for all qTips
        QTIP.nextid = 0;

        // Inactive events array
        QTIP.inactiveEvents = INACTIVE_EVENTS;

        // Base z-index for all qTips
        QTIP.zindex = 15000;

        // Define configuration defaults
        QTIP.defaults = {
            prerender: FALSE,
            id: FALSE,
            overwrite: TRUE,
            suppress: TRUE,
            content: {
                text: TRUE,
                attr: 'title',
                title: FALSE,
                button: FALSE
            },
            position: {
                my: 'top left',
                at: 'bottom right',
                target: FALSE,
                container: FALSE,
                viewport: FALSE,
                adjust: {
                    x: 0, y: 0,
                    mouse: TRUE,
                    scroll: TRUE,
                    resize: TRUE,
                    method: 'flipinvert flipinvert'
                },
                effect: function (api, pos, viewport) {
                    $(this).animate(pos, {
                        duration: 200,
                        queue: FALSE
                    });
                }
            },
            show: {
                target: FALSE,
                event: 'mouseenter',
                effect: TRUE,
                delay: 90,
                solo: FALSE,
                ready: FALSE,
                autofocus: FALSE
            },
            hide: {
                target: FALSE,
                event: 'mouseleave',
                effect: TRUE,
                delay: 0,
                fixed: FALSE,
                inactive: FALSE,
                leave: 'window',
                distance: FALSE
            },
            style: {
                classes: '',
                widget: FALSE,
                width: FALSE,
                height: FALSE,
                def: TRUE
            },
            events: {
                render: NULL,
                move: NULL,
                show: NULL,
                hide: NULL,
                toggle: NULL,
                visible: NULL,
                hidden: NULL,
                focus: NULL,
                blur: NULL
            }
        };
        ; var TIP,

        // .bind()/.on() namespace
        TIPNS = '.qtip-tip',

        // Common CSS strings
        MARGIN = 'margin',
        BORDER = 'border',
        COLOR = 'color',
        BG_COLOR = 'background-color',
        TRANSPARENT = 'transparent',
        IMPORTANT = ' !important',

        // Check if the browser supports <canvas/> elements
        HASCANVAS = !!document.createElement('canvas').getContext,

        // Invalid colour values used in parseColours()
        INVALID = /rgba?\(0, 0, 0(, 0)?\)|transparent|#123456/i;

        // Camel-case method, taken from jQuery source
        // http://code.jquery.com/jquery-1.8.0.js
        function camel(s) { return s.charAt(0).toUpperCase() + s.slice(1); }

        /*
         * Modified from Modernizr's testPropsAll()
         * http://modernizr.com/downloads/modernizr-latest.js
         */
        var cssProps = {}, cssPrefixes = ["Webkit", "O", "Moz", "ms"];
        function vendorCss(elem, prop) {
            var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1),
                props = (prop + ' ' + cssPrefixes.join(ucProp + ' ') + ucProp).split(' '),
                cur, val, i = 0;

            // If the property has already been mapped...
            if (cssProps[prop]) { return elem.css(cssProps[prop]); }

            while ((cur = props[i++])) {
                if ((val = elem.css(cur)) !== undefined) {
                    return cssProps[prop] = cur, val;
                }
            }
        }

        // Parse a given elements CSS property into an int
        function intCss(elem, prop) {
            return Math.ceil(parseFloat(vendorCss(elem, prop)));
        }


        // VML creation (for IE only)
        if (!HASCANVAS) {
            var createVML = function (tag, props, style) {
                return '<qtipvml:' + tag + ' xmlns="urn:schemas-microsoft.com:vml" class="qtip-vml" ' + (props || '') +
                    ' style="behavior: url(#default#VML); ' + (style || '') + '" />';
            };
        }

            // Canvas only definitions
        else {
            var PIXEL_RATIO = window.devicePixelRatio || 1,
                BACKING_STORE_RATIO = (function () {
                    var context = document.createElement('canvas').getContext('2d');
                    return context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio ||
                            context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || 1;
                }()),
                SCALE = PIXEL_RATIO / BACKING_STORE_RATIO;
        }


        function Tip(qtip, options) {
            this._ns = 'tip';
            this.options = options;
            this.offset = options.offset;
            this.size = [options.width, options.height];

            // Initialize
            this.init((this.qtip = qtip));
        }

        $.extend(Tip.prototype, {
            init: function (qtip) {
                var context, tip;

                // Create tip element and prepend to the tooltip
                tip = this.element = qtip.elements.tip = $('<div />', { 'class': NAMESPACE + '-tip' }).prependTo(qtip.tooltip);

                // Create tip drawing element(s)
                if (HASCANVAS) {
                    // save() as soon as we create the canvas element so FF2 doesn't bork on our first restore()!
                    context = $('<canvas />').appendTo(this.element)[0].getContext('2d');

                    // Setup constant parameters
                    context.lineJoin = 'miter';
                    context.miterLimit = 100000;
                    context.save();
                }
                else {
                    context = createVML('shape', 'coordorigin="0,0"', 'position:absolute;');
                    this.element.html(context + context);

                    // Prevent mousing down on the tip since it causes problems with .live() handling in IE due to VML
                    qtip._bind($('*', tip).add(tip), ['click', 'mousedown'], function (event) { event.stopPropagation(); }, this._ns);
                }

                // Bind update events
                qtip._bind(qtip.tooltip, 'tooltipmove', this.reposition, this._ns, this);

                // Create it
                this.create();
            },

            _swapDimensions: function () {
                this.size[0] = this.options.height;
                this.size[1] = this.options.width;
            },
            _resetDimensions: function () {
                this.size[0] = this.options.width;
                this.size[1] = this.options.height;
            },

            _useTitle: function (corner) {
                var titlebar = this.qtip.elements.titlebar;
                return titlebar && (
                    corner.y === TOP || (corner.y === CENTER && this.element.position().top + (this.size[1] / 2) + this.options.offset < titlebar.outerHeight(TRUE))
                );
            },

            _parseCorner: function (corner) {
                var my = this.qtip.options.position.my;

                // Detect corner and mimic properties
                if (corner === FALSE || my === FALSE) {
                    corner = FALSE;
                }
                else if (corner === TRUE) {
                    corner = new CORNER(my.string());
                }
                else if (!corner.string) {
                    corner = new CORNER(corner);
                    corner.fixed = TRUE;
                }

                return corner;
            },

            _parseWidth: function (corner, side, use) {
                var elements = this.qtip.elements,
                    prop = BORDER + camel(side) + 'Width';

                return (use ? intCss(use, prop) : (
                    intCss(elements.content, prop) ||
                    intCss(this._useTitle(corner) && elements.titlebar || elements.content, prop) ||
                    intCss(elements.tooltip, prop)
                )) || 0;
            },

            _parseRadius: function (corner) {
                var elements = this.qtip.elements,
                    prop = BORDER + camel(corner.y) + camel(corner.x) + 'Radius';

                return BROWSER.ie < 9 ? 0 :
                    intCss(this._useTitle(corner) && elements.titlebar || elements.content, prop) ||
                    intCss(elements.tooltip, prop) || 0;
            },

            _invalidColour: function (elem, prop, compare) {
                var val = elem.css(prop);
                return !val || (compare && val === elem.css(compare)) || INVALID.test(val) ? FALSE : val;
            },

            _parseColours: function (corner) {
                var elements = this.qtip.elements,
                    tip = this.element.css('cssText', ''),
                    borderSide = BORDER + camel(corner[corner.precedance]) + camel(COLOR),
                    colorElem = this._useTitle(corner) && elements.titlebar || elements.content,
                    css = this._invalidColour, color = [];

                // Attempt to detect the background colour from various elements, left-to-right precedance
                color[0] = css(tip, BG_COLOR) || css(colorElem, BG_COLOR) || css(elements.content, BG_COLOR) ||
                    css(elements.tooltip, BG_COLOR) || tip.css(BG_COLOR);

                // Attempt to detect the correct border side colour from various elements, left-to-right precedance
                color[1] = css(tip, borderSide, COLOR) || css(colorElem, borderSide, COLOR) ||
                    css(elements.content, borderSide, COLOR) || css(elements.tooltip, borderSide, COLOR) || elements.tooltip.css(borderSide);

                // Reset background and border colours
                $('*', tip).add(tip).css('cssText', BG_COLOR + ':' + TRANSPARENT + IMPORTANT + ';' + BORDER + ':0' + IMPORTANT + ';');

                return color;
            },

            _calculateSize: function (corner) {
                var y = corner.precedance === Y,
                    width = this.options['width'],
                    height = this.options['height'],
                    isCenter = corner.abbrev() === 'c',
                    base = (y ? width : height) * (isCenter ? 0.5 : 1),
                    pow = Math.pow,
                    round = Math.round,
                    bigHyp, ratio, result,

                smallHyp = Math.sqrt(pow(base, 2) + pow(height, 2)),
                hyp = [(this.border / base) * smallHyp, (this.border / height) * smallHyp];

                hyp[2] = Math.sqrt(pow(hyp[0], 2) - pow(this.border, 2));
                hyp[3] = Math.sqrt(pow(hyp[1], 2) - pow(this.border, 2));

                bigHyp = smallHyp + hyp[2] + hyp[3] + (isCenter ? 0 : hyp[0]);
                ratio = bigHyp / smallHyp;

                result = [round(ratio * width), round(ratio * height)];
                return y ? result : result.reverse();
            },

            // Tip coordinates calculator
            _calculateTip: function (corner, size, scale) {
                scale = scale || 1;
                size = size || this.size;

                var width = size[0] * scale,
                    height = size[1] * scale,
                    width2 = Math.ceil(width / 2), height2 = Math.ceil(height / 2),

                // Define tip coordinates in terms of height and width values
                tips = {
                    br: [0, 0, width, height, width, 0],
                    bl: [0, 0, width, 0, 0, height],
                    tr: [0, height, width, 0, width, height],
                    tl: [0, 0, 0, height, width, height],
                    tc: [0, height, width2, 0, width, height],
                    bc: [0, 0, width, 0, width2, height],
                    rc: [0, 0, width, height2, 0, height],
                    lc: [width, 0, width, height, 0, height2]
                };

                // Set common side shapes
                tips.lt = tips.br; tips.rt = tips.bl;
                tips.lb = tips.tr; tips.rb = tips.tl;

                return tips[corner.abbrev()];
            },

            // Tip coordinates drawer (canvas)
            _drawCoords: function (context, coords) {
                context.beginPath();
                context.moveTo(coords[0], coords[1]);
                context.lineTo(coords[2], coords[3]);
                context.lineTo(coords[4], coords[5]);
                context.closePath();
            },

            create: function () {
                // Determine tip corner
                var c = this.corner = (HASCANVAS || BROWSER.ie) && this._parseCorner(this.options.corner);

                // If we have a tip corner...
                if ((this.enabled = !!this.corner && this.corner.abbrev() !== 'c')) {
                    // Cache it
                    this.qtip.cache.corner = c.clone();

                    // Create it
                    this.update();
                }

                // Toggle tip element
                this.element.toggle(this.enabled);

                return this.corner;
            },

            update: function (corner, position) {
                if (!this.enabled) { return this; }

                var elements = this.qtip.elements,
                    tip = this.element,
                    inner = tip.children(),
                    options = this.options,
                    curSize = this.size,
                    mimic = options.mimic,
                    round = Math.round,
                    color, precedance, context,
                    coords, bigCoords, translate, newSize, border, BACKING_STORE_RATIO;

                // Re-determine tip if not already set
                if (!corner) { corner = this.qtip.cache.corner || this.corner; }

                // Use corner property if we detect an invalid mimic value
                if (mimic === FALSE) { mimic = corner; }

                    // Otherwise inherit mimic properties from the corner object as necessary
                else {
                    mimic = new CORNER(mimic);
                    mimic.precedance = corner.precedance;

                    if (mimic.x === 'inherit') { mimic.x = corner.x; }
                    else if (mimic.y === 'inherit') { mimic.y = corner.y; }
                    else if (mimic.x === mimic.y) {
                        mimic[corner.precedance] = corner[corner.precedance];
                    }
                }
                precedance = mimic.precedance;

                // Ensure the tip width.height are relative to the tip position
                if (corner.precedance === X) { this._swapDimensions(); }
                else { this._resetDimensions(); }

                // Update our colours
                color = this.color = this._parseColours(corner);

                // Detect border width, taking into account colours
                if (color[1] !== TRANSPARENT) {
                    // Grab border width
                    border = this.border = this._parseWidth(corner, corner[corner.precedance]);

                    // If border width isn't zero, use border color as fill if it's not invalid (1.0 style tips)
                    if (options.border && border < 1 && !INVALID.test(color[1])) { color[0] = color[1]; }

                    // Set border width (use detected border width if options.border is true)
                    this.border = border = options.border !== TRUE ? options.border : border;
                }

                    // Border colour was invalid, set border to zero
                else { this.border = border = 0; }

                // Determine tip size
                newSize = this.size = this._calculateSize(corner);
                tip.css({
                    width: newSize[0],
                    height: newSize[1],
                    lineHeight: newSize[1] + 'px'
                });

                // Calculate tip translation
                if (corner.precedance === Y) {
                    translate = [
                        round(mimic.x === LEFT ? border : mimic.x === RIGHT ? newSize[0] - curSize[0] - border : (newSize[0] - curSize[0]) / 2),
                        round(mimic.y === TOP ? newSize[1] - curSize[1] : 0)
                    ];
                }
                else {
                    translate = [
                        round(mimic.x === LEFT ? newSize[0] - curSize[0] : 0),
                        round(mimic.y === TOP ? border : mimic.y === BOTTOM ? newSize[1] - curSize[1] - border : (newSize[1] - curSize[1]) / 2)
                    ];
                }

                // Canvas drawing implementation
                if (HASCANVAS) {
                    // Grab canvas context and clear/save it
                    context = inner[0].getContext('2d');
                    context.restore(); context.save();
                    context.clearRect(0, 0, 6000, 6000);

                    // Calculate coordinates
                    coords = this._calculateTip(mimic, curSize, SCALE);
                    bigCoords = this._calculateTip(mimic, this.size, SCALE);

                    // Set the canvas size using calculated size
                    inner.attr(WIDTH, newSize[0] * SCALE).attr(HEIGHT, newSize[1] * SCALE);
                    inner.css(WIDTH, newSize[0]).css(HEIGHT, newSize[1]);

                    // Draw the outer-stroke tip
                    this._drawCoords(context, bigCoords);
                    context.fillStyle = color[1];
                    context.fill();

                    // Draw the actual tip
                    context.translate(translate[0] * SCALE, translate[1] * SCALE);
                    this._drawCoords(context, coords);
                    context.fillStyle = color[0];
                    context.fill();
                }

                    // VML (IE Proprietary implementation)
                else {
                    // Calculate coordinates
                    coords = this._calculateTip(mimic);

                    // Setup coordinates string
                    coords = 'm' + coords[0] + ',' + coords[1] + ' l' + coords[2] +
                        ',' + coords[3] + ' ' + coords[4] + ',' + coords[5] + ' xe';

                    // Setup VML-specific offset for pixel-perfection
                    translate[2] = border && /^(r|b)/i.test(corner.string()) ?
                        BROWSER.ie === 8 ? 2 : 1 : 0;

                    // Set initial CSS
                    inner.css({
                        coordsize: (newSize[0] + border) + ' ' + (newSize[1] + border),
                        antialias: '' + (mimic.string().indexOf(CENTER) > -1),
                        left: translate[0] - (translate[2] * Number(precedance === X)),
                        top: translate[1] - (translate[2] * Number(precedance === Y)),
                        width: newSize[0] + border,
                        height: newSize[1] + border
                    })
                    .each(function (i) {
                        var $this = $(this);

                        // Set shape specific attributes
                        $this[$this.prop ? 'prop' : 'attr']({
                            coordsize: (newSize[0] + border) + ' ' + (newSize[1] + border),
                            path: coords,
                            fillcolor: color[0],
                            filled: !!i,
                            stroked: !i
                        })
                        .toggle(!!(border || i));

                        // Check if border is enabled and add stroke element
                        !i && $this.html(createVML(
                            'stroke', 'weight="' + (border * 2) + 'px" color="' + color[1] + '" miterlimit="1000" joinstyle="miter"'
                        ));
                    });
                }

                // Opera bug #357 - Incorrect tip position
                // https://github.com/Craga89/qTip2/issues/367
                window.opera && setTimeout(function () {
                    elements.tip.css({
                        display: 'inline-block',
                        visibility: 'visible'
                    });
                }, 1);

                // Position if needed
                if (position !== FALSE) { this.calculate(corner, newSize); }
            },

            calculate: function (corner, size) {
                if (!this.enabled) { return FALSE; }

                var self = this,
                    elements = this.qtip.elements,
                    tip = this.element,
                    userOffset = this.options.offset,
                    isWidget = elements.tooltip.hasClass('ui-widget'),
                    position = {},
                    precedance, corners;

                // Inherit corner if not provided
                corner = corner || this.corner;
                precedance = corner.precedance;

                // Determine which tip dimension to use for adjustment
                size = size || this._calculateSize(corner);

                // Setup corners and offset array
                corners = [corner.x, corner.y];
                if (precedance === X) { corners.reverse(); }

                // Calculate tip position
                $.each(corners, function (i, side) {
                    var b, bc, br;

                    if (side === CENTER) {
                        b = precedance === Y ? LEFT : TOP;
                        position[b] = '50%';
                        position[MARGIN + '-' + b] = -Math.round(size[precedance === Y ? 0 : 1] / 2) + userOffset;
                    }
                    else {
                        b = self._parseWidth(corner, side, elements.tooltip);
                        bc = self._parseWidth(corner, side, elements.content);
                        br = self._parseRadius(corner);

                        position[side] = Math.max(-self.border, i ? bc : (userOffset + (br > b ? br : -b)));
                    }
                });

                // Adjust for tip size
                position[corner[precedance]] -= size[precedance === X ? 0 : 1];

                // Set and return new position
                tip.css({ margin: '', top: '', bottom: '', left: '', right: '' }).css(position);
                return position;
            },

            reposition: function (event, api, pos, viewport) {
                if (!this.enabled) { return; }

                var cache = api.cache,
                    newCorner = this.corner.clone(),
                    adjust = pos.adjusted,
                    method = api.options.position.adjust.method.split(' '),
                    horizontal = method[0],
                    vertical = method[1] || method[0],
                    shift = { left: FALSE, top: FALSE, x: 0, y: 0 },
                    offset, css = {}, props;

                function shiftflip(direction, precedance, popposite, side, opposite) {
                    // Horizontal - Shift or flip method
                    if (direction === SHIFT && newCorner.precedance === precedance && adjust[side] && newCorner[popposite] !== CENTER) {
                        newCorner.precedance = newCorner.precedance === X ? Y : X;
                    }
                    else if (direction !== SHIFT && adjust[side]) {
                        newCorner[precedance] = newCorner[precedance] === CENTER ?
                            (adjust[side] > 0 ? side : opposite) : (newCorner[precedance] === side ? opposite : side);
                    }
                }

                function shiftonly(xy, side, opposite) {
                    if (newCorner[xy] === CENTER) {
                        css[MARGIN + '-' + side] = shift[xy] = offset[MARGIN + '-' + side] - adjust[side];
                    }
                    else {
                        props = offset[opposite] !== undefined ?
                            [adjust[side], -offset[side]] : [-adjust[side], offset[side]];

                        if ((shift[xy] = Math.max(props[0], props[1])) > props[0]) {
                            pos[side] -= adjust[side];
                            shift[side] = FALSE;
                        }

                        css[offset[opposite] !== undefined ? opposite : side] = shift[xy];
                    }
                }

                // If our tip position isn't fixed e.g. doesn't adjust with viewport...
                if (this.corner.fixed !== TRUE) {
                    // Perform shift/flip adjustments
                    shiftflip(horizontal, X, Y, LEFT, RIGHT);
                    shiftflip(vertical, Y, X, TOP, BOTTOM);

                    // Update and redraw the tip if needed (check cached details of last drawn tip)
                    if (newCorner.string() !== cache.corner.string() || cache.cornerTop !== adjust.top || cache.cornerLeft !== adjust.left) {
                        this.update(newCorner, FALSE);
                    }
                }

                // Setup tip offset properties
                offset = this.calculate(newCorner);

                // Readjust offset object to make it left/top
                if (offset.right !== undefined) { offset.left = -offset.right; }
                if (offset.bottom !== undefined) { offset.top = -offset.bottom; }
                offset.user = this.offset;

                // Perform shift adjustments
                if (shift.left = (horizontal === SHIFT && !!adjust.left)) { shiftonly(X, LEFT, RIGHT); }
                if (shift.top = (vertical === SHIFT && !!adjust.top)) { shiftonly(Y, TOP, BOTTOM); }

                /*
                * If the tip is adjusted in both dimensions, or in a
                * direction that would cause it to be anywhere but the
                * outer border, hide it!
                */
                this.element.css(css).toggle(
                    !((shift.x && shift.y) || (newCorner.x === CENTER && shift.y) || (newCorner.y === CENTER && shift.x))
                );

                // Adjust position to accomodate tip dimensions
                pos.left -= offset.left.charAt ? offset.user :
                    horizontal !== SHIFT || shift.top || !shift.left && !shift.top ? offset.left + this.border : 0;
                pos.top -= offset.top.charAt ? offset.user :
                    vertical !== SHIFT || shift.left || !shift.left && !shift.top ? offset.top + this.border : 0;

                // Cache details
                cache.cornerLeft = adjust.left; cache.cornerTop = adjust.top;
                cache.corner = newCorner.clone();
            },

            destroy: function () {
                // Unbind events
                this.qtip._unbind(this.qtip.tooltip, this._ns);

                // Remove the tip element(s)
                if (this.qtip.elements.tip) {
                    this.qtip.elements.tip.find('*')
                        .remove().end().remove();
                }
            }
        });

        TIP = PLUGINS.tip = function (api) {
            return new Tip(api, api.options.style.tip);
        };

        // Initialize tip on render
        TIP.initialize = 'render';

        // Setup plugin sanitization options
        TIP.sanitize = function (options) {
            if (options.style && 'tip' in options.style) {
                var opts = options.style.tip;
                if (typeof opts !== 'object') { opts = options.style.tip = { corner: opts }; }
                if (!(/string|boolean/i).test(typeof opts.corner)) { opts.corner = TRUE; }
            }
        };

        // Add new option checks for the plugin
        CHECKS.tip = {
            '^position.my|style.tip.(corner|mimic|border)$': function () {
                // Make sure a tip can be drawn
                this.create();

                // Reposition the tooltip
                this.qtip.reposition();
            },
            '^style.tip.(height|width)$': function (obj) {
                // Re-set dimensions and redraw the tip
                this.size = [obj.width, obj.height];
                this.update();

                // Reposition the tooltip
                this.qtip.reposition();
            },
            '^content.title|style.(classes|widget)$': function () {
                this.update();
            }
        };

        // Extend original qTip defaults
        $.extend(TRUE, QTIP.defaults, {
            style: {
                tip: {
                    corner: TRUE,
                    mimic: FALSE,
                    width: 6,
                    height: 6,
                    border: TRUE,
                    offset: 0
                }
            }
        });
        ; PLUGINS.viewport = function (api, position, posOptions, targetWidth, targetHeight, elemWidth, elemHeight) {
            var target = posOptions.target,
                tooltip = api.elements.tooltip,
                my = posOptions.my,
                at = posOptions.at,
                adjust = posOptions.adjust,
                method = adjust.method.split(' '),
                methodX = method[0],
                methodY = method[1] || method[0],
                viewport = posOptions.viewport,
                container = posOptions.container,
                cache = api.cache,
                adjusted = { left: 0, top: 0 },
                fixed, newMy, containerOffset, containerStatic,
                viewportWidth, viewportHeight, viewportScroll, viewportOffset;

            // If viewport is not a jQuery element, or it's the window/document, or no adjustment method is used... return
            if (!viewport.jquery || target[0] === window || target[0] === document.body || adjust.method === 'none') {
                return adjusted;
            }

            // Cach container details
            containerOffset = container.offset() || adjusted;
            containerStatic = container.css('position') === 'static';

            // Cache our viewport details
            fixed = tooltip.css('position') === 'fixed';
            viewportWidth = viewport[0] === window ? viewport.width() : viewport.outerWidth(FALSE);
            viewportHeight = viewport[0] === window ? viewport.height() : viewport.outerHeight(FALSE);
            viewportScroll = { left: fixed ? 0 : viewport.scrollLeft(), top: fixed ? 0 : viewport.scrollTop() };
            viewportOffset = viewport.offset() || adjusted;

            // Generic calculation method
            function calculate(side, otherSide, type, adjust, side1, side2, lengthName, targetLength, elemLength) {
                var initialPos = position[side1],
                    mySide = my[side],
                    atSide = at[side],
                    isShift = type === SHIFT,
                    myLength = mySide === side1 ? elemLength : mySide === side2 ? -elemLength : -elemLength / 2,
                    atLength = atSide === side1 ? targetLength : atSide === side2 ? -targetLength : -targetLength / 2,
                    sideOffset = viewportScroll[side1] + viewportOffset[side1] - (containerStatic ? 0 : containerOffset[side1]),
                    overflow1 = sideOffset - initialPos,
                    overflow2 = initialPos + elemLength - (lengthName === WIDTH ? viewportWidth : viewportHeight) - sideOffset,
                    offset = myLength - (my.precedance === side || mySide === my[otherSide] ? atLength : 0) - (atSide === CENTER ? targetLength / 2 : 0);

                // shift
                if (isShift) {
                    offset = (mySide === side1 ? 1 : -1) * myLength;

                    // Adjust position but keep it within viewport dimensions
                    position[side1] += overflow1 > 0 ? overflow1 : overflow2 > 0 ? -overflow2 : 0;
                    position[side1] = Math.max(
                        -containerOffset[side1] + viewportOffset[side1],
                        initialPos - offset,
                        Math.min(
                            Math.max(
                                -containerOffset[side1] + viewportOffset[side1] + (lengthName === WIDTH ? viewportWidth : viewportHeight),
                                initialPos + offset
                            ),
                            position[side1],

                            // Make sure we don't adjust complete off the element when using 'center'
                            mySide === 'center' ? initialPos - myLength : 1E9
                        )
                    );

                }

                    // flip/flipinvert
                else {
                    // Update adjustment amount depending on if using flipinvert or flip
                    adjust *= (type === FLIPINVERT ? 2 : 0);

                    // Check for overflow on the left/top
                    if (overflow1 > 0 && (mySide !== side1 || overflow2 > 0)) {
                        position[side1] -= offset + adjust;
                        newMy.invert(side, side1);
                    }

                        // Check for overflow on the bottom/right
                    else if (overflow2 > 0 && (mySide !== side2 || overflow1 > 0)) {
                        position[side1] -= (mySide === CENTER ? -offset : offset) + adjust;
                        newMy.invert(side, side2);
                    }

                    // Make sure we haven't made things worse with the adjustment and reset if so
                    if (position[side1] < viewportScroll && -position[side1] > overflow2) {
                        position[side1] = initialPos; newMy = my.clone();
                    }
                }

                return position[side1] - initialPos;
            }

            // Set newMy if using flip or flipinvert methods
            if (methodX !== 'shift' || methodY !== 'shift') { newMy = my.clone(); }

            // Adjust position based onviewport and adjustment options
            adjusted = {
                left: methodX !== 'none' ? calculate(X, Y, methodX, adjust.x, LEFT, RIGHT, WIDTH, targetWidth, elemWidth) : 0,
                top: methodY !== 'none' ? calculate(Y, X, methodY, adjust.y, TOP, BOTTOM, HEIGHT, targetHeight, elemHeight) : 0,
                my: newMy
            };

            return adjusted;
        };
        ;
    }));
}(window, document));
;
/**
*
* Photobooth.js version 0.7
*
* build Mon Dec 17 2012 20:48:31 GMT+0000 (GMT Standard Time)
*
* CSS
*/
if (window.addEventListener != undefined) {
    window.addEventListener("load", function () { var s = document.createElement("style"); s.innerHTML = ".photobooth{position:relative;font:11px arial,sans-serif;overflow:hidden;user-select:none;-webkit-user-select:none;-moz-user-select:none;-o-user-select:none}.photobooth canvas{position:absolute;left:0;top:0}.photobooth .blind{position:absolute;left:0;top:0;opacity:0;width:100%;height:100%;background:#fff;z-index:1}.photobooth .blind.anim{transition:opacity 1500ms ease-out;-o-transition:opacity 1500ms ease-out;-moz-transition:opacity 1500ms ease-out;-webkit-transition:opacity 1500ms ease-out}.photobooth .warning{position:absolute;top:45%;background:#ffebeb;color:#cf0000;border:1px solid #cf0000;width:60%;left:50%;margin-left:-30%;display:none;padding:5px;z-index:10;text-align:center}.photobooth .warning span{text-decoration:underline;cursor:pointer;color:#333}.photobooth ul{width:30px;position:absolute;right:0;top:0;background:rgba( 0,0,0,.6 );height:190px;z-index:2;border-bottom-left-radius:5px}.photobooth ul li{width:30px;height:38px;background-repeat:no-repeat;background-position:center center;cursor:pointer;position:relative}.photobooth ul li:hover{background-color:#aaa}.photobooth ul li.selected{background-color:#ccc}.photobooth ul.noHSB{height:80px}.photobooth ul.noHSB li.hue,.photobooth ul.noHSB li.saturation,.photobooth ul.noHSB li.brightness{display:none}.photobooth ul li.hue{background-image:url(data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAAZAAA/+4ADkFkb2JlAGTAAAAAAf/bAIQAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQICAgICAgICAgICAwMDAwMDAwMDAwEBAQEBAQECAQECAgIBAgIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMD/8AAEQgACAAYAwERAAIRAQMRAf/EAHgAAQEAAAAAAAAAAAAAAAAAAAkIAQEAAwAAAAAAAAAAAAAAAAAKBggLEAAAAwQLAAAAAAAAAAAAAAAAMQZBAjQ4A3MEdMQFdQcICTkRAAEBBAcGBwAAAAAAAAAAABExAAEhElECMjMEBQlhwgNzFDgVNRY3CBgK/9oADAMBAAIRAxEAPwBGOKPmqmNdT5FD2YgarLO67OVueIqrxF2tI/1Kn0jjjKfFcJZEt+5BAUCAaKuw+ThT3vC0wbFof+U4Dnv3WGl8Pu47A8vecwabKy8ZRVNKFdF3dY72fztbVdFu67axelcfrPkYlPTutCW7qqYCkwDf/9k=)}.photobooth ul li.saturation{background-image:url(data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAAZAAA/+4ADkFkb2JlAGTAAAAAAf/bAIQAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQICAgICAgICAgICAwMDAwMDAwMDAwEBAQEBAQECAQECAgIBAgIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMD/8AAEQgACAAYAwERAAIRAQMRAf/EAGMAAAMAAAAAAAAAAAAAAAAAAAYICQEBAQEAAAAAAAAAAAAAAAAACAkKEAAABgMBAAAAAAAAAAAAAAAAwYIDMwZxAkQHEQABAgUFAAAAAAAAAAAAAAAAAQYxgQIyM3HBQgMH/9oADAMBAAIRAxEAPwAwo0rWdSFXHBYpnLZmWjVB/fLedIODu5Do81j1y2KE0CJlJA2uK5ZjtY2Kg//Z)}.photobooth ul li.brightness{background-image:url(data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAAZAAA/+4ADkFkb2JlAGTAAAAAAf/bAIQAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQICAgICAgICAgICAwMDAwMDAwMDAwEBAQEBAQECAQECAgIBAgIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMD/8AAEQgACAAYAwERAAIRAQMRAf/EAFcAAQAAAAAAAAAAAAAAAAAAAAoBAQAAAAAAAAAAAAAAAAAAAAAQAAAEBQUAAAAAAAAAAAAAAACxAwgBMXECBXJzBDQ1EQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwAcTWfR4GtIwC5mITxNUDgAYA0joY3aRKwB/9k=)}.photobooth ul li.crop{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAICAYAAADjoT9jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAEFJREFUeNpi/A8EDAjACMT/qUgzMCJZwMhAXQA2l4VGhsPNZKKR4XBfMMG8QiPASDcf0MIX/2FxgCJARRoMAAIMAK49Iv4yTUj5AAAAAElFTkSuQmCC)}.photobooth ul li.trigger{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAASCAYAAABB7B6eAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAa9JREFUeNqc1M8rRFEUwPF5M4MhP8aPIiIS21lQk1Is5ceChZIdOytlI/+A7Ig/gGRhpYiNbKQsrBRFLPzYWJghNH7MjOd76qhr8m6vOfWpmffevefec987juu6AZ8RQhhBpJHJuT+CfsiEDo6wGjYeKMKn8b8Um/jCG2qQ0skjyOIWB9hFNyaN8bWSwGEHM5q9EVc6mUQ9YpjDHQbwoQkjuspDDKNEF9hjJDjFcoAEx653XEoJMYoVxNGBGPZRhzbL+HTYWLEtpO6V6EQ5kijTc7HFiwyssDwgyXsxhW8tkZSxAAksoj3n7P4G20hatviKE3RpqXKN4V5K4TE+IQ89WBI8ao0DFkP49krw+057xbyWxBY72LIdXsbjnlzf8/kRbtgSeO1APqonnwlu8tlBIYp9JojmkyCiX7Kf6MsngcSsvvO2aMZEPmcgEcea7ua/aNKGaC2RY0lwgTNsYwwNOlkrprGOJe2q/84vvegabdrrQyqomrSTyirHtbPKc+84x4L2qBazORi/s9KuC7QfBY3JC1UVBlGt16PallPap+Tas+7wWc8za1Ql8yPAAAzkXGo1lmDtAAAAAElFTkSuQmCC)}.photobooth .submenu{background:rgba( 0,0,0,.6 );position:absolute;width:100px;opacity:0;height:20px;padding:5px 10px;color:#fff;top:4px;left:-124px;border-radius:5px;-webkit-transition:opacity 500ms ease;-moz-transition:opacity 500ms ease;-o-transition:opacity 500ms ease;-msie-transition:opacity 500ms ease;transition:opacity 500ms ease}.photobooth li:hover .submenu{opacity:1}.photobooth .submenu .tip{width:4px;height:8px;position:absolute;right:-4px;top:50%;margin-top:-2px;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAICAYAAADeM14FAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADVJREFUeNpiYGBgmAnEDP///wdjJgYImMnIyAhmwATggowwLTCArAKrQDqyQDrcMGQlAAEGAAGOCdflbyWyAAAAAElFTkSuQmCC)}.photobooth .submenu .slider{width:100px;height:20px;position:relative}.photobooth .submenu .slider .track{height:2px;width:100px;position:absolute;top:9px;background:rgba(255,255,255,.6)}.photobooth .submenu .slider .handle{height:14px;width:2px;position:absolute;top:3;background:#fff;z-index:2}.photobooth .submenu .slider .handle div{position:absolute;z-index:3;width:20px;top:-3px;height:20px;cursor:w-resize;left:-9px}.resizehandle{position:absolute;z-index:1;width:100px;height:100px;left:30px;top:30px;cursor:move;outline:1500px solid rgba( 0,0,0,.35 );box-shadow:2px 2px 10px rgba(0,0,0,.5),0 0 3px #000;opacity:0;transition:opacity 500ms ease;-moz-transition:opacity 500ms ease;-o-transition:opacity 500ms ease;-webkit-transition:opacity 500ms ease}noindex:-o-prefocus,.resizehandle{outline:0!important}@-moz-document url-prefix(){.resizehandle{ box-shadow:none!important}}.resizehandle .handle{width:100%;height:100%;border:2px dashed #0da4d3;margin:-2px 0 0 -2px;z-index:3;position:relative}.resizehandle .handle div{width:18px;height:18px;position:absolute;right:-2px;bottom:-2px;z-index:4;cursor:se-resize;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAHdJREFUeNpi/P//PwO5gIlcjXxLr/xnIlujsg7pNsM0AgEjE7kaSfIzusZ/d4n0M1aNxPgZWeMHC4RGIJuREV8847IRpBGvnwlpxBnPRGkEyYOcjYx5l1z+z3/8Pwij8NHlQWwUPxNrI4afSdUI9zNZGoF8gAADAOGvmx/e+CgVAAAAAElFTkSuQmCC);background-position:top left;background-repeat:no-repeat}"; document.head.appendChild(s); }, false);
} else {
    window.attachEvent("load", function () { var s = document.createElement("style"); s.innerHTML = ".photobooth{position:relative;font:11px arial,sans-serif;overflow:hidden;user-select:none;-webkit-user-select:none;-moz-user-select:none;-o-user-select:none}.photobooth canvas{position:absolute;left:0;top:0}.photobooth .blind{position:absolute;left:0;top:0;opacity:0;width:100%;height:100%;background:#fff;z-index:1}.photobooth .blind.anim{transition:opacity 1500ms ease-out;-o-transition:opacity 1500ms ease-out;-moz-transition:opacity 1500ms ease-out;-webkit-transition:opacity 1500ms ease-out}.photobooth .warning{position:absolute;top:45%;background:#ffebeb;color:#cf0000;border:1px solid #cf0000;width:60%;left:50%;margin-left:-30%;display:none;padding:5px;z-index:10;text-align:center}.photobooth .warning span{text-decoration:underline;cursor:pointer;color:#333}.photobooth ul{width:30px;position:absolute;right:0;top:0;background:rgba( 0,0,0,.6 );height:190px;z-index:2;border-bottom-left-radius:5px}.photobooth ul li{width:30px;height:38px;background-repeat:no-repeat;background-position:center center;cursor:pointer;position:relative}.photobooth ul li:hover{background-color:#aaa}.photobooth ul li.selected{background-color:#ccc}.photobooth ul.noHSB{height:80px}.photobooth ul.noHSB li.hue,.photobooth ul.noHSB li.saturation,.photobooth ul.noHSB li.brightness{display:none}.photobooth ul li.hue{background-image:url(data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAAZAAA/+4ADkFkb2JlAGTAAAAAAf/bAIQAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQICAgICAgICAgICAwMDAwMDAwMDAwEBAQEBAQECAQECAgIBAgIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMD/8AAEQgACAAYAwERAAIRAQMRAf/EAHgAAQEAAAAAAAAAAAAAAAAAAAkIAQEAAwAAAAAAAAAAAAAAAAAKBggLEAAAAwQLAAAAAAAAAAAAAAAAMQZBAjQ4A3MEdMQFdQcICTkRAAEBBAcGBwAAAAAAAAAAABExAAEhElECMjMEBQlhwgNzFDgVNRY3CBgK/9oADAMBAAIRAxEAPwBGOKPmqmNdT5FD2YgarLO67OVueIqrxF2tI/1Kn0jjjKfFcJZEt+5BAUCAaKuw+ThT3vC0wbFof+U4Dnv3WGl8Pu47A8vecwabKy8ZRVNKFdF3dY72fztbVdFu67axelcfrPkYlPTutCW7qqYCkwDf/9k=)}.photobooth ul li.saturation{background-image:url(data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAAZAAA/+4ADkFkb2JlAGTAAAAAAf/bAIQAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQICAgICAgICAgICAwMDAwMDAwMDAwEBAQEBAQECAQECAgIBAgIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMD/8AAEQgACAAYAwERAAIRAQMRAf/EAGMAAAMAAAAAAAAAAAAAAAAAAAYICQEBAQEAAAAAAAAAAAAAAAAACAkKEAAABgMBAAAAAAAAAAAAAAAAwYIDMwZxAkQHEQABAgUFAAAAAAAAAAAAAAAAAQYxgQIyM3HBQgMH/9oADAMBAAIRAxEAPwAwo0rWdSFXHBYpnLZmWjVB/fLedIODu5Do81j1y2KE0CJlJA2uK5ZjtY2Kg//Z)}.photobooth ul li.brightness{background-image:url(data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAAZAAA/+4ADkFkb2JlAGTAAAAAAf/bAIQAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQICAgICAgICAgICAwMDAwMDAwMDAwEBAQEBAQECAQECAgIBAgIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMD/8AAEQgACAAYAwERAAIRAQMRAf/EAFcAAQAAAAAAAAAAAAAAAAAAAAoBAQAAAAAAAAAAAAAAAAAAAAAQAAAEBQUAAAAAAAAAAAAAAACxAwgBMXECBXJzBDQ1EQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwAcTWfR4GtIwC5mITxNUDgAYA0joY3aRKwB/9k=)}.photobooth ul li.crop{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAICAYAAADjoT9jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAEFJREFUeNpi/A8EDAjACMT/qUgzMCJZwMhAXQA2l4VGhsPNZKKR4XBfMMG8QiPASDcf0MIX/2FxgCJARRoMAAIMAK49Iv4yTUj5AAAAAElFTkSuQmCC)}.photobooth ul li.trigger{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAASCAYAAABB7B6eAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAa9JREFUeNqc1M8rRFEUwPF5M4MhP8aPIiIS21lQk1Is5ceChZIdOytlI/+A7Ig/gGRhpYiNbKQsrBRFLPzYWJghNH7MjOd76qhr8m6vOfWpmffevefec987juu6AZ8RQhhBpJHJuT+CfsiEDo6wGjYeKMKn8b8Um/jCG2qQ0skjyOIWB9hFNyaN8bWSwGEHM5q9EVc6mUQ9YpjDHQbwoQkjuspDDKNEF9hjJDjFcoAEx653XEoJMYoVxNGBGPZRhzbL+HTYWLEtpO6V6EQ5kijTc7HFiwyssDwgyXsxhW8tkZSxAAksoj3n7P4G20hatviKE3RpqXKN4V5K4TE+IQ89WBI8ao0DFkP49krw+057xbyWxBY72LIdXsbjnlzf8/kRbtgSeO1APqonnwlu8tlBIYp9JojmkyCiX7Kf6MsngcSsvvO2aMZEPmcgEcea7ua/aNKGaC2RY0lwgTNsYwwNOlkrprGOJe2q/84vvegabdrrQyqomrSTyirHtbPKc+84x4L2qBazORi/s9KuC7QfBY3JC1UVBlGt16PallPap+Tas+7wWc8za1Ql8yPAAAzkXGo1lmDtAAAAAElFTkSuQmCC)}.photobooth .submenu{background:rgba( 0,0,0,.6 );position:absolute;width:100px;opacity:0;height:20px;padding:5px 10px;color:#fff;top:4px;left:-124px;border-radius:5px;-webkit-transition:opacity 500ms ease;-moz-transition:opacity 500ms ease;-o-transition:opacity 500ms ease;-msie-transition:opacity 500ms ease;transition:opacity 500ms ease}.photobooth li:hover .submenu{opacity:1}.photobooth .submenu .tip{width:4px;height:8px;position:absolute;right:-4px;top:50%;margin-top:-2px;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAICAYAAADeM14FAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADVJREFUeNpiYGBgmAnEDP///wdjJgYImMnIyAhmwATggowwLTCArAKrQDqyQDrcMGQlAAEGAAGOCdflbyWyAAAAAElFTkSuQmCC)}.photobooth .submenu .slider{width:100px;height:20px;position:relative}.photobooth .submenu .slider .track{height:2px;width:100px;position:absolute;top:9px;background:rgba(255,255,255,.6)}.photobooth .submenu .slider .handle{height:14px;width:2px;position:absolute;top:3;background:#fff;z-index:2}.photobooth .submenu .slider .handle div{position:absolute;z-index:3;width:20px;top:-3px;height:20px;cursor:w-resize;left:-9px}.resizehandle{position:absolute;z-index:1;width:100px;height:100px;left:30px;top:30px;cursor:move;outline:1500px solid rgba( 0,0,0,.35 );box-shadow:2px 2px 10px rgba(0,0,0,.5),0 0 3px #000;opacity:0;transition:opacity 500ms ease;-moz-transition:opacity 500ms ease;-o-transition:opacity 500ms ease;-webkit-transition:opacity 500ms ease}noindex:-o-prefocus,.resizehandle{outline:0!important}@-moz-document url-prefix(){.resizehandle{ box-shadow:none!important}}.resizehandle .handle{width:100%;height:100%;border:2px dashed #0da4d3;margin:-2px 0 0 -2px;z-index:3;position:relative}.resizehandle .handle div{width:18px;height:18px;position:absolute;right:-2px;bottom:-2px;z-index:4;cursor:se-resize;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAYAAAA71pVKAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAHdJREFUeNpi/P//PwO5gIlcjXxLr/xnIlujsg7pNsM0AgEjE7kaSfIzusZ/d4n0M1aNxPgZWeMHC4RGIJuREV8847IRpBGvnwlpxBnPRGkEyYOcjYx5l1z+z3/8Pwij8NHlQWwUPxNrI4afSdUI9zNZGoF8gAADAOGvmx/e+CgVAAAAAElFTkSuQmCC);background-position:top left;background-repeat:no-repeat}"; document.head.appendChild(s); }, false);
}
    /**
* JS
*/
Photobooth = function (e) { e.length && (e = e[0]); var t = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.oGetUserMedia || navigator.msieGetUserMedia || !1; this.onImage = function () { }, this.getHueOffset = function () { return o }, this.setHueOffset = function (e) { v(e, "hue") && (o = e) }, this.getBrightnessOffset = function () { return a }, this.setBrightnessOffset = function (e) { v(e, "brightness") && (a = e) }, this.getSaturationOffset = function () { return u }, this.setSaturationOffset = function (e) { v(e, "saturation") && (u = e) }, this.pause = function () { l === !1 && (l = !0, c && c.stop && c.stop()) }, this.resume = function () { l === !0 && (l = !1, M()) }, this.destroy = function () { this.pause(), e.removeChild(b) }, this.forceHSB = !1, this.isSupported = !!t, this.resize = function (e, t) { if (e < 200 || t < 200) throw "Error: Not enough space for Photobooth. Min height / width is 200 px"; p = e, d = t, C.setMax(p, d), b.style.width = e + "px", b.style.height = t + "px", w.width = e, w.height = t, S.width = e, S.height = t, T.width = e, T.height = t }; var n = function (e) { e.stopPropagation(), e.cancelBubble = !0 }, r = function (e) { this.startX = 0, this.startY = 0, e.addEventListener("mousedown", this, !1) }; r.prototype.onStart = function (e, t) { }, r.prototype.onMove = function (e, t) { }, r.prototype.onStop = function (e, t) { }, r.prototype.handleEvent = function (e) { this["fon" + e.type](e) }, r.prototype.fonmousedown = function (e) { e.preventDefault(), this.startX = e.clientX, this.startY = e.clientY, this.onStart(this.startX, this.startY), document.addEventListener("mousemove", this, !1), document.addEventListener("mouseup", this, !1) }, r.prototype.fonmousemove = function (e) { this.onMove(e.clientX - this.startX, e.clientY - this.startY) }, r.prototype.fonmouseup = function (e) { this.onStop(e.clientX - this.startX, e.clientY - this.startY), document.removeEventListener("mousemove", this), document.removeEventListener("mouseup", this) }; var i = function (e, t) { e.innerHTML = '<div class="submenu"><div class="tip"></div><div class="slider"><div class="track"></div><div class="handle" style="left:50px"><div></div></div></div></div>'; var i = 50, s = 50, o = e.getElementsByClassName("handle")[0], u = e.getElementsByClassName("slider")[0], a = new r(o); a.onMove = function (e) { f(i + e) }, a.onStop = function (e) { i = s }; var f = function (e) { e > 0 && e < 100 && (s = e, o.style.left = e + "px", t((e - 50) / 100)) }, l = function (e) { f(e.layerX), i = s }; u.addEventListener("click", l, !1), o.addEventListener("click", n, !1) }, s = function (e, t, i) { this.setMax = function (e, n) { t = e, i = n }, this.getData = function () { return { x: s, y: o, width: u, height: a } }, this.isActive = function () { return p }, this.toggle = function () { p === !1 ? (d.style.opacity = 1, p = !0) : (d.style.opacity = 0, p = !1) }; var s = 30, o = 30, u = 100, a = 100, f = 30, l = 30, c = 100, h = 100, p = !1, d = document.createElement("div"); d.className = "resizehandle", d.innerHTML = '<div class="handle"><div></div></div>', e.appendChild(d); var v = d.getElementsByTagName("div")[0], m = new r(v); m.onMove = function (e, n) { s + e + u < t && s + e > 0 && (f = s + e, d.style.left = f + "px"), o + n + a < i && o + n > 0 && (l = o + n, d.style.top = l + "px") }, m.onStop = function () { s = f, o = l }; var g = d.getElementsByTagName("div")[1]; g.addEventListener("mousedown", n, !1); var y = new r(g); y.onMove = function (e, n) { s + e + u < t && u + e > 18 && (c = u + e, d.style.width = c + "px"), o + n + a < i && a + n > 18 && (h = a + n, d.style.height = h + "px") }, y.onStop = function () { u = c, a = h } }, o = 0, u = 0, a = 0, f = !1, l = !1, c = null, h = this, p = e.offsetWidth, d = e.offsetHeight, v = function (e, t) { if (e < -0.5 || e > .5) throw "Invalid value: " + t + " must be between 0 and 1"; return !0 }, m = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (e) { window.setTimeout(e, 1e3 / 60) }, g = function (e) { return b.getElementsByClassName(e)[0] }, y = function (e) { return document.createElement(e) }, b = y("div"); b.className = "photobooth", b.innerHTML = '<div class="blind"></div><canvas></canvas><div class="warning notSupported">Sorry, Photobooth.js is not supported by your browser</div><div class="warning noWebcam">Please give Photobooth permission to use your Webcam. <span>Try again</span></div><ul><li title="hue"class="hue"></li><li title="saturation"class="saturation"></li><li title="brightness"class="brightness"></li><li title="crop"class="crop"></li><li title="take picture"class="trigger"></li></ul>'; var w = y("canvas"), E = w.getContext("2d"), S = b.getElementsByTagName("canvas")[0], x = S.getContext("2d"), T = y("video"); T.autoplay = !0; var N = g("noWebcam"); N.getElementsByTagName("span")[0].onclick = function () { M() }, new i(g("hue"), function (e) { o = e }), new i(g("saturation"), function (e) { u = e }), new i(g("brightness"), function (e) { a = e }); var C = new s(b, p, d), k = g("crop"); k.onclick = function () { C.toggle(), k.className === "crop" ? k.className = "crop selected" : k.className = "crop" }; var L = g("blind"); g("trigger").onclick = function () { L.className = "blind", L.style.opacity = 1, setTimeout(function () { L.className = "blind anim", L.style.opacity = 0 }, 50); var e = {}; C.isActive() ? e = C.getData() : f ? e = { x: (p - T.videoWidth) / 2, y: (d - T.videoHeight) / 2, width: T.videoWidth, height: T.videoHeight } : e = { x: 0, y: 0, width: p, height: d }; var t = y("canvas"); t.width = e.width, t.height = e.height; if (f) t.getContext("2d").drawImage(T, Math.max(0, e.x - (p - T.videoWidth) / 2), Math.max(e.y - (d - T.videoHeight) / 2), e.width, e.height, 0, 0, e.width, e.height); else { var n = x.getImageData(e.x, e.y, e.width, e.height); t.getContext("2d").putImageData(n, 0, 0) } h.onImage(t.toDataURL()) }; var A = function (e) { c = e; try { T.src = (window.URL || window.webkitURL).createObjectURL(c), m(H) } catch (t) { T.mozSrcObject = c, h.forceHSB === !1 ? (f = !0, b.appendChild(T), b.getElementsByTagName("ul")[0].className = "noHSB") : T.addEventListener("canplay", function () { m(H) }, !1), T.play() } }, O = function (e) { N.style.display = "block" }, M = function () { N.style.display = "none", t.call(navigator, { video: !0 }, A, O) }, _ = function (e, t, n) { return n < 0 && (n += 1), n > 1 && (n -= 1), n < 1 / 6 ? e + (t - e) * 6 * n : n < .5 ? t : n < 2 / 3 ? e + (t - e) * (2 / 3 - n) * 6 : e }, D = function (e) { return e > 1 ? e - 1 : e < 0 ? 1 + e : e }, P = function (e) { return e > 1 ? 1 : e < 0 ? 0 : e }, H = function () { E.drawImage(T, 0, 0, p, d); var e = E.getImageData(0, 0, p, d), t = e.data; for (var n = 0; n < t.length; n += 4) { var r = t[n] / 255, i = t[n + 1] / 255, s = t[n + 2] / 255, f = Math.max(r, i, s), c = Math.min(r, i, s), h, v, g = (f + c) / 2; if (f == c) h = v = 0; else { var y = f - c; v = g > .5 ? y / (2 - f - c) : y / (f + c), f === r && (h = ((i - s) / y + (i < s ? 6 : 0)) / 6), f === i && (h = ((s - r) / y + 2) / 6), f === s && (h = ((r - i) / y + 4) / 6) } h = D(h + o), v = P(v + u), g = P(g + a); if (v === 0) r = i = s = g; else { var b = g < .5 ? g * (1 + v) : g + v - g * v, w = 2 * g - b; r = _(w, b, h + 1 / 3), i = _(w, b, h), s = _(w, b, h - 1 / 3) } t[n] = r * 255, t[n + 1] = i * 255, t[n + 2] = s * 255 } x.putImageData(e, 0, 0), l === !1 && m(H) }; this.resize(p, d), e.appendChild(b), t ? m(M) : g("notSupported").style.display = "block" }
/**
* jQuery integration. (It's safe to delete this line if you're not using jQuery)
*/
window.jQuery && ($.fn.photobooth = function () { return this.each(function (e, t) { var n = new Photobooth(t); $(t).data("photobooth", n), n.onImage = function (e) { $(t).trigger("image", e) } }) });
/*!
 * mustache.js - Logic-less {{mustache}} templates with JavaScript
 * http://github.com/janl/mustache.js
 */

/*global define: false Mustache: true*/

(function defineMustache (global, factory) {
  if (typeof exports === 'object' && exports && typeof exports.nodeName !== 'string') {
    factory(exports); // CommonJS
  } else if (typeof define === 'function' && define.amd) {
    define(['exports'], factory); // AMD
  } else {
    global.Mustache = {};
    factory(global.Mustache); // script, wsh, asp
  }
}(this, function mustacheFactory (mustache) {

  var objectToString = Object.prototype.toString;
  var isArray = Array.isArray || function isArrayPolyfill (object) {
    return objectToString.call(object) === '[object Array]';
  };

  function isFunction (object) {
    return typeof object === 'function';
  }

  /**
   * More correct typeof string handling array
   * which normally returns typeof 'object'
   */
  function typeStr (obj) {
    return isArray(obj) ? 'array' : typeof obj;
  }

  function escapeRegExp (string) {
    return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
  }

  /**
   * Null safe way of checking whether or not an object,
   * including its prototype, has a given property
   */
  function hasProperty (obj, propName) {
    return obj != null && typeof obj === 'object' && (propName in obj);
  }

  // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
  // See https://github.com/janl/mustache.js/issues/189
  var regExpTest = RegExp.prototype.test;
  function testRegExp (re, string) {
    return regExpTest.call(re, string);
  }

  var nonSpaceRe = /\S/;
  function isWhitespace (string) {
    return !testRegExp(nonSpaceRe, string);
  }

  var entityMap = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;',
    '/': '&#x2F;',
    '`': '&#x60;',
    '=': '&#x3D;'
  };

  function escapeHtml (string) {
    return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap (s) {
      return entityMap[s];
    });
  }

  var whiteRe = /\s*/;
  var spaceRe = /\s+/;
  var equalsRe = /\s*=/;
  var curlyRe = /\s*\}/;
  var tagRe = /#|\^|\/|>|\{|&|=|!/;

  /**
   * Breaks up the given `template` string into a tree of tokens. If the `tags`
   * argument is given here it must be an array with two string values: the
   * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
   * course, the default is to use mustaches (i.e. mustache.tags).
   *
   * A token is an array with at least 4 elements. The first element is the
   * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
   * did not contain a symbol (i.e. {{myValue}}) this element is "name". For
   * all text that appears outside a symbol this element is "text".
   *
   * The second element of a token is its "value". For mustache tags this is
   * whatever else was inside the tag besides the opening symbol. For text tokens
   * this is the text itself.
   *
   * The third and fourth elements of the token are the start and end indices,
   * respectively, of the token in the original template.
   *
   * Tokens that are the root node of a subtree contain two more elements: 1) an
   * array of tokens in the subtree and 2) the index in the original template at
   * which the closing tag for that section begins.
   */
  function parseTemplate (template, tags) {
    if (!template)
      return [];

    var sections = [];     // Stack to hold section tokens
    var tokens = [];       // Buffer to hold the tokens
    var spaces = [];       // Indices of whitespace tokens on the current line
    var hasTag = false;    // Is there a {{tag}} on the current line?
    var nonSpace = false;  // Is there a non-space char on the current line?

    // Strips all whitespace tokens array for the current line
    // if there was a {{#tag}} on it and otherwise only space.
    function stripSpace () {
      if (hasTag && !nonSpace) {
        while (spaces.length)
          delete tokens[spaces.pop()];
      } else {
        spaces = [];
      }

      hasTag = false;
      nonSpace = false;
    }

    var openingTagRe, closingTagRe, closingCurlyRe;
    function compileTags (tagsToCompile) {
      if (typeof tagsToCompile === 'string')
        tagsToCompile = tagsToCompile.split(spaceRe, 2);

      if (!isArray(tagsToCompile) || tagsToCompile.length !== 2)
        throw new Error('Invalid tags: ' + tagsToCompile);

      openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*');
      closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1]));
      closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1]));
    }

    compileTags(tags || mustache.tags);

    var scanner = new Scanner(template);

    var start, type, value, chr, token, openSection;
    while (!scanner.eos()) {
      start = scanner.pos;

      // Match any text between tags.
      value = scanner.scanUntil(openingTagRe);

      if (value) {
        for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
          chr = value.charAt(i);

          if (isWhitespace(chr)) {
            spaces.push(tokens.length);
          } else {
            nonSpace = true;
          }

          tokens.push([ 'text', chr, start, start + 1 ]);
          start += 1;

          // Check for whitespace on the current line.
          if (chr === '\n')
            stripSpace();
        }
      }

      // Match the opening tag.
      if (!scanner.scan(openingTagRe))
        break;

      hasTag = true;

      // Get the tag type.
      type = scanner.scan(tagRe) || 'name';
      scanner.scan(whiteRe);

      // Get the tag value.
      if (type === '=') {
        value = scanner.scanUntil(equalsRe);
        scanner.scan(equalsRe);
        scanner.scanUntil(closingTagRe);
      } else if (type === '{') {
        value = scanner.scanUntil(closingCurlyRe);
        scanner.scan(curlyRe);
        scanner.scanUntil(closingTagRe);
        type = '&';
      } else {
        value = scanner.scanUntil(closingTagRe);
      }

      // Match the closing tag.
      if (!scanner.scan(closingTagRe))
        throw new Error('Unclosed tag at ' + scanner.pos);

      token = [ type, value, start, scanner.pos ];
      tokens.push(token);

      if (type === '#' || type === '^') {
        sections.push(token);
      } else if (type === '/') {
        // Check section nesting.
        openSection = sections.pop();

        if (!openSection)
          throw new Error('Unopened section "' + value + '" at ' + start);

        if (openSection[1] !== value)
          throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
      } else if (type === 'name' || type === '{' || type === '&') {
        nonSpace = true;
      } else if (type === '=') {
        // Set the tags for the next time around.
        compileTags(value);
      }
    }

    // Make sure there are no open sections when we're done.
    openSection = sections.pop();

    if (openSection)
      throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);

    return nestTokens(squashTokens(tokens));
  }

  /**
   * Combines the values of consecutive text tokens in the given `tokens` array
   * to a single token.
   */
  function squashTokens (tokens) {
    var squashedTokens = [];

    var token, lastToken;
    for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
      token = tokens[i];

      if (token) {
        if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
          lastToken[1] += token[1];
          lastToken[3] = token[3];
        } else {
          squashedTokens.push(token);
          lastToken = token;
        }
      }
    }

    return squashedTokens;
  }

  /**
   * Forms the given array of `tokens` into a nested tree structure where
   * tokens that represent a section have two additional items: 1) an array of
   * all tokens that appear in that section and 2) the index in the original
   * template that represents the end of that section.
   */
  function nestTokens (tokens) {
    var nestedTokens = [];
    var collector = nestedTokens;
    var sections = [];

    var token, section;
    for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
      token = tokens[i];

      switch (token[0]) {
        case '#':
        case '^':
          collector.push(token);
          sections.push(token);
          collector = token[4] = [];
          break;
        case '/':
          section = sections.pop();
          section[5] = token[2];
          collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
          break;
        default:
          collector.push(token);
      }
    }

    return nestedTokens;
  }

  /**
   * A simple string scanner that is used by the template parser to find
   * tokens in template strings.
   */
  function Scanner (string) {
    this.string = string;
    this.tail = string;
    this.pos = 0;
  }

  /**
   * Returns `true` if the tail is empty (end of string).
   */
  Scanner.prototype.eos = function eos () {
    return this.tail === '';
  };

  /**
   * Tries to match the given regular expression at the current position.
   * Returns the matched text if it can match, the empty string otherwise.
   */
  Scanner.prototype.scan = function scan (re) {
    var match = this.tail.match(re);

    if (!match || match.index !== 0)
      return '';

    var string = match[0];

    this.tail = this.tail.substring(string.length);
    this.pos += string.length;

    return string;
  };

  /**
   * Skips all text until the given regular expression can be matched. Returns
   * the skipped string, which is the entire tail if no match can be made.
   */
  Scanner.prototype.scanUntil = function scanUntil (re) {
    var index = this.tail.search(re), match;

    switch (index) {
      case -1:
        match = this.tail;
        this.tail = '';
        break;
      case 0:
        match = '';
        break;
      default:
        match = this.tail.substring(0, index);
        this.tail = this.tail.substring(index);
    }

    this.pos += match.length;

    return match;
  };

  /**
   * Represents a rendering context by wrapping a view object and
   * maintaining a reference to the parent context.
   */
  function Context (view, parentContext) {
    this.view = view;
    this.cache = { '.': this.view };
    this.parent = parentContext;
  }

  /**
   * Creates a new context using the given view with this context
   * as the parent.
   */
  Context.prototype.push = function push (view) {
    return new Context(view, this);
  };

  /**
   * Returns the value of the given name in this context, traversing
   * up the context hierarchy if the value is absent in this context's view.
   */
  Context.prototype.lookup = function lookup (name) {
    var cache = this.cache;

    var value;
    if (cache.hasOwnProperty(name)) {
      value = cache[name];
    } else {
      var context = this, names, index, lookupHit = false;

      while (context) {
        if (name.indexOf('.') > 0) {
          value = context.view;
          names = name.split('.');
          index = 0;

          /**
           * Using the dot notion path in `name`, we descend through the
           * nested objects.
           *
           * To be certain that the lookup has been successful, we have to
           * check if the last object in the path actually has the property
           * we are looking for. We store the result in `lookupHit`.
           *
           * This is specially necessary for when the value has been set to
           * `undefined` and we want to avoid looking up parent contexts.
           **/
          while (value != null && index < names.length) {
            if (index === names.length - 1)
              lookupHit = hasProperty(value, names[index]);

            value = value[names[index++]];
          }
        } else {
          value = context.view[name];
          lookupHit = hasProperty(context.view, name);
        }

        if (lookupHit)
          break;

        context = context.parent;
      }

      cache[name] = value;
    }

    if (isFunction(value))
      value = value.call(this.view);

    return value;
  };

  /**
   * A Writer knows how to take a stream of tokens and render them to a
   * string, given a context. It also maintains a cache of templates to
   * avoid the need to parse the same template twice.
   */
  function Writer () {
    this.cache = {};
  }

  /**
   * Clears all cached templates in this writer.
   */
  Writer.prototype.clearCache = function clearCache () {
    this.cache = {};
  };

  /**
   * Parses and caches the given `template` and returns the array of tokens
   * that is generated from the parse.
   */
  Writer.prototype.parse = function parse (template, tags) {
    var cache = this.cache;
    var tokens = cache[template];

    if (tokens == null)
      tokens = cache[template] = parseTemplate(template, tags);

    return tokens;
  };

  /**
   * High-level method that is used to render the given `template` with
   * the given `view`.
   *
   * The optional `partials` argument may be an object that contains the
   * names and templates of partials that are used in the template. It may
   * also be a function that is used to load partial templates on the fly
   * that takes a single argument: the name of the partial.
   */
  Writer.prototype.render = function render (template, view, partials) {
    var tokens = this.parse(template);
    var context = (view instanceof Context) ? view : new Context(view);
    return this.renderTokens(tokens, context, partials, template);
  };

  /**
   * Low-level method that renders the given array of `tokens` using
   * the given `context` and `partials`.
   *
   * Note: The `originalTemplate` is only ever used to extract the portion
   * of the original template that was contained in a higher-order section.
   * If the template doesn't use higher-order sections, this argument may
   * be omitted.
   */
  Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate) {
    var buffer = '';

    var token, symbol, value;
    for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
      value = undefined;
      token = tokens[i];
      symbol = token[0];

      if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate);
      else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate);
      else if (symbol === '>') value = this.renderPartial(token, context, partials, originalTemplate);
      else if (symbol === '&') value = this.unescapedValue(token, context);
      else if (symbol === 'name') value = this.escapedValue(token, context);
      else if (symbol === 'text') value = this.rawValue(token);

      if (value !== undefined)
        buffer += value;
    }

    return buffer;
  };

  Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate) {
    var self = this;
    var buffer = '';
    var value = context.lookup(token[1]);

    // This function is used to render an arbitrary template
    // in the current context by higher-order sections.
    function subRender (template) {
      return self.render(template, context, partials);
    }

    if (!value) return;

    if (isArray(value)) {
      for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
        buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
      }
    } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
      buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
    } else if (isFunction(value)) {
      if (typeof originalTemplate !== 'string')
        throw new Error('Cannot use higher-order sections without the original template');

      // Extract the portion of the original template that the section contains.
      value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);

      if (value != null)
        buffer += value;
    } else {
      buffer += this.renderTokens(token[4], context, partials, originalTemplate);
    }
    return buffer;
  };

  Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate) {
    var value = context.lookup(token[1]);

    // Use JavaScript's definition of falsy. Include empty arrays.
    // See https://github.com/janl/mustache.js/issues/186
    if (!value || (isArray(value) && value.length === 0))
      return this.renderTokens(token[4], context, partials, originalTemplate);
  };

  Writer.prototype.renderPartial = function renderPartial (token, context, partials) {
    if (!partials) return;

    var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
    if (value != null)
      return this.renderTokens(this.parse(value), context, partials, value);
  };

  Writer.prototype.unescapedValue = function unescapedValue (token, context) {
    var value = context.lookup(token[1]);
    if (value != null)
      return value;
  };

  Writer.prototype.escapedValue = function escapedValue (token, context) {
    var value = context.lookup(token[1]);
    if (value != null)
      return mustache.escape(value);
  };

  Writer.prototype.rawValue = function rawValue (token) {
    return token[1];
  };

  mustache.name = 'mustache.js';
  mustache.version = '2.2.1';
  mustache.tags = [ '{{', '}}' ];

  // All high-level mustache.* functions use this writer.
  var defaultWriter = new Writer();

  /**
   * Clears all cached templates in the default writer.
   */
  mustache.clearCache = function clearCache () {
    return defaultWriter.clearCache();
  };

  /**
   * Parses and caches the given template in the default writer and returns the
   * array of tokens it contains. Doing this ahead of time avoids the need to
   * parse templates on the fly as they are rendered.
   */
  mustache.parse = function parse (template, tags) {
    return defaultWriter.parse(template, tags);
  };

  /**
   * Renders the `template` with the given `view` and `partials` using the
   * default writer.
   */
  mustache.render = function render (template, view, partials) {
    if (typeof template !== 'string') {
      throw new TypeError('Invalid template! Template should be a "string" ' +
                          'but "' + typeStr(template) + '" was given as the first ' +
                          'argument for mustache#render(template, view, partials)');
    }

    return defaultWriter.render(template, view, partials);
  };

  // This is here for backwards compatibility with 0.4.x.,
  /*eslint-disable */ // eslint wants camel cased function name
  mustache.to_html = function to_html (template, view, partials, send) {
    /*eslint-enable*/

    var result = mustache.render(template, view, partials);

    if (isFunction(send)) {
      send(result);
    } else {
      return result;
    }
  };

  // Export the escaping function so that the user may override it.
  // See https://github.com/janl/mustache.js/issues/244
  mustache.escape = escapeHtml;

  // Export these mainly for testing, but also for advanced usage.
  mustache.Scanner = Scanner;
  mustache.Context = Context;
  mustache.Writer = Writer;

}));
;
/*!
 * Bootstrap v3.3.6 (http://getbootstrap.com)
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under the MIT license
 */

if (typeof jQuery === 'undefined') {
    throw new Error('Bootstrap\'s JavaScript requires jQuery')
}

+function ($) {
    'use strict';
    var version = $.fn.jquery.split(' ')[0].split('.')
    if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 2)) {
        throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3')
    }
}(jQuery);

/* ========================================================================
 * Bootstrap: transition.js v3.3.6
 * http://getbootstrap.com/javascript/#transitions
 * ========================================================================
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
    'use strict';

    // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
    // ============================================================

    function transitionEnd() {
        var el = document.createElement('bootstrap')

        var transEndEventNames = {
            WebkitTransition: 'webkitTransitionEnd',
            MozTransition: 'transitionend',
            OTransition: 'oTransitionEnd otransitionend',
            transition: 'transitionend'
        }

        for (var name in transEndEventNames) {
            if (el.style[name] !== undefined) {
                return { end: transEndEventNames[name] }
            }
        }

        return false // explicit for ie8 (  ._.)
    }

    // http://blog.alexmaccaw.com/css-transitions
    $.fn.emulateTransitionEnd = function (duration) {
        var called = false
        var $el = this
        $(this).one('bsTransitionEnd', function () { called = true })
        var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
        setTimeout(callback, duration)
        return this
    }

    $(function () {
        $.support.transition = transitionEnd()

        if (!$.support.transition) return

        $.event.special.bsTransitionEnd = {
            bindType: $.support.transition.end,
            delegateType: $.support.transition.end,
            handle: function (e) {
                if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
            }
        }
    })

}(jQuery);

/* ========================================================================
 * Bootstrap: alert.js v3.3.6
 * http://getbootstrap.com/javascript/#alerts
 * ========================================================================
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
    'use strict';

    // ALERT CLASS DEFINITION
    // ======================

    var dismiss = '[data-dismiss="alert"]'
    var Alert = function (el) {
        $(el).on('click', dismiss, this.close)
    }

    Alert.VERSION = '3.3.6'

    Alert.TRANSITION_DURATION = 150

    Alert.prototype.close = function (e) {
        var $this = $(this)
        var selector = $this.attr('data-target')

        if (!selector) {
            selector = $this.attr('href')
            selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
        }

        var $parent = $(selector)

        if (e) e.preventDefault()

        if (!$parent.length) {
            $parent = $this.closest('.alert')
        }

        $parent.trigger(e = $.Event('close.bs.alert'))

        if (e.isDefaultPrevented()) return

        $parent.removeClass('in')

        function removeElement() {
            // detach from parent, fire event then clean up data
            $parent.detach().trigger('closed.bs.alert').remove()
        }

        $.support.transition && $parent.hasClass('fade') ?
          $parent
            .one('bsTransitionEnd', removeElement)
            .emulateTransitionEnd(Alert.TRANSITION_DURATION) :
          removeElement()
    }


    // ALERT PLUGIN DEFINITION
    // =======================

    function Plugin(option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.alert')

            if (!data) $this.data('bs.alert', (data = new Alert(this)))
            if (typeof option == 'string') data[option].call($this)
        })
    }

    var old = $.fn.alert

    $.fn.alert = Plugin
    $.fn.alert.Constructor = Alert


    // ALERT NO CONFLICT
    // =================

    $.fn.alert.noConflict = function () {
        $.fn.alert = old
        return this
    }


    // ALERT DATA-API
    // ==============

    $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)

}(jQuery);

/* ========================================================================
 * Bootstrap: button.js v3.3.6
 * http://getbootstrap.com/javascript/#buttons
 * ========================================================================
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
    'use strict';

    // BUTTON PUBLIC CLASS DEFINITION
    // ==============================

    var Button = function (element, options) {
        this.$element = $(element)
        this.options = $.extend({}, Button.DEFAULTS, options)
        this.isLoading = false
    }

    Button.VERSION = '3.3.6'

    Button.DEFAULTS = {
        loadingText: 'loading...'
    }

    Button.prototype.setState = function (state) {
        var d = 'disabled'
        var $el = this.$element
        var val = $el.is('input') ? 'val' : 'html'
        var data = $el.data()

        state += 'Text'

        if (data.resetText == null) $el.data('resetText', $el[val]())

        // push to event loop to allow forms to submit
        setTimeout($.proxy(function () {
            $el[val](data[state] == null ? this.options[state] : data[state])

            if (state == 'loadingText') {
                this.isLoading = true
                $el.addClass(d).attr(d, d)
            } else if (this.isLoading) {
                this.isLoading = false
                $el.removeClass(d).removeAttr(d)
            }
        }, this), 0)
    }

    Button.prototype.toggle = function () {
        var changed = true
        var $parent = this.$element.closest('[data-toggle="buttons"]')

        if ($parent.length) {
            var $input = this.$element.find('input')
            if ($input.prop('type') == 'radio') {
                if ($input.prop('checked')) changed = false
                $parent.find('.active').removeClass('active')
                this.$element.addClass('active')
            } else if ($input.prop('type') == 'checkbox') {
                if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false
                this.$element.toggleClass('active')
            }
            $input.prop('checked', this.$element.hasClass('active'))
            if (changed) $input.trigger('change')
        } else {
            this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
            this.$element.toggleClass('active')
        }
    }


    // BUTTON PLUGIN DEFINITION
    // ========================

    function Plugin(option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.button')
            var options = typeof option == 'object' && option

            if (!data) $this.data('bs.button', (data = new Button(this, options)))

            if (option == 'toggle') data.toggle()
            else if (option) data.setState(option)
        })
    }

    var old = $.fn.button

    $.fn.button = Plugin
    $.fn.button.Constructor = Button


    // BUTTON NO CONFLICT
    // ==================

    $.fn.button.noConflict = function () {
        $.fn.button = old
        return this
    }


    // BUTTON DATA-API
    // ===============

    $(document)
      .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
          var $btn = $(e.target)
          if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
          Plugin.call($btn, 'toggle')
          if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) e.preventDefault()
      })
      .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
          $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
      })

}(jQuery);

/* ========================================================================
 * Bootstrap: carousel.js v3.3.6
 * http://getbootstrap.com/javascript/#carousel
 * ========================================================================
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
    'use strict';

    // CAROUSEL CLASS DEFINITION
    // =========================

    var Carousel = function (element, options) {
        this.$element = $(element)
        this.$indicators = this.$element.find('.carousel-indicators')
        this.options = options
        this.paused = null
        this.sliding = null
        this.interval = null
        this.$active = null
        this.$items = null

        this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))

        this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element
          .on('mouseenter.bs.carousel', $.proxy(this.pause, this))
          .on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
    }

    Carousel.VERSION = '3.3.6'

    Carousel.TRANSITION_DURATION = 600

    Carousel.DEFAULTS = {
        interval: 5000,
        pause: 'hover',
        wrap: true,
        keyboard: true
    }

    Carousel.prototype.keydown = function (e) {
        if (/input|textarea/i.test(e.target.tagName)) return
        switch (e.which) {
            case 37: this.prev(); break
            case 39: this.next(); break
            default: return
        }

        e.preventDefault()
    }

    Carousel.prototype.cycle = function (e) {
        e || (this.paused = false)

        this.interval && clearInterval(this.interval)

        this.options.interval
          && !this.paused
          && (this.interval = setInterval($.proxy(this.next, this), this.options.interval))

        return this
    }

    Carousel.prototype.getItemIndex = function (item) {
        this.$items = item.parent().children('.item')
        return this.$items.index(item || this.$active)
    }

    Carousel.prototype.getItemForDirection = function (direction, active) {
        var activeIndex = this.getItemIndex(active)
        var willWrap = (direction == 'prev' && activeIndex === 0)
                    || (direction == 'next' && activeIndex == (this.$items.length - 1))
        if (willWrap && !this.options.wrap) return active
        var delta = direction == 'prev' ? -1 : 1
        var itemIndex = (activeIndex + delta) % this.$items.length
        return this.$items.eq(itemIndex)
    }

    Carousel.prototype.to = function (pos) {
        var that = this
        var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))

        if (pos > (this.$items.length - 1) || pos < 0) return

        if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
        if (activeIndex == pos) return this.pause().cycle()

        return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
    }

    Carousel.prototype.pause = function (e) {
        e || (this.paused = true)

        if (this.$element.find('.next, .prev').length && $.support.transition) {
            this.$element.trigger($.support.transition.end)
            this.cycle(true)
        }

        this.interval = clearInterval(this.interval)

        return this
    }

    Carousel.prototype.next = function () {
        if (this.sliding) return
        return this.slide('next')
    }

    Carousel.prototype.prev = function () {
        if (this.sliding) return
        return this.slide('prev')
    }

    Carousel.prototype.slide = function (type, next) {
        var $active = this.$element.find('.item.active')
        var $next = next || this.getItemForDirection(type, $active)
        var isCycling = this.interval
        var direction = type == 'next' ? 'left' : 'right'
        var that = this

        if ($next.hasClass('active')) return (this.sliding = false)

        var relatedTarget = $next[0]
        var slideEvent = $.Event('slide.bs.carousel', {
            relatedTarget: relatedTarget,
            direction: direction
        })
        this.$element.trigger(slideEvent)
        if (slideEvent.isDefaultPrevented()) return

        this.sliding = true

        isCycling && this.pause()

        if (this.$indicators.length) {
            this.$indicators.find('.active').removeClass('active')
            var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
            $nextIndicator && $nextIndicator.addClass('active')
        }

        var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
        if ($.support.transition && this.$element.hasClass('slide')) {
            $next.addClass(type)
            $next[0].offsetWidth // force reflow
            $active.addClass(direction)
            $next.addClass(direction)
            $active
              .one('bsTransitionEnd', function () {
                  $next.removeClass([type, direction].join(' ')).addClass('active')
                  $active.removeClass(['active', direction].join(' '))
                  that.sliding = false
                  setTimeout(function () {
                      that.$element.trigger(slidEvent)
                  }, 0)
              })
              .emulateTransitionEnd(Carousel.TRANSITION_DURATION)
        } else {
            $active.removeClass('active')
            $next.addClass('active')
            this.sliding = false
            this.$element.trigger(slidEvent)
        }

        isCycling && this.cycle()

        return this
    }


    // CAROUSEL PLUGIN DEFINITION
    // ==========================

    function Plugin(option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.carousel')
            var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
            var action = typeof option == 'string' ? option : options.slide

            if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
            if (typeof option == 'number') data.to(option)
            else if (action) data[action]()
            else if (options.interval) data.pause().cycle()
        })
    }

    var old = $.fn.carousel

    $.fn.carousel = Plugin
    $.fn.carousel.Constructor = Carousel


    // CAROUSEL NO CONFLICT
    // ====================

    $.fn.carousel.noConflict = function () {
        $.fn.carousel = old
        return this
    }


    // CAROUSEL DATA-API
    // =================

    var clickHandler = function (e) {
        var href
        var $this = $(this)
        var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
        if (!$target.hasClass('carousel')) return
        var options = $.extend({}, $target.data(), $this.data())
        var slideIndex = $this.attr('data-slide-to')
        if (slideIndex) options.interval = false

        Plugin.call($target, options)

        if (slideIndex) {
            $target.data('bs.carousel').to(slideIndex)
        }

        e.preventDefault()
    }

    $(document)
      .on('click.bs.carousel.data-api', '[data-slide]', clickHandler)
      .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler)

    $(window).on('load', function () {
        $('[data-ride="carousel"]').each(function () {
            var $carousel = $(this)
            Plugin.call($carousel, $carousel.data())
        })
    })

}(jQuery);

/* ========================================================================
 * Bootstrap: collapse.js v3.3.6
 * http://getbootstrap.com/javascript/#collapse
 * ========================================================================
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
    'use strict';

    // COLLAPSE PUBLIC CLASS DEFINITION
    // ================================

    var Collapse = function (element, options) {
        this.$element = $(element)
        this.options = $.extend({}, Collapse.DEFAULTS, options)
        this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' +
                               '[data-toggle="collapse"][data-target="#' + element.id + '"]')
        this.transitioning = null

        if (this.options.parent) {
            this.$parent = this.getParent()
        } else {
            this.addAriaAndCollapsedClass(this.$element, this.$trigger)
        }

        if (this.options.toggle) this.toggle()
    }

    Collapse.VERSION = '3.3.6'

    Collapse.TRANSITION_DURATION = 350

    Collapse.DEFAULTS = {
        toggle: true
    }

    Collapse.prototype.dimension = function () {
        var hasWidth = this.$element.hasClass('width')
        return hasWidth ? 'width' : 'height'
    }

    Collapse.prototype.show = function () {
        if (this.transitioning || this.$element.hasClass('in')) return

        var activesData
        var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing')

        if (actives && actives.length) {
            activesData = actives.data('bs.collapse')
            if (activesData && activesData.transitioning) return
        }

        var startEvent = $.Event('show.bs.collapse')
        this.$element.trigger(startEvent)
        if (startEvent.isDefaultPrevented()) return

        if (actives && actives.length) {
            Plugin.call(actives, 'hide')
            activesData || actives.data('bs.collapse', null)
        }

        var dimension = this.dimension()

        this.$element
          .removeClass('collapse')
          .addClass('collapsing')[dimension](0)
          .attr('aria-expanded', true)

        this.$trigger
          .removeClass('collapsed')
          .attr('aria-expanded', true)

        this.transitioning = 1

        var complete = function () {
            this.$element
              .removeClass('collapsing')
              .addClass('collapse in')[dimension]('')
            this.transitioning = 0
            this.$element
              .trigger('shown.bs.collapse')
        }

        if (!$.support.transition) return complete.call(this)

        var scrollSize = $.camelCase(['scroll', dimension].join('-'))

        this.$element
          .one('bsTransitionEnd', $.proxy(complete, this))
          .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
    }

    Collapse.prototype.hide = function () {
        if (this.transitioning || !this.$element.hasClass('in')) return

        var startEvent = $.Event('hide.bs.collapse')
        this.$element.trigger(startEvent)
        if (startEvent.isDefaultPrevented()) return

        var dimension = this.dimension()

        this.$element[dimension](this.$element[dimension]())[0].offsetHeight

        this.$element
          .addClass('collapsing')
          .removeClass('collapse in')
          .attr('aria-expanded', false)

        this.$trigger
          .addClass('collapsed')
          .attr('aria-expanded', false)

        this.transitioning = 1

        var complete = function () {
            this.transitioning = 0
            this.$element
              .removeClass('collapsing')
              .addClass('collapse')
              .trigger('hidden.bs.collapse')
        }

        if (!$.support.transition) return complete.call(this)

        this.$element
          [dimension](0)
          .one('bsTransitionEnd', $.proxy(complete, this))
          .emulateTransitionEnd(Collapse.TRANSITION_DURATION)
    }

    Collapse.prototype.toggle = function () {
        this[this.$element.hasClass('in') ? 'hide' : 'show']()
    }

    Collapse.prototype.getParent = function () {
        return $(this.options.parent)
          .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]')
          .each($.proxy(function (i, element) {
              var $element = $(element)
              this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
          }, this))
          .end()
    }

    Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) {
        var isOpen = $element.hasClass('in')

        $element.attr('aria-expanded', isOpen)
        $trigger
          .toggleClass('collapsed', !isOpen)
          .attr('aria-expanded', isOpen)
    }

    function getTargetFromTrigger($trigger) {
        var href
        var target = $trigger.attr('data-target')
          || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7

        return $(target)
    }


    // COLLAPSE PLUGIN DEFINITION
    // ==========================

    function Plugin(option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.collapse')
            var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)

            if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false
            if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
            if (typeof option == 'string') data[option]()
        })
    }

    var old = $.fn.collapse

    $.fn.collapse = Plugin
    $.fn.collapse.Constructor = Collapse


    // COLLAPSE NO CONFLICT
    // ====================

    $.fn.collapse.noConflict = function () {
        $.fn.collapse = old
        return this
    }


    // COLLAPSE DATA-API
    // =================

    $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
        var $this = $(this)

        if (!$this.attr('data-target')) e.preventDefault()

        var $target = getTargetFromTrigger($this)
        var data = $target.data('bs.collapse')
        var option = data ? 'toggle' : $this.data()

        Plugin.call($target, option)
    })

}(jQuery);

/* ========================================================================
 * Bootstrap: dropdown.js v3.3.6
 * http://getbootstrap.com/javascript/#dropdowns
 * ========================================================================
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
    'use strict';

    // DROPDOWN CLASS DEFINITION
    // =========================

    var backdrop = '.dropdown-backdrop'
    var toggle = '[data-toggle="dropdown"]'
    var Dropdown = function (element) {
        $(element).on('click.bs.dropdown', this.toggle)
    }

    Dropdown.VERSION = '3.3.6'

    function getParent($this) {
        var selector = $this.attr('data-target')

        if (!selector) {
            selector = $this.attr('href')
            selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
        }

        var $parent = selector && $(selector)

        return $parent && $parent.length ? $parent : $this.parent()
    }

    function clearMenus(e) {
        if (e && e.which === 3) return
        $(backdrop).remove()
        $(toggle).each(function () {
            var $this = $(this)
            var $parent = getParent($this)
            var relatedTarget = { relatedTarget: this }

            if (!$parent.hasClass('open')) return

            if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return

            $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))

            if (e.isDefaultPrevented()) return

            $this.attr('aria-expanded', 'false')
            $parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget))
        })
    }

    Dropdown.prototype.toggle = function (e) {
        var $this = $(this)

        if ($this.is('.disabled, :disabled')) return

        var $parent = getParent($this)
        var isActive = $parent.hasClass('open')

        clearMenus()

        if (!isActive) {
            if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
                // if mobile we use a backdrop because click events don't delegate
                $(document.createElement('div'))
                  .addClass('dropdown-backdrop')
                  .insertAfter($(this))
                  .on('click', clearMenus)
            }

            var relatedTarget = { relatedTarget: this }
            $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))

            if (e.isDefaultPrevented()) return

            $this
              .trigger('focus')
              .attr('aria-expanded', 'true')

            $parent
              .toggleClass('open')
              .trigger($.Event('shown.bs.dropdown', relatedTarget))
        }

        return false
    }

    Dropdown.prototype.keydown = function (e) {
        if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return

        var $this = $(this)

        e.preventDefault()
        e.stopPropagation()

        if ($this.is('.disabled, :disabled')) return

        var $parent = getParent($this)
        var isActive = $parent.hasClass('open')

        if (!isActive && e.which != 27 || isActive && e.which == 27) {
            if (e.which == 27) $parent.find(toggle).trigger('focus')
            return $this.trigger('click')
        }

        var desc = ' li:not(.disabled):visible a'
        var $items = $parent.find('.dropdown-menu' + desc)

        if (!$items.length) return

        var index = $items.index(e.target)

        if (e.which == 38 && index > 0) index--         // up
        if (e.which == 40 && index < $items.length - 1) index++         // down
        if (!~index) index = 0

        $items.eq(index).trigger('focus')
    }


    // DROPDOWN PLUGIN DEFINITION
    // ==========================

    function Plugin(option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.dropdown')

            if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
            if (typeof option == 'string') data[option].call($this)
        })
    }

    var old = $.fn.dropdown

    $.fn.dropdown = Plugin
    $.fn.dropdown.Constructor = Dropdown


    // DROPDOWN NO CONFLICT
    // ====================

    $.fn.dropdown.noConflict = function () {
        $.fn.dropdown = old
        return this
    }


    // APPLY TO STANDARD DROPDOWN ELEMENTS
    // ===================================

    $(document)
      .on('click.bs.dropdown.data-api', clearMenus)
      .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
      .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
      .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
      .on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown)

}(jQuery);

/* ========================================================================
 * Bootstrap: modal.js v3.3.6
 * http://getbootstrap.com/javascript/#modals
 * ========================================================================
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
    'use strict';

    // MODAL CLASS DEFINITION
    // ======================

    var Modal = function (element, options) {
        this.options = options
        this.$body = $(document.body)
        this.$element = $(element)
        this.$dialog = this.$element.find('.modal-dialog')
        this.$backdrop = null
        this.isShown = null
        this.originalBodyPad = null
        this.scrollbarWidth = 0
        this.ignoreBackdropClick = false

        if (this.options.remote) {
            this.$element
              .find('.modal-content')
              .load(this.options.remote, $.proxy(function () {
                  this.$element.trigger('loaded.bs.modal')
              }, this))
        }
    }

    Modal.VERSION = '3.3.6'

    Modal.TRANSITION_DURATION = 300
    Modal.BACKDROP_TRANSITION_DURATION = 150

    Modal.DEFAULTS = {
        backdrop: true,
        keyboard: true,
        show: true
    }

    Modal.prototype.toggle = function (_relatedTarget) {
        return this.isShown ? this.hide() : this.show(_relatedTarget)
    }

    Modal.prototype.show = function (_relatedTarget) {
        var that = this
        var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })

        this.$element.trigger(e)

        if (this.isShown || e.isDefaultPrevented()) return

        this.isShown = true

        this.checkScrollbar()
        this.setScrollbar()
        this.$body.addClass('modal-open')

        this.escape()
        this.resize()

        this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))

        this.$dialog.on('mousedown.dismiss.bs.modal', function () {
            that.$element.one('mouseup.dismiss.bs.modal', function (e) {
                if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
            })
        })

        this.backdrop(function () {
            var transition = $.support.transition && that.$element.hasClass('fade')

            if (!that.$element.parent().length) {
                that.$element.appendTo(that.$body) // don't move modals dom position
            }

            that.$element
              .show()
              .scrollTop(0)

            that.adjustDialog()

            if (transition) {
                that.$element[0].offsetWidth // force reflow
            }

            that.$element.addClass('in')

            that.enforceFocus()

            var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })

            transition ?
              that.$dialog // wait for modal to slide in
                .one('bsTransitionEnd', function () {
                    that.$element.trigger('focus').trigger(e)
                })
                .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
              that.$element.trigger('focus').trigger(e)
        })
    }

    Modal.prototype.hide = function (e) {
        if (e) e.preventDefault()

        e = $.Event('hide.bs.modal')

        this.$element.trigger(e)

        if (!this.isShown || e.isDefaultPrevented()) return

        this.isShown = false

        this.escape()
        this.resize()

        $(document).off('focusin.bs.modal')

        this.$element
          .removeClass('in')
          .off('click.dismiss.bs.modal')
          .off('mouseup.dismiss.bs.modal')

        this.$dialog.off('mousedown.dismiss.bs.modal')

        $.support.transition && this.$element.hasClass('fade') ?
          this.$element
            .one('bsTransitionEnd', $.proxy(this.hideModal, this))
            .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
          this.hideModal()
    }

    Modal.prototype.enforceFocus = function () {
        $(document)
          .off('focusin.bs.modal') // guard against infinite focus loop
          .on('focusin.bs.modal', $.proxy(function (e) {
              if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
                  this.$element.trigger('focus')
              }
          }, this))
    }

    Modal.prototype.escape = function () {
        if (this.isShown && this.options.keyboard) {
            this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
                e.which == 27 && this.hide()
            }, this))
        } else if (!this.isShown) {
            this.$element.off('keydown.dismiss.bs.modal')
        }
    }

    Modal.prototype.resize = function () {
        if (this.isShown) {
            $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
        } else {
            $(window).off('resize.bs.modal')
        }
    }

    Modal.prototype.hideModal = function () {
        var that = this
        this.$element.hide()
        this.backdrop(function () {
            that.$body.removeClass('modal-open')
            that.resetAdjustments()
            that.resetScrollbar()
            that.$element.trigger('hidden.bs.modal')
        })
    }

    Modal.prototype.removeBackdrop = function () {
        this.$backdrop && this.$backdrop.remove()
        this.$backdrop = null
    }

    Modal.prototype.backdrop = function (callback) {
        var that = this
        var animate = this.$element.hasClass('fade') ? 'fade' : ''

        if (this.isShown && this.options.backdrop) {
            var doAnimate = $.support.transition && animate

            this.$backdrop = $(document.createElement('div'))
              .addClass('modal-backdrop ' + animate)
              .appendTo(this.$body)

            this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
                if (this.ignoreBackdropClick) {
                    this.ignoreBackdropClick = false
                    return
                }
                if (e.target !== e.currentTarget) return
                this.options.backdrop == 'static'
                  ? this.$element[0].focus()
                  : this.hide()
            }, this))

            if (doAnimate) this.$backdrop[0].offsetWidth // force reflow

            this.$backdrop.addClass('in')

            if (!callback) return

            doAnimate ?
              this.$backdrop
                .one('bsTransitionEnd', callback)
                .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
              callback()

        } else if (!this.isShown && this.$backdrop) {
            this.$backdrop.removeClass('in')

            var callbackRemove = function () {
                that.removeBackdrop()
                callback && callback()
            }
            $.support.transition && this.$element.hasClass('fade') ?
              this.$backdrop
                .one('bsTransitionEnd', callbackRemove)
                .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
              callbackRemove()

        } else if (callback) {
            callback()
        }
    }

    // these following methods are used to handle overflowing modals

    Modal.prototype.handleUpdate = function () {
        this.adjustDialog()
    }

    Modal.prototype.adjustDialog = function () {
        var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight

        this.$element.css({
            paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
            paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
        })
    }

    Modal.prototype.resetAdjustments = function () {
        this.$element.css({
            paddingLeft: '',
            paddingRight: ''
        })
    }

    Modal.prototype.checkScrollbar = function () {
        var fullWindowWidth = window.innerWidth
        if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
            var documentElementRect = document.documentElement.getBoundingClientRect()
            fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
        }
        this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
        this.scrollbarWidth = this.measureScrollbar()
    }

    Modal.prototype.setScrollbar = function () {
        var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
        this.originalBodyPad = document.body.style.paddingRight || ''
        if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
    }

    Modal.prototype.resetScrollbar = function () {
        this.$body.css('padding-right', this.originalBodyPad)
    }

    Modal.prototype.measureScrollbar = function () { // thx walsh
        var scrollDiv = document.createElement('div')
        scrollDiv.className = 'modal-scrollbar-measure'
        this.$body.append(scrollDiv)
        var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
        this.$body[0].removeChild(scrollDiv)
        return scrollbarWidth
    }


    // MODAL PLUGIN DEFINITION
    // =======================

    function Plugin(option, _relatedTarget) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.modal')
            var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)

            if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
            if (typeof option == 'string') data[option](_relatedTarget)
            else if (options.show) data.show(_relatedTarget)
        })
    }

    var old = $.fn.modal

    $.fn.modal = Plugin
    $.fn.modal.Constructor = Modal


    // MODAL NO CONFLICT
    // =================

    $.fn.modal.noConflict = function () {
        $.fn.modal = old
        return this
    }


    // MODAL DATA-API
    // ==============

    $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
        var $this = $(this)
        var href = $this.attr('href')
        var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
        var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())

        if ($this.is('a')) e.preventDefault()

        $target.one('show.bs.modal', function (showEvent) {
            if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
            $target.one('hidden.bs.modal', function () {
                $this.is(':visible') && $this.trigger('focus')
            })
        })
        Plugin.call($target, option, this)
    })

}(jQuery);

/* ========================================================================
 * Bootstrap: tooltip.js v3.3.6
 * http://getbootstrap.com/javascript/#tooltip
 * Inspired by the original jQuery.tipsy by Jason Frame
 * ========================================================================
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
    'use strict';

    // TOOLTIP PUBLIC CLASS DEFINITION
    // ===============================

    var Tooltip = function (element, options) {
        this.type = null
        this.options = null
        this.enabled = null
        this.timeout = null
        this.hoverState = null
        this.$element = null
        this.inState = null

        this.init('tooltip', element, options)
    }

    Tooltip.VERSION = '3.3.6'

    Tooltip.TRANSITION_DURATION = 150

    Tooltip.DEFAULTS = {
        animation: true,
        placement: 'top',
        selector: false,
        template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
        trigger: 'hover focus',
        title: '',
        delay: 0,
        html: false,
        container: false,
        viewport: {
            selector: 'body',
            padding: 0
        }
    }

    Tooltip.prototype.init = function (type, element, options) {
        this.enabled = true
        this.type = type
        this.$element = $(element)
        this.options = this.getOptions(options)
        this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport))
        this.inState = { click: false, hover: false, focus: false }

        if (this.$element[0] instanceof document.constructor && !this.options.selector) {
            throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!')
        }

        var triggers = this.options.trigger.split(' ')

        for (var i = triggers.length; i--;) {
            var trigger = triggers[i]

            if (trigger == 'click') {
                this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
            } else if (trigger != 'manual') {
                var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
                var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'

                this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
                this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
            }
        }

        this.options.selector ?
          (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
          this.fixTitle()
    }

    Tooltip.prototype.getDefaults = function () {
        return Tooltip.DEFAULTS
    }

    Tooltip.prototype.getOptions = function (options) {
        options = $.extend({}, this.getDefaults(), this.$element.data(), options)

        if (options.delay && typeof options.delay == 'number') {
            options.delay = {
                show: options.delay,
                hide: options.delay
            }
        }

        return options
    }

    Tooltip.prototype.getDelegateOptions = function () {
        var options = {}
        var defaults = this.getDefaults()

        this._options && $.each(this._options, function (key, value) {
            if (defaults[key] != value) options[key] = value
        })

        return options
    }

    Tooltip.prototype.enter = function (obj) {
        var self = obj instanceof this.constructor ?
            obj : $(obj.currentTarget).data('bs.' + this.type)

        if (!self) {
            self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
            $(obj.currentTarget).data('bs.' + this.type, self)
        }

        if (obj instanceof $.Event) {
            self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true
        }

        if (self.tip().hasClass('in') || self.hoverState == 'in') {
            self.hoverState = 'in'
            return
        }

        clearTimeout(self.timeout)

        self.hoverState = 'in'

        if (!self.options.delay || !self.options.delay.show) return self.show()

        self.timeout = setTimeout(function () {
            if (self.hoverState == 'in') self.show()
        }, self.options.delay.show)
    }

    Tooltip.prototype.isInStateTrue = function () {
        for (var key in this.inState) {
            if (this.inState[key]) return true
        }

        return false
    }

    Tooltip.prototype.leave = function (obj) {
        var self = obj instanceof this.constructor ?
            obj : $(obj.currentTarget).data('bs.' + this.type)

        if (!self) {
            self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
            $(obj.currentTarget).data('bs.' + this.type, self)
        }

        if (obj instanceof $.Event) {
            self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false
        }

        if (self.isInStateTrue()) return

        clearTimeout(self.timeout)

        self.hoverState = 'out'

        if (!self.options.delay || !self.options.delay.hide) return self.hide()

        self.timeout = setTimeout(function () {
            if (self.hoverState == 'out') self.hide()
        }, self.options.delay.hide)
    }

    Tooltip.prototype.show = function () {
        var e = $.Event('show.bs.' + this.type)

        if (this.hasContent() && this.enabled) {
            this.$element.trigger(e)

            var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
            if (e.isDefaultPrevented() || !inDom) return
            var that = this

            var $tip = this.tip()

            var tipId = this.getUID(this.type)

            this.setContent()
            $tip.attr('id', tipId)
            this.$element.attr('aria-describedby', tipId)

            if (this.options.animation) $tip.addClass('fade')

            var placement = typeof this.options.placement == 'function' ?
              this.options.placement.call(this, $tip[0], this.$element[0]) :
              this.options.placement

            var autoToken = /\s?auto?\s?/i
            var autoPlace = autoToken.test(placement)
            if (autoPlace) placement = placement.replace(autoToken, '') || 'top'

            $tip
              .detach()
              .css({ top: 0, left: 0, display: 'block' })
              .addClass(placement)
              .data('bs.' + this.type, this)

            this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
            this.$element.trigger('inserted.bs.' + this.type)

            var pos = this.getPosition()
            var actualWidth = $tip[0].offsetWidth
            var actualHeight = $tip[0].offsetHeight

            if (autoPlace) {
                var orgPlacement = placement
                var viewportDim = this.getPosition(this.$viewport)

                placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' :
                            placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' :
                            placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' :
                            placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' :
                            placement

                $tip
                  .removeClass(orgPlacement)
                  .addClass(placement)
            }

            var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)

            this.applyPlacement(calculatedOffset, placement)

            var complete = function () {
                var prevHoverState = that.hoverState
                that.$element.trigger('shown.bs.' + that.type)
                that.hoverState = null

                if (prevHoverState == 'out') that.leave(that)
            }

            $.support.transition && this.$tip.hasClass('fade') ?
              $tip
                .one('bsTransitionEnd', complete)
                .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
              complete()
        }
    }

    Tooltip.prototype.applyPlacement = function (offset, placement) {
        var $tip = this.tip()
        var width = $tip[0].offsetWidth
        var height = $tip[0].offsetHeight

        // manually read margins because getBoundingClientRect includes difference
        var marginTop = parseInt($tip.css('margin-top'), 10)
        var marginLeft = parseInt($tip.css('margin-left'), 10)

        // we must check for NaN for ie 8/9
        if (isNaN(marginTop)) marginTop = 0
        if (isNaN(marginLeft)) marginLeft = 0

        offset.top += marginTop
        offset.left += marginLeft

        // $.fn.offset doesn't round pixel values
        // so we use setOffset directly with our own function B-0
        $.offset.setOffset($tip[0], $.extend({
            using: function (props) {
                $tip.css({
                    top: Math.round(props.top),
                    left: Math.round(props.left)
                })
            }
        }, offset), 0)

        $tip.addClass('in')

        // check to see if placing tip in new offset caused the tip to resize itself
        var actualWidth = $tip[0].offsetWidth
        var actualHeight = $tip[0].offsetHeight

        if (placement == 'top' && actualHeight != height) {
            offset.top = offset.top + height - actualHeight
        }

        var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)

        if (delta.left) offset.left += delta.left
        else offset.top += delta.top

        var isVertical = /top|bottom/.test(placement)
        var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
        var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'

        $tip.offset(offset)
        this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
    }

    Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) {
        this.arrow()
          .css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
          .css(isVertical ? 'top' : 'left', '')
    }

    Tooltip.prototype.setContent = function () {
        var $tip = this.tip()
        var title = this.getTitle()

        $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
        $tip.removeClass('fade in top bottom left right')
    }

    Tooltip.prototype.hide = function (callback) {
        var that = this
        var $tip = $(this.$tip)
        var e = $.Event('hide.bs.' + this.type)

        function complete() {
            if (that.hoverState != 'in') $tip.detach()
            that.$element
              .removeAttr('aria-describedby')
              .trigger('hidden.bs.' + that.type)
            callback && callback()
        }

        this.$element.trigger(e)

        if (e.isDefaultPrevented()) return

        $tip.removeClass('in')

        $.support.transition && $tip.hasClass('fade') ?
          $tip
            .one('bsTransitionEnd', complete)
            .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
          complete()

        this.hoverState = null

        return this
    }

    Tooltip.prototype.fixTitle = function () {
        var $e = this.$element
        if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') {
            $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
        }
    }

    Tooltip.prototype.hasContent = function () {
        return this.getTitle()
    }

    Tooltip.prototype.getPosition = function ($element) {
        $element = $element || this.$element

        var el = $element[0]
        var isBody = el.tagName == 'BODY'

        var elRect = el.getBoundingClientRect()
        if (elRect.width == null) {
            // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
            elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
        }
        var elOffset = isBody ? { top: 0, left: 0 } : $element.offset()
        var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
        var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null

        return $.extend({}, elRect, scroll, outerDims, elOffset)
    }

    Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
        return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
               placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
               placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
            /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }

    }

    Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
        var delta = { top: 0, left: 0 }
        if (!this.$viewport) return delta

        var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
        var viewportDimensions = this.getPosition(this.$viewport)

        if (/right|left/.test(placement)) {
            var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
            var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
            if (topEdgeOffset < viewportDimensions.top) { // top overflow
                delta.top = viewportDimensions.top - topEdgeOffset
            } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
                delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
            }
        } else {
            var leftEdgeOffset = pos.left - viewportPadding
            var rightEdgeOffset = pos.left + viewportPadding + actualWidth
            if (leftEdgeOffset < viewportDimensions.left) { // left overflow
                delta.left = viewportDimensions.left - leftEdgeOffset
            } else if (rightEdgeOffset > viewportDimensions.right) { // right overflow
                delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
            }
        }

        return delta
    }

    Tooltip.prototype.getTitle = function () {
        var title
        var $e = this.$element
        var o = this.options

        title = $e.attr('data-original-title')
          || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)

        return title
    }

    Tooltip.prototype.getUID = function (prefix) {
        do prefix += ~~(Math.random() * 1000000)
        while (document.getElementById(prefix))
        return prefix
    }

    Tooltip.prototype.tip = function () {
        if (!this.$tip) {
            this.$tip = $(this.options.template)
            if (this.$tip.length != 1) {
                throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!')
            }
        }
        return this.$tip
    }

    Tooltip.prototype.arrow = function () {
        return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
    }

    Tooltip.prototype.enable = function () {
        this.enabled = true
    }

    Tooltip.prototype.disable = function () {
        this.enabled = false
    }

    Tooltip.prototype.toggleEnabled = function () {
        this.enabled = !this.enabled
    }

    Tooltip.prototype.toggle = function (e) {
        var self = this
        if (e) {
            self = $(e.currentTarget).data('bs.' + this.type)
            if (!self) {
                self = new this.constructor(e.currentTarget, this.getDelegateOptions())
                $(e.currentTarget).data('bs.' + this.type, self)
            }
        }

        if (e) {
            self.inState.click = !self.inState.click
            if (self.isInStateTrue()) self.enter(self)
            else self.leave(self)
        } else {
            self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
        }
    }

    Tooltip.prototype.destroy = function () {
        var that = this
        clearTimeout(this.timeout)
        this.hide(function () {
            that.$element.off('.' + that.type).removeData('bs.' + that.type)
            if (that.$tip) {
                that.$tip.detach()
            }
            that.$tip = null
            that.$arrow = null
            that.$viewport = null
        })
    }


    // TOOLTIP PLUGIN DEFINITION
    // =========================

    function Plugin(option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.tooltip')
            var options = typeof option == 'object' && option

            if (!data && /destroy|hide/.test(option)) return
            if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
            if (typeof option == 'string') data[option]()
        })
    }

    var old = $.fn.tooltip

    $.fn.tooltip = Plugin
    $.fn.tooltip.Constructor = Tooltip


    // TOOLTIP NO CONFLICT
    // ===================

    $.fn.tooltip.noConflict = function () {
        $.fn.tooltip = old
        return this
    }

}(jQuery);

/* ========================================================================
 * Bootstrap: popover.js v3.3.6
 * http://getbootstrap.com/javascript/#popovers
 * ========================================================================
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
    'use strict';

    // POPOVER PUBLIC CLASS DEFINITION
    // ===============================

    var Popover = function (element, options) {
        this.init('popover', element, options)
    }

    if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')

    Popover.VERSION = '3.3.6'

    Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
        placement: 'right',
        trigger: 'click',
        content: '',
        template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
    })


    // NOTE: POPOVER EXTENDS tooltip.js
    // ================================

    Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)

    Popover.prototype.constructor = Popover

    Popover.prototype.getDefaults = function () {
        return Popover.DEFAULTS
    }

    Popover.prototype.setContent = function () {
        var $tip = this.tip()
        var title = this.getTitle()
        var content = this.getContent()

        $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
        $tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events
          this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
        ](content)

        $tip.removeClass('fade top bottom left right in')

        // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
        // this manually by checking the contents.
        if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
    }

    Popover.prototype.hasContent = function () {
        return this.getTitle() || this.getContent()
    }

    Popover.prototype.getContent = function () {
        var $e = this.$element
        var o = this.options

        return $e.attr('data-content')
          || (typeof o.content == 'function' ?
                o.content.call($e[0]) :
                o.content)
    }

    Popover.prototype.arrow = function () {
        return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
    }


    // POPOVER PLUGIN DEFINITION
    // =========================

    function Plugin(option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.popover')
            var options = typeof option == 'object' && option

            if (!data && /destroy|hide/.test(option)) return
            if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
            if (typeof option == 'string') data[option]()
        })
    }

    var old = $.fn.popover

    $.fn.popover = Plugin
    $.fn.popover.Constructor = Popover


    // POPOVER NO CONFLICT
    // ===================

    $.fn.popover.noConflict = function () {
        $.fn.popover = old
        return this
    }

}(jQuery);

/* ========================================================================
 * Bootstrap: scrollspy.js v3.3.6
 * http://getbootstrap.com/javascript/#scrollspy
 * ========================================================================
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
    'use strict';

    // SCROLLSPY CLASS DEFINITION
    // ==========================

    function ScrollSpy(element, options) {
        this.$body = $(document.body)
        this.$scrollElement = $(element).is(document.body) ? $(window) : $(element)
        this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
        this.selector = (this.options.target || '') + ' .nav li > a'
        this.offsets = []
        this.targets = []
        this.activeTarget = null
        this.scrollHeight = 0

        this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this))
        this.refresh()
        this.process()
    }

    ScrollSpy.VERSION = '3.3.6'

    ScrollSpy.DEFAULTS = {
        offset: 10
    }

    ScrollSpy.prototype.getScrollHeight = function () {
        return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
    }

    ScrollSpy.prototype.refresh = function () {
        var that = this
        var offsetMethod = 'offset'
        var offsetBase = 0

        this.offsets = []
        this.targets = []
        this.scrollHeight = this.getScrollHeight()

        if (!$.isWindow(this.$scrollElement[0])) {
            offsetMethod = 'position'
            offsetBase = this.$scrollElement.scrollTop()
        }

        this.$body
          .find(this.selector)
          .map(function () {
              var $el = $(this)
              var href = $el.data('target') || $el.attr('href')
              var $href = /^#./.test(href) && $(href)

              return ($href
                && $href.length
                && $href.is(':visible')
                && [[$href[offsetMethod]().top + offsetBase, href]]) || null
          })
          .sort(function (a, b) { return a[0] - b[0] })
          .each(function () {
              that.offsets.push(this[0])
              that.targets.push(this[1])
          })
    }

    ScrollSpy.prototype.process = function () {
        var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
        var scrollHeight = this.getScrollHeight()
        var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
        var offsets = this.offsets
        var targets = this.targets
        var activeTarget = this.activeTarget
        var i

        if (this.scrollHeight != scrollHeight) {
            this.refresh()
        }

        if (scrollTop >= maxScroll) {
            return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
        }

        if (activeTarget && scrollTop < offsets[0]) {
            this.activeTarget = null
            return this.clear()
        }

        for (i = offsets.length; i--;) {
            activeTarget != targets[i]
              && scrollTop >= offsets[i]
              && (offsets[i + 1] === undefined || scrollTop < offsets[i + 1])
              && this.activate(targets[i])
        }
    }

    ScrollSpy.prototype.activate = function (target) {
        this.activeTarget = target

        this.clear()

        var selector = this.selector +
          '[data-target="' + target + '"],' +
          this.selector + '[href="' + target + '"]'

        var active = $(selector)
          .parents('li')
          .addClass('active')

        if (active.parent('.dropdown-menu').length) {
            active = active
              .closest('li.dropdown')
              .addClass('active')
        }

        active.trigger('activate.bs.scrollspy')
    }

    ScrollSpy.prototype.clear = function () {
        $(this.selector)
          .parentsUntil(this.options.target, '.active')
          .removeClass('active')
    }


    // SCROLLSPY PLUGIN DEFINITION
    // ===========================

    function Plugin(option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.scrollspy')
            var options = typeof option == 'object' && option

            if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
            if (typeof option == 'string') data[option]()
        })
    }

    var old = $.fn.scrollspy

    $.fn.scrollspy = Plugin
    $.fn.scrollspy.Constructor = ScrollSpy


    // SCROLLSPY NO CONFLICT
    // =====================

    $.fn.scrollspy.noConflict = function () {
        $.fn.scrollspy = old
        return this
    }


    // SCROLLSPY DATA-API
    // ==================

    $(window).on('load.bs.scrollspy.data-api', function () {
        $('[data-spy="scroll"]').each(function () {
            var $spy = $(this)
            Plugin.call($spy, $spy.data())
        })
    })

}(jQuery);

/* ========================================================================
 * Bootstrap: tab.js v3.3.6
 * http://getbootstrap.com/javascript/#tabs
 * ========================================================================
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
    'use strict';

    // TAB CLASS DEFINITION
    // ====================

    var Tab = function (element) {
        // jscs:disable requireDollarBeforejQueryAssignment
        this.element = $(element)
        // jscs:enable requireDollarBeforejQueryAssignment
    }

    Tab.VERSION = '3.3.6'

    Tab.TRANSITION_DURATION = 150

    Tab.prototype.show = function () {
        var $this = this.element
        var $ul = $this.closest('ul:not(.dropdown-menu)')
        var selector = $this.data('target')

        if (!selector) {
            selector = $this.attr('href')
            selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
        }

        if ($this.parent('li').hasClass('active')) return

        var $previous = $ul.find('.active:last a')
        var hideEvent = $.Event('hide.bs.tab', {
            relatedTarget: $this[0]
        })
        var showEvent = $.Event('show.bs.tab', {
            relatedTarget: $previous[0]
        })

        $previous.trigger(hideEvent)
        $this.trigger(showEvent)

        if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return

        var $target = $(selector)

        this.activate($this.closest('li'), $ul)
        this.activate($target, $target.parent(), function () {
            $previous.trigger({
                type: 'hidden.bs.tab',
                relatedTarget: $this[0]
            })
            $this.trigger({
                type: 'shown.bs.tab',
                relatedTarget: $previous[0]
            })
        })
    }

    Tab.prototype.activate = function (element, container, callback) {
        var $active = container.find('> .active')
        var transition = callback
          && $.support.transition
          && ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length)

        function next() {
            $active
              .removeClass('active')
              .find('> .dropdown-menu > .active')
                .removeClass('active')
              .end()
              .find('[data-toggle="tab"]')
                .attr('aria-expanded', false)

            element
              .addClass('active')
              .find('[data-toggle="tab"]')
                .attr('aria-expanded', true)

            if (transition) {
                element[0].offsetWidth // reflow for transition
                element.addClass('in')
            } else {
                element.removeClass('fade')
            }

            if (element.parent('.dropdown-menu').length) {
                element
                  .closest('li.dropdown')
                    .addClass('active')
                  .end()
                  .find('[data-toggle="tab"]')
                    .attr('aria-expanded', true)
            }

            callback && callback()
        }

        $active.length && transition ?
          $active
            .one('bsTransitionEnd', next)
            .emulateTransitionEnd(Tab.TRANSITION_DURATION) :
          next()

        $active.removeClass('in')
    }


    // TAB PLUGIN DEFINITION
    // =====================

    function Plugin(option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.tab')

            if (!data) $this.data('bs.tab', (data = new Tab(this)))
            if (typeof option == 'string') data[option]()
        })
    }

    var old = $.fn.tab

    $.fn.tab = Plugin
    $.fn.tab.Constructor = Tab


    // TAB NO CONFLICT
    // ===============

    $.fn.tab.noConflict = function () {
        $.fn.tab = old
        return this
    }


    // TAB DATA-API
    // ============

    var clickHandler = function (e) {
        e.preventDefault()
        Plugin.call($(this), 'show')
    }

    $(document)
      .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
      .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)

}(jQuery);

/* ========================================================================
 * Bootstrap: affix.js v3.3.6
 * http://getbootstrap.com/javascript/#affix
 * ========================================================================
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
    'use strict';

    // AFFIX CLASS DEFINITION
    // ======================

    var Affix = function (element, options) {
        this.options = $.extend({}, Affix.DEFAULTS, options)

        this.$target = $(this.options.target)
          .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
          .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))

        this.$element = $(element)
        this.affixed = null
        this.unpin = null
        this.pinnedOffset = null

        this.checkPosition()
    }

    Affix.VERSION = '3.3.6'

    Affix.RESET = 'affix affix-top affix-bottom'

    Affix.DEFAULTS = {
        offset: 0,
        target: window
    }

    Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
        var scrollTop = this.$target.scrollTop()
        var position = this.$element.offset()
        var targetHeight = this.$target.height()

        if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false

        if (this.affixed == 'bottom') {
            if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
            return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
        }

        var initializing = this.affixed == null
        var colliderTop = initializing ? scrollTop : position.top
        var colliderHeight = initializing ? targetHeight : height

        if (offsetTop != null && scrollTop <= offsetTop) return 'top'
        if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'

        return false
    }

    Affix.prototype.getPinnedOffset = function () {
        if (this.pinnedOffset) return this.pinnedOffset
        this.$element.removeClass(Affix.RESET).addClass('affix')
        var scrollTop = this.$target.scrollTop()
        var position = this.$element.offset()
        return (this.pinnedOffset = position.top - scrollTop)
    }

    Affix.prototype.checkPositionWithEventLoop = function () {
        setTimeout($.proxy(this.checkPosition, this), 1)
    }

    Affix.prototype.checkPosition = function () {
        if (!this.$element.is(':visible')) return

        var height = this.$element.height()
        var offset = this.options.offset
        var offsetTop = offset.top
        var offsetBottom = offset.bottom
        var scrollHeight = Math.max($(document).height(), $(document.body).height())

        if (typeof offset != 'object') offsetBottom = offsetTop = offset
        if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
        if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)

        var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)

        if (this.affixed != affix) {
            if (this.unpin != null) this.$element.css('top', '')

            var affixType = 'affix' + (affix ? '-' + affix : '')
            var e = $.Event(affixType + '.bs.affix')

            this.$element.trigger(e)

            if (e.isDefaultPrevented()) return

            this.affixed = affix
            this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null

            this.$element
              .removeClass(Affix.RESET)
              .addClass(affixType)
              .trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
        }

        if (affix == 'bottom') {
            this.$element.offset({
                top: scrollHeight - height - offsetBottom
            })
        }
    }


    // AFFIX PLUGIN DEFINITION
    // =======================

    function Plugin(option) {
        return this.each(function () {
            var $this = $(this)
            var data = $this.data('bs.affix')
            var options = typeof option == 'object' && option

            if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
            if (typeof option == 'string') data[option]()
        })
    }

    var old = $.fn.affix

    $.fn.affix = Plugin
    $.fn.affix.Constructor = Affix


    // AFFIX NO CONFLICT
    // =================

    $.fn.affix.noConflict = function () {
        $.fn.affix = old
        return this
    }


    // AFFIX DATA-API
    // ==============

    $(window).on('load', function () {
        $('[data-spy="affix"]').each(function () {
            var $spy = $(this)
            var data = $spy.data()

            data.offset = data.offset || {}

            if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
            if (data.offsetTop != null) data.offset.top = data.offsetTop

            Plugin.call($spy, data)
        })
    })

}(jQuery);
;
/*\
|*| ========================================================================
|*| Bootstrap Toggle: bootstrap4-toggle.js v3.6.1
|*| https://gitbrent.github.io/bootstrap4-toggle/
|*| ========================================================================
|*| Copyright 2018-2019 Brent Ely
|*| Licensed under MIT
|*| ========================================================================
\*/
!function (a) { "use strict"; function l(t, e) { this.$element = a(t), this.options = a.extend({}, this.defaults(), e), this.render() } l.VERSION = "3.6.0", l.DEFAULTS = { on: "On", off: "Off", onstyle: "primary", offstyle: "light", size: "normal", style: "", width: null, height: null }, l.prototype.defaults = function () { return { on: this.$element.attr("data-on") || l.DEFAULTS.on, off: this.$element.attr("data-off") || l.DEFAULTS.off, onstyle: this.$element.attr("data-onstyle") || l.DEFAULTS.onstyle, offstyle: this.$element.attr("data-offstyle") || l.DEFAULTS.offstyle, size: this.$element.attr("data-size") || l.DEFAULTS.size, style: this.$element.attr("data-style") || l.DEFAULTS.style, width: this.$element.attr("data-width") || l.DEFAULTS.width, height: this.$element.attr("data-height") || l.DEFAULTS.height } }, l.prototype.render = function () { this._onstyle = "btn-" + this.options.onstyle, this._offstyle = "btn-" + this.options.offstyle; var t = "large" === this.options.size || "lg" === this.options.size ? "btn-lg" : "small" === this.options.size || "sm" === this.options.size ? "btn-sm" : "mini" === this.options.size || "xs" === this.options.size ? "btn-xs" : "", e = a('<label for="' + this.$element.prop("id") + '" class="btn">').html(this.options.on).addClass(this._onstyle + " " + t), s = a('<label for="' + this.$element.prop("id") + '" class="btn">').html(this.options.off).addClass(this._offstyle + " " + t), o = a('<span class="toggle-handle btn btn-light">').addClass(t), i = a('<div class="toggle-group">').append(e, s, o), l = a('<div class="toggle btn" data-toggle="toggle" role="button">').addClass(this.$element.prop("checked") ? this._onstyle : this._offstyle + " off").addClass(t).addClass(this.options.style); this.$element.wrap(l), a.extend(this, { $toggle: this.$element.parent(), $toggleOn: e, $toggleOff: s, $toggleGroup: i }), this.$toggle.append(i); var n = this.options.width || Math.max(e.outerWidth(), s.outerWidth()) + o.outerWidth() / 2, h = this.options.height || Math.max(e.outerHeight(), s.outerHeight()); e.addClass("toggle-on"), s.addClass("toggle-off"), this.$toggle.css({ width: n, height: h }), this.options.height && (e.css("line-height", e.height() + "px"), s.css("line-height", s.height() + "px")), this.update(!0), this.trigger(!0) }, l.prototype.toggle = function () { this.$element.prop("checked") ? this.off() : this.on() }, l.prototype.on = function (t) { if (this.$element.prop("disabled")) return !1; this.$toggle.removeClass(this._offstyle + " off").addClass(this._onstyle), this.$element.prop("checked", !0), t || this.trigger() }, l.prototype.off = function (t) { if (this.$element.prop("disabled")) return !1; this.$toggle.removeClass(this._onstyle).addClass(this._offstyle + " off"), this.$element.prop("checked", !1), t || this.trigger() }, l.prototype.enable = function () { this.$toggle.removeClass("disabled"), this.$toggle.removeAttr("disabled"), this.$element.prop("disabled", !1) }, l.prototype.disable = function () { this.$toggle.addClass("disabled"), this.$toggle.attr("disabled", "disabled"), this.$element.prop("disabled", !0) }, l.prototype.update = function (t) { this.$element.prop("disabled") ? this.disable() : this.enable(), this.$element.prop("checked") ? this.on(t) : this.off(t) }, l.prototype.trigger = function (t) { this.$element.off("change.bs.toggle"), t || this.$element.change(), this.$element.on("change.bs.toggle", a.proxy(function () { this.update() }, this)) }, l.prototype.destroy = function () { this.$element.off("change.bs.toggle"), this.$toggleGroup.remove(), this.$element.removeData("bs.toggle"), this.$element.unwrap() }; var t = a.fn.bootstrapToggle; a.fn.bootstrapToggle = function (o) { var i = Array.prototype.slice.call(arguments, 1)[0]; return this.each(function () { var t = a(this), e = t.data("bs.toggle"), s = "object" == typeof o && o; e || t.data("bs.toggle", e = new l(this, s)), "string" == typeof o && e[o] && "boolean" == typeof i ? e[o](i) : "string" == typeof o && e[o] && e[o]() }) }, a.fn.bootstrapToggle.Constructor = l, a.fn.toggle.noConflict = function () { return a.fn.bootstrapToggle = t, this }, a(function () { a("input[type=checkbox][data-toggle^=toggle]").bootstrapToggle() }), a(document).on("click.bs.toggle", "div[data-toggle^=toggle]", function (t) { a(this).find("input[type=checkbox]").bootstrapToggle("toggle"), t.preventDefault() }) }(jQuery);
//# sourceMappingURL=bootstrap4-toggle.min.js.map;
/**
 * Copyright (c) Tiny Technologies, Inc. All rights reserved.
 * Licensed under the LGPL or a commercial license.
 * For LGPL see License.txt in the project root for license information.
 * For commercial licenses see https://www.tiny.cloud/
 *
 * Version: 5.5.1 (2020-10-01)
 */
!function(){"use strict";var r=function(e){if(null===e)return"null";if(e===undefined)return"undefined";var t=typeof e;return"object"==t&&(Array.prototype.isPrototypeOf(e)||e.constructor&&"Array"===e.constructor.name)?"array":"object"==t&&(String.prototype.isPrototypeOf(e)||e.constructor&&"String"===e.constructor.name)?"string":t},t=function(e){return{eq:e}},s=t(function(e,t){return e===t}),i=function(o){return t(function(e,t){if(e.length!==t.length)return!1;for(var n=e.length,r=0;r<n;r++)if(!o.eq(e[r],t[r]))return!1;return!0})},c=function(e,r){return n=i(e),o=function(e){return t=e,n=r,Array.prototype.slice.call(t).sort(n);var t,n},t(function(e,t){return n.eq(o(e),o(t))});var n,o},u=function(u){return t(function(e,t){var n=Object.keys(e),r=Object.keys(t);if(!c(s).eq(n,r))return!1;for(var o=n.length,i=0;i<o;i++){var a=n[i];if(!u.eq(e[a],t[a]))return!1}return!0})},l=t(function(e,t){if(e===t)return!0;var n=r(e);return n===r(t)&&(-1!==["undefined","boolean","number","string","function","xml","null"].indexOf(n)?e===t:"array"===n?i(l).eq(e,t):"object"===n&&u(l).eq(e,t))}),V=function(){},a=function(n,r){return function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return n(r.apply(null,e))}},N=function(e){return function(){return e}},o=function(e){return e};function E(r){for(var o=[],e=1;e<arguments.length;e++)o[e-1]=arguments[e];return function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=o.concat(e);return r.apply(null,n)}}var e,n,f,d=function(t){return function(e){return!t(e)}},m=function(e){return function(){throw new Error(e)}},p=N(!1),k=N(!0),g=function(){return h},h=(e=function(e){return e.isNone()},{fold:function(e,t){return e()},is:p,isSome:p,isNone:k,getOr:f=function(e){return e},getOrThunk:n=function(e){return e()},getOrDie:function(e){throw new Error(e||"error: getOrDie called on none.")},getOrNull:N(null),getOrUndefined:N(undefined),or:f,orThunk:n,map:g,each:V,bind:g,exists:p,forall:k,filter:g,equals:e,equals_:e,toArray:function(){return[]},toString:N("none()")}),v=function(n){var e=N(n),t=function(){return o},r=function(e){return e(n)},o={fold:function(e,t){return t(n)},is:function(e){return n===e},isSome:k,isNone:p,getOr:e,getOrThunk:e,getOrDie:e,getOrNull:e,getOrUndefined:e,or:t,orThunk:t,map:function(e){return v(e(n))},each:function(e){e(n)},bind:r,exists:r,forall:r,filter:function(e){return e(n)?o:h},toArray:function(){return[n]},toString:function(){return"some("+n+")"},equals:function(e){return e.is(n)},equals_:function(e,t){return e.fold(p,function(e){return t(n,e)})}};return o},U={some:v,none:g,from:function(e){return null===e||e===undefined?h:v(e)}},y=function(r){return function(e){return n=typeof(t=e),(null===t?"null":"object"==n&&(Array.prototype.isPrototypeOf(t)||t.constructor&&"Array"===t.constructor.name)?"array":"object"==n&&(String.prototype.isPrototypeOf(t)||t.constructor&&"String"===t.constructor.name)?"string":n)===r;var t,n}},b=function(t){return function(e){return typeof e===t}},C=function(t){return function(e){return t===e}},q=y("string"),_=y("object"),S=y("array"),w=C(null),x=b("boolean"),R=C(undefined),T=function(e){return!(null===(t=e)||t===undefined);var t},A=b("function"),D=b("number"),O=Array.prototype.slice,B=Array.prototype.indexOf,P=Array.prototype.push,L=function(e,t){return B.call(e,t)},I=function(e,t){return-1<L(e,t)},M=function(e,t){for(var n=0,r=e.length;n<r;n++){if(t(e[n],n))return!0}return!1},F=function(e,t){for(var n=e.length,r=new Array(n),o=0;o<n;o++){var i=e[o];r[o]=t(i,o)}return r},$=function(e,t){for(var n=0,r=e.length;n<r;n++){t(e[n],n)}},z=function(e,t){for(var n=e.length-1;0<=n;n--){t(e[n],n)}},j=function(e,t){for(var n=[],r=0,o=e.length;r<o;r++){var i=e[r];t(i,r)&&n.push(i)}return n},H=function(e,t,n){return z(e,function(e){n=t(n,e)}),n},W=function(e,t,n){return $(e,function(e){n=t(n,e)}),n},K=function(e,t){return function(e,t,n){for(var r=0,o=e.length;r<o;r++){var i=e[r];if(t(i,r))return U.some(i);if(n(i,r))break}return U.none()}(e,t,p)},X=function(e,t){for(var n=0,r=e.length;n<r;n++){if(t(e[n],n))return U.some(n)}return U.none()},Y=function(e,t){return function(e){for(var t=[],n=0,r=e.length;n<r;++n){if(!S(e[n]))throw new Error("Arr.flatten item "+n+" was not an array, input: "+e);P.apply(t,e[n])}return t}(F(e,t))},G=function(e,t){for(var n=0,r=e.length;n<r;++n){if(!0!==t(e[n],n))return!1}return!0},J=function(e){var t=O.call(e,0);return t.reverse(),t},Q=function(e,t){return j(e,function(e){return!I(t,e)})},Z=function(e){return 0===e.length?U.none():U.some(e[0])},ee=function(e){return 0===e.length?U.none():U.some(e[e.length-1])},te=A(Array.from)?Array.from:function(e){return O.call(e)},ne=Object.keys,re=Object.hasOwnProperty,oe=function(e,t){for(var n=ne(e),r=0,o=n.length;r<o;r++){var i=n[r];t(e[i],i)}},ie=function(e,n){return ae(e,function(e,t){return{k:t,v:n(e,t)}})},ae=function(e,r){var o={};return oe(e,function(e,t){var n=r(e,t);o[n.k]=n.v}),o},ue=function(n){return function(e,t){n[t]=e}},se=function(e,n,r,o){return oe(e,function(e,t){(n(e,t)?r:o)(e,t)}),{}},ce=function(e,t){var n={},r={};return se(e,t,ue(n),ue(r)),{t:n,f:r}},le=function(e,t){var n={};return se(e,t,ue(n),V),n},fe=function(e){return n=function(e){return e},r=[],oe(e,function(e,t){r.push(n(e,t))}),r;var n,r},de=function(e,t){return me(e,t)?U.from(e[t]):U.none()},me=function(e,t){return re.call(e,t)},pe=Array.isArray,ge=function(e,t,n){var r,o;if(!e)return!1;if(n=n||e,e.length!==undefined){for(r=0,o=e.length;r<o;r++)if(!1===t.call(n,e[r],r,e))return!1}else for(r in e)if(e.hasOwnProperty(r)&&!1===t.call(n,e[r],r,e))return!1;return!0},he=function(n,r){var o=[];return ge(n,function(e,t){o.push(r(e,t,n))}),o},ve=function(n,r){var o=[];return ge(n,function(e,t){r&&!r(e,t,n)||o.push(e)}),o},ye=function(e,t){if(e)for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},be=function(e,t,n,r){for(var o=R(n)?e[0]:n,i=0;i<e.length;i++)o=t.call(r,o,e[i],i);return o},Ce=function(e,t,n){for(var r=0,o=e.length;r<o;r++)if(t.call(n,e[r],r,e))return r;return-1},we=function(e){return e[e.length-1]},xe=function(){return(xe=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)};function Se(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),o=0,t=0;t<n;t++)for(var i=arguments[t],a=0,u=i.length;a<u;a++,o++)r[o]=i[a];return r}var Ne,Ee,ke,_e,Re,Te,Ae,De=function(e,t){var n=function(e,t){for(var n=0;n<e.length;n++){var r=e[n];if(r.test(t))return r}return undefined}(e,t);if(!n)return{major:0,minor:0};var r=function(e){return Number(t.replace(n,"$"+e))};return Be(r(1),r(2))},Oe=function(){return Be(0,0)},Be=function(e,t){return{major:e,minor:t}},Pe={nu:Be,detect:function(e,t){var n=String(t).toLowerCase();return 0===e.length?Oe():De(e,n)},unknown:Oe},Le=function(e,t){var n=String(t).toLowerCase();return K(e,function(e){return e.search(n)})},Ie=function(e,n){return Le(e,n).map(function(e){var t=Pe.detect(e.versionRegexes,n);return{current:e.name,version:t}})},Me=function(e,n){return Le(e,n).map(function(e){var t=Pe.detect(e.versionRegexes,n);return{current:e.name,version:t}})},Fe=function(e,t){return-1!==e.indexOf(t)},Ue=function(e,t){return n=e,o=0,""===(r=t)||n.length>=r.length&&n.substr(o,o+r.length)===r;var n,r,o},ze=function(t){return function(e){return e.replace(t,"")}},je=ze(/^\s+|\s+$/g),He=ze(/^\s+/g),Ve=ze(/\s+$/g),qe=/.*?version\/\ ?([0-9]+)\.([0-9]+).*/,$e=function(t){return function(e){return Fe(e,t)}},We=[{name:"Edge",versionRegexes:[/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],search:function(e){return Fe(e,"edge/")&&Fe(e,"chrome")&&Fe(e,"safari")&&Fe(e,"applewebkit")}},{name:"Chrome",versionRegexes:[/.*?chrome\/([0-9]+)\.([0-9]+).*/,qe],search:function(e){return Fe(e,"chrome")&&!Fe(e,"chromeframe")}},{name:"IE",versionRegexes:[/.*?msie\ ?([0-9]+)\.([0-9]+).*/,/.*?rv:([0-9]+)\.([0-9]+).*/],search:function(e){return Fe(e,"msie")||Fe(e,"trident")}},{name:"Opera",versionRegexes:[qe,/.*?opera\/([0-9]+)\.([0-9]+).*/],search:$e("opera")},{name:"Firefox",versionRegexes:[/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],search:$e("firefox")},{name:"Safari",versionRegexes:[qe,/.*?cpu os ([0-9]+)_([0-9]+).*/],search:function(e){return(Fe(e,"safari")||Fe(e,"mobile/"))&&Fe(e,"applewebkit")}}],Ke=[{name:"Windows",search:$e("win"),versionRegexes:[/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]},{name:"iOS",search:function(e){return Fe(e,"iphone")||Fe(e,"ipad")},versionRegexes:[/.*?version\/\ ?([0-9]+)\.([0-9]+).*/,/.*cpu os ([0-9]+)_([0-9]+).*/,/.*cpu iphone os ([0-9]+)_([0-9]+).*/]},{name:"Android",search:$e("android"),versionRegexes:[/.*?android\ ?([0-9]+)\.([0-9]+).*/]},{name:"OSX",search:$e("mac os x"),versionRegexes:[/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]},{name:"Linux",search:$e("linux"),versionRegexes:[]},{name:"Solaris",search:$e("sunos"),versionRegexes:[]},{name:"FreeBSD",search:$e("freebsd"),versionRegexes:[]},{name:"ChromeOS",search:$e("cros"),versionRegexes:[/.*?chrome\/([0-9]+)\.([0-9]+).*/]}],Xe={browsers:N(We),oses:N(Ke)},Ye="Firefox",Ge=function(e){var t=e.current,n=e.version,r=function(e){return function(){return t===e}};return{current:t,version:n,isEdge:r("Edge"),isChrome:r("Chrome"),isIE:r("IE"),isOpera:r("Opera"),isFirefox:r(Ye),isSafari:r("Safari")}},Je={unknown:function(){return Ge({current:undefined,version:Pe.unknown()})},nu:Ge,edge:N("Edge"),chrome:N("Chrome"),ie:N("IE"),opera:N("Opera"),firefox:N(Ye),safari:N("Safari")},Qe="Windows",Ze="Android",et="Solaris",tt="FreeBSD",nt="ChromeOS",rt=function(e){var t=e.current,n=e.version,r=function(e){return function(){return t===e}};return{current:t,version:n,isWindows:r(Qe),isiOS:r("iOS"),isAndroid:r(Ze),isOSX:r("OSX"),isLinux:r("Linux"),isSolaris:r(et),isFreeBSD:r(tt),isChromeOS:r(nt)}},ot={unknown:function(){return rt({current:undefined,version:Pe.unknown()})},nu:rt,windows:N(Qe),ios:N("iOS"),android:N(Ze),linux:N("Linux"),osx:N("OSX"),solaris:N(et),freebsd:N(tt),chromeos:N(nt)},it=function(e,t){var n,r,o,i,a,u,s,c,l,f,d,m,p=Xe.browsers(),g=Xe.oses(),h=Ie(p,e).fold(Je.unknown,Je.nu),v=Me(g,e).fold(ot.unknown,ot.nu);return{browser:h,os:v,deviceType:(r=h,o=e,i=t,a=(n=v).isiOS()&&!0===/ipad/i.test(o),u=n.isiOS()&&!a,s=n.isiOS()||n.isAndroid(),c=s||i("(pointer:coarse)"),l=a||!u&&s&&i("(min-device-width:768px)"),f=u||s&&!l,d=r.isSafari()&&n.isiOS()&&!1===/safari/i.test(o),m=!f&&!l&&!d,{isiPad:N(a),isiPhone:N(u),isTablet:N(l),isPhone:N(f),isTouch:N(c),isAndroid:n.isAndroid,isiOS:n.isiOS,isWebView:N(d),isDesktop:N(m)})}},at=function(e){return window.matchMedia(e).matches},ut=(ke=!(Ne=function(){return it(navigator.userAgent,at)}),function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ke||(ke=!0,Ee=Ne.apply(null,e)),Ee}),st=function(){return ut()},ct=navigator.userAgent,lt=st(),ft=lt.browser,dt=lt.os,mt=lt.deviceType,pt=/WebKit/.test(ct)&&!ft.isEdge(),gt="FormData"in window&&"FileReader"in window&&"URL"in window&&!!URL.createObjectURL,ht=-1!==ct.indexOf("Windows Phone"),vt={opera:ft.isOpera(),webkit:pt,ie:!(!ft.isIE()&&!ft.isEdge())&&ft.version.major,gecko:ft.isFirefox(),mac:dt.isOSX()||dt.isiOS(),iOS:mt.isiPad()||mt.isiPhone(),android:dt.isAndroid(),contentEditable:!0,transparentSrc:"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",caretAfter:!0,range:window.getSelection&&"Range"in window,documentMode:ft.isIE()?document.documentMode||7:10,fileApi:gt,ceFalse:!0,cacheSuffix:null,container:null,experimentalShadowDom:!1,canHaveCSP:!ft.isIE(),desktop:mt.isDesktop(),windowsPhone:ht,browser:{current:ft.current,version:ft.version,isChrome:ft.isChrome,isEdge:ft.isEdge,isFirefox:ft.isFirefox,isIE:ft.isIE,isOpera:ft.isOpera,isSafari:ft.isSafari},os:{current:dt.current,version:dt.version,isAndroid:dt.isAndroid,isChromeOS:dt.isChromeOS,isFreeBSD:dt.isFreeBSD,isiOS:dt.isiOS,isLinux:dt.isLinux,isOSX:dt.isOSX,isSolaris:dt.isSolaris,isWindows:dt.isWindows},deviceType:{isDesktop:mt.isDesktop,isiPad:mt.isiPad,isiPhone:mt.isiPhone,isPhone:mt.isPhone,isTablet:mt.isTablet,isTouch:mt.isTouch,isWebView:mt.isWebView}},yt=/^\s*|\s*$/g,bt=function(e){return null===e||e===undefined?"":(""+e).replace(yt,"")},Ct=function(e,t){return t?!("array"!==t||!pe(e))||typeof e===t:e!==undefined},wt=function(e,n,r,o){o=o||this,e&&(r&&(e=e[r]),ge(e,function(e,t){return!1!==n.call(o,e,t,r)&&void wt(e,n,r,o)}))},xt={trim:bt,isArray:pe,is:Ct,toArray:function(e){if(pe(e))return e;for(var t=[],n=0,r=e.length;n<r;n++)t[n]=e[n];return t},makeMap:function(e,t,n){var r;for(t=t||",","string"==typeof(e=e||[])&&(e=e.split(t)),n=n||{},r=e.length;r--;)n[e[r]]={};return n},each:ge,map:he,grep:ve,inArray:ye,hasOwn:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},extend:function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0;r<t.length;r++){var o,i=t[r];for(var a in i){!i.hasOwnProperty(a)||(o=i[a])!==undefined&&(e[a]=o)}}return e},create:function(e,t,n){var r,o,i,a=this,u=0,s=(e=/^((static) )?([\w.]+)(:([\w.]+))?/.exec(e))[3].match(/(^|\.)(\w+)$/i)[2],c=a.createNS(e[3].replace(/\.\w+$/,""),n);if(!c[s]){if("static"===e[2])return c[s]=t,void(this.onCreate&&this.onCreate(e[2],e[3],c[s]));t[s]||(t[s]=function(){},u=1),c[s]=t[s],a.extend(c[s].prototype,t),e[5]&&(r=a.resolve(e[5]).prototype,o=e[5].match(/\.(\w+)$/i)[1],i=c[s],c[s]=u?function(){return r[o].apply(this,arguments)}:function(){return this.parent=r[o],i.apply(this,arguments)},c[s].prototype[s]=c[s],a.each(r,function(e,t){c[s].prototype[t]=r[t]}),a.each(t,function(e,t){r[t]?c[s].prototype[t]=function(){return this.parent=r[t],e.apply(this,arguments)}:t!==s&&(c[s].prototype[t]=e)})),a.each(t["static"],function(e,t){c[s][t]=e})}},walk:wt,createNS:function(e,t){var n,r;for(t=t||window,e=e.split("."),n=0;n<e.length;n++)t[r=e[n]]||(t[r]={}),t=t[r];return t},resolve:function(e,t){var n,r;for(t=t||window,n=0,r=(e=e.split(".")).length;n<r&&(t=t[e[n]]);n++);return t},explode:function(e,t){return!e||Ct(e,"array")?e:he(e.split(t||","),bt)},_addCacheSuffix:function(e){var t=vt.cacheSuffix;return t&&(e+=(-1===e.indexOf("?")?"?":"&")+t),e}},St=function(e){if(null===e||e===undefined)throw new Error("Node cannot be null or undefined");return{dom:e}},Nt={fromHtml:function(e,t){var n=(t||document).createElement("div");if(n.innerHTML=e,!n.hasChildNodes()||1<n.childNodes.length)throw console.error("HTML does not have a single root node",e),new Error("HTML must have a single root node");return St(n.childNodes[0])},fromTag:function(e,t){var n=(t||document).createElement(e);return St(n)},fromText:function(e,t){var n=(t||document).createTextNode(e);return St(n)},fromDom:St,fromPoint:function(e,t,n){return U.from(e.dom.elementFromPoint(t,n)).map(St)}},Et=function(e,t){for(var n=[],r=function(e){return n.push(e),t(e)},o=t(e);(o=o.bind(r)).isSome(););return n},kt=function(e,t){var n=e.dom;if(1!==n.nodeType)return!1;var r=n;if(r.matches!==undefined)return r.matches(t);if(r.msMatchesSelector!==undefined)return r.msMatchesSelector(t);if(r.webkitMatchesSelector!==undefined)return r.webkitMatchesSelector(t);if(r.mozMatchesSelector!==undefined)return r.mozMatchesSelector(t);throw new Error("Browser lacks native selectors")},_t=function(e){return 1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType||0===e.childElementCount},Rt=function(e,t){return e.dom===t.dom},Tt=function(e,t){return n=e.dom,r=t.dom,o=n,i=r,a=Node.DOCUMENT_POSITION_CONTAINED_BY,0!=(o.compareDocumentPosition(i)&a);var n,r,o,i,a},At=function(e,t){return st().browser.isIE()?Tt(e,t):(n=t,r=e.dom,o=n.dom,r!==o&&r.contains(o));var n,r,o},Dt=("undefined"!=typeof window||Function("return this;")(),function(e){return e.dom.nodeName.toLowerCase()}),Ot=function(e){return e.dom.nodeType},Bt=function(t){return function(e){return Ot(e)===t}},Pt=Bt(1),Lt=Bt(3),It=Bt(9),Mt=Bt(11),Ft=function(e){return Nt.fromDom(e.dom.ownerDocument)},Ut=function(e){return It(e)?e:Ft(e)},zt=function(e){return Nt.fromDom(Ut(e).dom.defaultView)},jt=function(e){return U.from(e.dom.parentNode).map(Nt.fromDom)},Ht=function(e){return U.from(e.dom.previousSibling).map(Nt.fromDom)},Vt=function(e){return U.from(e.dom.nextSibling).map(Nt.fromDom)},qt=function(e){return J(Et(e,Ht))},$t=function(e){return Et(e,Vt)},Wt=function(e){return F(e.dom.childNodes,Nt.fromDom)},Kt=function(e,t){var n=e.dom.childNodes;return U.from(n[t]).map(Nt.fromDom)},Xt=function(e){return Kt(e,0)},Yt=function(e){return Kt(e,e.dom.childNodes.length-1)},Gt=function(e){return Mt(e)},Jt=A(Element.prototype.attachShadow)&&A(Node.prototype.getRootNode),Qt=N(Jt),Zt=Jt?function(e){return Nt.fromDom(e.dom.getRootNode())}:Ut,en=function(e){return Gt(e)?e:function(e){var t=e.dom.head;if(null===t||t===undefined)throw new Error("Head is not available yet");return Nt.fromDom(t)}(Ut(e))},tn=function(e){return Nt.fromDom(e.dom.host)},nn=function(e){return T(e.dom.shadowRoot)},rn=function(t,n){jt(t).each(function(e){e.dom.insertBefore(n.dom,t.dom)})},on=function(e,t){Vt(e).fold(function(){jt(e).each(function(e){un(e,t)})},function(e){rn(e,t)})},an=function(t,n){Xt(t).fold(function(){un(t,n)},function(e){t.dom.insertBefore(n.dom,e.dom)})},un=function(e,t){e.dom.appendChild(t.dom)},sn=function(t,e){$(e,function(e){un(t,e)})},cn=function(e){e.dom.textContent="",$(Wt(e),function(e){ln(e)})},ln=function(e){var t=e.dom;null!==t.parentNode&&t.parentNode.removeChild(t)},fn=function(e){var t,n=Wt(e);0<n.length&&(t=e,$(n,function(e){rn(t,e)})),ln(e)},dn=function(e){var t=Lt(e)?e.dom.parentNode:e.dom;if(t===undefined||null===t||null===t.ownerDocument)return!1;var n,r,o,i,a=t.ownerDocument;return o=Nt.fromDom(t),i=Zt(o),(Gt(i)?U.some(i):U.none()).fold(function(){return a.body.contains(t)},(n=dn,r=tn,function(e){return n(r(e))}))},mn=function(n,r){return{left:n,top:r,translate:function(e,t){return mn(n+e,r+t)}}},pn=mn,gn=function(e,t){return e!==undefined?e:t!==undefined?t:0},hn=function(e){var t,n=e.dom,r=n.ownerDocument.body;return r===n?pn(r.offsetLeft,r.offsetTop):dn(e)?(t=n.getBoundingClientRect(),pn(t.left,t.top)):pn(0,0)},vn=function(e){var t=e!==undefined?e.dom:document,n=t.body.scrollLeft||t.documentElement.scrollLeft,r=t.body.scrollTop||t.documentElement.scrollTop;return pn(n,r)},yn=function(e,t,n){var r=(n!==undefined?n.dom:document).defaultView;r&&r.scrollTo(e,t)},bn=function(e,t){st().browser.isSafari()&&A(e.dom.scrollIntoViewIfNeeded)?e.dom.scrollIntoViewIfNeeded(!1):e.dom.scrollIntoView(t)},Cn=function(e,t,n,r){return{x:e,y:t,width:n,height:r,right:e+n,bottom:t+r}},wn=function(e){var t,n,r=e===undefined?window:e,o=r.document,i=vn(Nt.fromDom(o));return n=(t=r)===undefined?window:t,U.from(n.visualViewport).fold(function(){var e=r.document.documentElement,t=e.clientWidth,n=e.clientHeight;return Cn(i.left,i.top,t,n)},function(e){return Cn(Math.max(e.pageLeft,i.left),Math.max(e.pageTop,i.top),e.width,e.height)})},xn=function(t){return function(e){return!!e&&e.nodeType===t}},Sn=function(e){return!!e&&!Object.getPrototypeOf(e)},Nn=xn(1),En=function(e){var n=e.map(function(e){return e.toLowerCase()});return function(e){if(e&&e.nodeName){var t=e.nodeName.toLowerCase();return I(n,t)}return!1}},kn=function(r,e){var o=e.toLowerCase().split(" ");return function(e){var t;if(Nn(e))for(t=0;t<o.length;t++){var n=e.ownerDocument.defaultView.getComputedStyle(e,null);if((n?n.getPropertyValue(r):null)===o[t])return!0}return!1}},_n=function(t){return function(e){return Nn(e)&&e.hasAttribute(t)}},Rn=function(e){return Nn(e)&&e.hasAttribute("data-mce-bogus")},Tn=function(e){return Nn(e)&&"TABLE"===e.tagName},An=function(t){return function(e){if(Nn(e)){if(e.contentEditable===t)return!0;if(e.getAttribute("data-mce-contenteditable")===t)return!0}return!1}},Dn=En(["textarea","input"]),On=xn(3),Bn=xn(8),Pn=xn(9),Ln=xn(11),In=En(["br"]),Mn=En(["img"]),Fn=An("true"),Un=An("false"),zn=En(["td","th"]),jn=En(["video","audio","object","embed"]),Hn=function(e){return e.style!==undefined&&A(e.style.getPropertyValue)},Vn=function(e,t,n){if(!(q(n)||x(n)||D(n)))throw console.error("Invalid call to Attribute.set. Key ",t,":: Value ",n,":: Element ",e),new Error("Attribute value was not simple");e.setAttribute(t,n+"")},qn=function(e,t,n){Vn(e.dom,t,n)},$n=function(e,t){var n=e.dom;oe(t,function(e,t){Vn(n,t,e)})},Wn=function(e,t){var n=e.dom.getAttribute(t);return null===n?undefined:n},Kn=function(e,t){e.dom.removeAttribute(t)},Xn=function(e,t){var n=e.dom;oe(t,function(e,t){!function(e,t,n){if(!q(n))throw console.error("Invalid call to CSS.set. Property ",t,":: Value ",n,":: Element ",e),new Error("CSS value must be a string: "+n);Hn(e)&&e.style.setProperty(t,n)}(n,t,e)})},Yn=function(e,t){var n=e.dom,r=window.getComputedStyle(n).getPropertyValue(t);return""!==r||dn(e)?r:Gn(n,t)},Gn=function(e,t){return Hn(e)?e.style.getPropertyValue(t):""},Jn=function(e,t){var n=e.dom,r=Gn(n,t);return U.from(r).filter(function(e){return 0<e.length})},Qn=function(e){var t={},n=e.dom;if(Hn(n))for(var r=0;r<n.style.length;r++){var o=n.style.item(r);t[o]=n.style[o]}return t},Zn=st().browser,er=function(e){return K(e,Pt)},tr=function(e,t){return e.children&&I(e.children,t)},nr=function(e,t,n){var r,o,i,a=0,u=0,s=e.ownerDocument;if(n=n||e,t){if(n===e&&t.getBoundingClientRect&&"static"===Yn(Nt.fromDom(e),"position"))return{x:a=(o=t.getBoundingClientRect()).left+(s.documentElement.scrollLeft||e.scrollLeft)-s.documentElement.clientLeft,y:u=o.top+(s.documentElement.scrollTop||e.scrollTop)-s.documentElement.clientTop};for(r=t;r&&r!==n&&r.nodeType&&!tr(r,n);)a+=r.offsetLeft||0,u+=r.offsetTop||0,r=r.offsetParent;for(r=t.parentNode;r&&r!==n&&r.nodeType&&!tr(r,n);)a-=r.scrollLeft||0,u-=r.scrollTop||0,r=r.parentNode;u+=(i=Nt.fromDom(t),Zn.isFirefox()&&"table"===Dt(i)?er(Wt(i)).filter(function(e){return"caption"===Dt(e)}).bind(function(o){return er($t(o)).map(function(e){var t=e.dom.offsetTop,n=o.dom.offsetTop,r=o.dom.offsetHeight;return t<=n?-r:0})}).getOr(0):0)}return{x:a,y:u}},rr={},or={exports:rr};_e=undefined,Re=rr,Te=or,Ae=undefined,function(e){"object"==typeof Re&&void 0!==Te?Te.exports=e():"function"==typeof _e&&_e.amd?_e([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).EphoxContactWrapper=e()}(function(){return function l(i,a,u){function s(t,e){if(!a[t]){if(!i[t]){var n="function"==typeof Ae&&Ae;if(!e&&n)return n(t,!0);if(c)return c(t,!0);var r=new Error("Cannot find module '"+t+"'");throw r.code="MODULE_NOT_FOUND",r}var o=a[t]={exports:{}};i[t][0].call(o.exports,function(e){return s(i[t][1][e]||e)},o,o.exports,l,i,a,u)}return a[t].exports}for(var c="function"==typeof Ae&&Ae,e=0;e<u.length;e++)s(u[e]);return s}({1:[function(e,t,n){var r,o,i=t.exports={};function a(){throw new Error("setTimeout has not been defined")}function u(){throw new Error("clearTimeout has not been defined")}function s(e){if(r===setTimeout)return setTimeout(e,0);if((r===a||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:a}catch(e){r=a}try{o="function"==typeof clearTimeout?clearTimeout:u}catch(e){o=u}}();var c,l=[],f=!1,d=-1;function m(){f&&c&&(f=!1,c.length?l=c.concat(l):d=-1,l.length&&p())}function p(){if(!f){var e=s(m);f=!0;for(var t=l.length;t;){for(c=l,l=[];++d<t;)c&&c[d].run();d=-1,t=l.length}c=null,f=!1,function(e){if(o===clearTimeout)return clearTimeout(e);if((o===u||!o)&&clearTimeout)return o=clearTimeout,clearTimeout(e);try{o(e)}catch(t){try{return o.call(null,e)}catch(t){return o.call(this,e)}}}(e)}}function g(e,t){this.fun=e,this.array=t}function h(){}i.nextTick=function(e){var t=new Array(arguments.length-1);if(1<arguments.length)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];l.push(new g(e,t)),1!==l.length||f||s(p)},g.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=h,i.addListener=h,i.once=h,i.off=h,i.removeListener=h,i.removeAllListeners=h,i.emit=h,i.prependListener=h,i.prependOnceListener=h,i.listeners=function(e){return[]},i.binding=function(e){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(e){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],2:[function(e,f,t){(function(t){function r(){}function a(e){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=undefined,this._deferreds=[],l(e,this)}function o(r,o){for(;3===r._state;)r=r._value;0!==r._state?(r._handled=!0,a._immediateFn(function(){var e,t=1===r._state?o.onFulfilled:o.onRejected;if(null!==t){try{e=t(r._value)}catch(n){return void u(o.promise,n)}i(o.promise,e)}else(1===r._state?i:u)(o.promise,r._value)})):r._deferreds.push(o)}function i(e,t){try{if(t===e)throw new TypeError("A promise cannot be resolved with itself.");if(t&&("object"==typeof t||"function"==typeof t)){var n=t.then;if(t instanceof a)return e._state=3,e._value=t,void s(e);if("function"==typeof n)return void l((r=n,o=t,function(){r.apply(o,arguments)}),e)}e._state=1,e._value=t,s(e)}catch(i){u(e,i)}var r,o}function u(e,t){e._state=2,e._value=t,s(e)}function s(e){2===e._state&&0===e._deferreds.length&&a._immediateFn(function(){e._handled||a._unhandledRejectionFn(e._value)});for(var t=0,n=e._deferreds.length;t<n;t++)o(e,e._deferreds[t]);e._deferreds=null}function c(e,t,n){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof t?t:null,this.promise=n}function l(e,t){var n=!1;try{e(function(e){n||(n=!0,i(t,e))},function(e){n||(n=!0,u(t,e))})}catch(r){if(n)return;n=!0,u(t,r)}}var e,n;e=this,n=setTimeout,a.prototype["catch"]=function(e){return this.then(null,e)},a.prototype.then=function(e,t){var n=new this.constructor(r);return o(this,new c(e,t,n)),n},a.all=function(e){var s=Array.prototype.slice.call(e);return new a(function(o,i){if(0===s.length)return o([]);var a=s.length;for(var e=0;e<s.length;e++)!function u(t,e){try{if(e&&("object"==typeof e||"function"==typeof e)){var n=e.then;if("function"==typeof n)return void n.call(e,function(e){u(t,e)},i)}s[t]=e,0==--a&&o(s)}catch(r){i(r)}}(e,s[e])})},a.resolve=function(t){return t&&"object"==typeof t&&t.constructor===a?t:new a(function(e){e(t)})},a.reject=function(n){return new a(function(e,t){t(n)})},a.race=function(o){return new a(function(e,t){for(var n=0,r=o.length;n<r;n++)o[n].then(e,t)})},a._immediateFn="function"==typeof t?function(e){t(e)}:function(e){n(e,0)},a._unhandledRejectionFn=function(e){"undefined"!=typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",e)},a._setImmediateFn=function(e){a._immediateFn=e},a._setUnhandledRejectionFn=function(e){a._unhandledRejectionFn=e},void 0!==f&&f.exports?f.exports=a:e.Promise||(e.Promise=a)}).call(this,e("timers").setImmediate)},{timers:3}],3:[function(s,e,c){(function(e,t){var r=s("process/browser.js").nextTick,n=Function.prototype.apply,o=Array.prototype.slice,i={},a=0;function u(e,t){this._id=e,this._clearFn=t}c.setTimeout=function(){return new u(n.call(setTimeout,window,arguments),clearTimeout)},c.setInterval=function(){return new u(n.call(setInterval,window,arguments),clearInterval)},c.clearTimeout=c.clearInterval=function(e){e.close()},u.prototype.unref=u.prototype.ref=function(){},u.prototype.close=function(){this._clearFn.call(window,this._id)},c.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},c.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},c._unrefActive=c.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;0<=t&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},c.setImmediate="function"==typeof e?e:function(e){var t=a++,n=!(arguments.length<2)&&o.call(arguments,1);return i[t]=!0,r(function(){i[t]&&(n?e.apply(null,n):e.call(null),c.clearImmediate(t))}),t},c.clearImmediate="function"==typeof t?t:function(e){delete i[e]}}).call(this,s("timers").setImmediate,s("timers").clearImmediate)},{"process/browser.js":1,timers:3}],4:[function(e,t,n){var r=e("promise-polyfill"),o="undefined"!=typeof window?window:Function("return this;")();t.exports={boltExport:o.Promise||r}},{"promise-polyfill":2}]},{},[4])(4)});var ir=or.exports.boltExport,ar=function(e){var n=U.none(),t=[],r=function(e){o()?a(e):t.push(e)},o=function(){return n.isSome()},i=function(e){$(e,a)},a=function(t){n.each(function(e){setTimeout(function(){t(e)},0)})};return e(function(e){o()||(n=U.some(e),i(t),t=[])}),{get:r,map:function(n){return ar(function(t){r(function(e){t(n(e))})})},isReady:o}},ur={nu:ar,pure:function(t){return ar(function(e){e(t)})}},sr=function(e){setTimeout(function(){throw e},0)},cr=function(n){var e=function(e){n().then(e,sr)};return{map:function(e){return cr(function(){return n().then(e)})},bind:function(t){return cr(function(){return n().then(function(e){return t(e).toPromise()})})},anonBind:function(e){return cr(function(){return n().then(function(){return e.toPromise()})})},toLazy:function(){return ur.nu(e)},toCached:function(){var e=null;return cr(function(){return null===e&&(e=n()),e})},toPromise:n,get:e}},lr=function(e){return cr(function(){return new ir(e)})},fr=function(a,e){return e(function(r){var o=[],i=0;0===a.length?r([]):$(a,function(e,t){var n;e.get((n=t,function(e){o[n]=e,++i>=a.length&&r(o)}))})})},dr=function(n){return{is:function(e){return n===e},isValue:k,isError:p,getOr:N(n),getOrThunk:N(n),getOrDie:N(n),or:function(e){return dr(n)},orThunk:function(e){return dr(n)},fold:function(e,t){return t(n)},map:function(e){return dr(e(n))},mapError:function(e){return dr(n)},each:function(e){e(n)},bind:function(e){return e(n)},exists:function(e){return e(n)},forall:function(e){return e(n)},toOptional:function(){return U.some(n)}}},mr=function(n){return{is:p,isValue:p,isError:k,getOr:o,getOrThunk:function(e){return e()},getOrDie:function(){return m(String(n))()},or:function(e){return e},orThunk:function(e){return e()},fold:function(e,t){return e(n)},map:function(e){return mr(n)},mapError:function(e){return mr(e(n))},each:V,bind:function(e){return mr(n)},exists:p,forall:k,toOptional:U.none}},pr={value:dr,error:mr,fromOption:function(e,t){return e.fold(function(){return mr(t)},dr)}},gr=function(a){if(!S(a))throw new Error("cases must be an array");if(0===a.length)throw new Error("there must be at least one case");var u=[],n={};return $(a,function(e,r){var t=ne(e);if(1!==t.length)throw new Error("one and only one name per case");var o=t[0],i=e[o];if(n[o]!==undefined)throw new Error("duplicate key detected:"+o);if("cata"===o)throw new Error("cannot have a case named cata (sorry)");if(!S(i))throw new Error("case arguments must be an array");u.push(o),n[o]=function(){var e=arguments.length;if(e!==i.length)throw new Error("Wrong number of arguments to case "+o+". Expected "+i.length+" ("+i+"), got "+e);for(var n=new Array(e),t=0;t<n.length;t++)n[t]=arguments[t];return{fold:function(){if(arguments.length!==a.length)throw new Error("Wrong number of arguments to fold. Expected "+a.length+", got "+arguments.length);return arguments[r].apply(null,n)},match:function(e){var t=ne(e);if(u.length!==t.length)throw new Error("Wrong number of arguments to match. Expected: "+u.join(",")+"\nActual: "+t.join(","));if(!G(u,function(e){return I(t,e)}))throw new Error("Not all branches were specified when using match. Specified: "+t.join(", ")+"\nRequired: "+u.join(", "));return e[o].apply(null,n)},log:function(e){console.log(e,{constructors:u,constructor:o,params:n})}}}}),n},hr=(gr([{bothErrors:["error1","error2"]},{firstError:["error1","value2"]},{secondError:["value1","error2"]},{bothValues:["value1","value2"]}]),function(e){return e.fold(o,o)});function vr(e,t,n,r,o){return e(n,r)?U.some(n):A(o)&&o(n)?U.none():t(n,r,o)}var yr,br,Cr,wr,xr=function(e,t,n){for(var r=e.dom,o=A(n)?n:p;r.parentNode;){r=r.parentNode;var i=Nt.fromDom(r);if(t(i))return U.some(i);if(o(i))break}return U.none()},Sr=function(e,t,n){return vr(function(e,t){return t(e)},xr,e,t,n)},Nr=function(e,t,n){return xr(e,function(e){return kt(e,t)},n)},Er=function(e,t){return n=t,o=(r=e)===undefined?document:r.dom,_t(o)?U.none():U.from(o.querySelector(n)).map(Nt.fromDom);var n,r,o},kr=function(e,t,n){return vr(kt,Nr,e,t,n)},_r=window.Promise?window.Promise:(yr=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},Cr=(br=function(e){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=null,this._value=null,this._deferreds=[],Pr(e,Rr(Ar,this),Rr(Dr,this))}).immediateFn||"function"==typeof setImmediate&&setImmediate||function(e){setTimeout(e,1)},br.prototype["catch"]=function(e){return this.then(null,e)},br.prototype.then=function(n,r){var o=this;return new br(function(e,t){Tr.call(o,new Br(n,r,e,t))})},br.all=function(){var s=Array.prototype.slice.call(1===arguments.length&&yr(arguments[0])?arguments[0]:arguments);return new br(function(o,i){if(0===s.length)return o([]);for(var a=s.length,e=0;e<s.length;e++)!function u(t,e){try{if(e&&("object"==typeof e||"function"==typeof e)){var n=e.then;if("function"==typeof n)return void n.call(e,function(e){u(t,e)},i)}s[t]=e,0==--a&&o(s)}catch(r){i(r)}}(e,s[e])})},br.resolve=function(t){return t&&"object"==typeof t&&t.constructor===br?t:new br(function(e){e(t)})},br.reject=function(n){return new br(function(e,t){t(n)})},br.race=function(o){return new br(function(e,t){for(var n=0,r=o.length;n<r;n++)o[n].then(e,t)})},br);function Rr(e,t){return function(){e.apply(t,arguments)}}function Tr(r){var o=this;null!==this._state?Cr(function(){var e,t=o._state?r.onFulfilled:r.onRejected;if(null!==t){try{e=t(o._value)}catch(n){return void r.reject(n)}r.resolve(e)}else(o._state?r.resolve:r.reject)(o._value)}):this._deferreds.push(r)}function Ar(e){try{if(e===this)throw new TypeError("A promise cannot be resolved with itself.");if(e&&("object"==typeof e||"function"==typeof e)){var t=e.then;if("function"==typeof t)return void Pr(Rr(t,e),Rr(Ar,this),Rr(Dr,this))}this._state=!0,this._value=e,Or.call(this)}catch(n){Dr.call(this,n)}}function Dr(e){this._state=!1,this._value=e,Or.call(this)}function Or(){for(var e=0,t=this._deferreds.length;e<t;e++)Tr.call(this,this._deferreds[e]);this._deferreds=null}function Br(e,t,n,r){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof t?t:null,this.resolve=n,this.reject=r}function Pr(e,t,n){var r=!1;try{e(function(e){r||(r=!0,t(e))},function(e){r||(r=!0,n(e))})}catch(o){if(r)return;r=!0,n(o)}}var Lr=function(e,t){return"number"!=typeof t&&(t=0),setTimeout(e,t)},Ir=function(e,t){return"number"!=typeof t&&(t=1),setInterval(e,t)},Mr=function(n,r){var o,e=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];clearTimeout(o),o=Lr(function(){n.apply(this,e)},r)};return e.stop=function(){clearTimeout(o)},e},Fr={requestAnimationFrame:function(e,t){wr?wr.then(e):wr=new _r(function(e){!function(e,t){for(var n=window.requestAnimationFrame,r=["ms","moz","webkit"],o=0;o<r.length&&!n;o++)n=window[r[o]+"RequestAnimationFrame"];(n=n||function(e){window.setTimeout(e,0)})(e,t)}(e,t=t||document.body)}).then(e)},setTimeout:Lr,setInterval:Ir,setEditorTimeout:function(e,t,n){return Lr(function(){e.removed||t()},n)},setEditorInterval:function(e,t,n){var r=Ir(function(){e.removed?clearInterval(r):t()},n);return r},debounce:Mr,throttle:Mr,clearInterval:function(e){return clearInterval(e)},clearTimeout:function(e){return clearTimeout(e)}};function Ur(m,p){void 0===p&&(p={});var g=0,h={},v=Nt.fromDom(m),y=Ut(v),b=p.maxLoadTime||5e3,n=function(e,t,n){var r,o=xt._addCacheSuffix(e),i=de(h,o).getOrThunk(function(){return{id:"mce-u"+g++,passed:[],failed:[],count:0}});(h[o]=i).count++;var a,u,s,c=function(e,t){for(var n=e.length;n--;)e[n]();i.status=t,i.passed=[],i.failed=[],r&&(r.onload=null,r.onerror=null,r=null)},l=function(){return c(i.passed,2)},f=function(){return c(i.failed,3)},d=function(){var e;e=d,function(){for(var e=m.styleSheets,t=e.length;t--;){var n=e[t].ownerNode;if(n&&n.id===r.id)return l(),1}}()||(Date.now()-u<b?Fr.setTimeout(e):f())};t&&i.passed.push(t),n&&i.failed.push(n),1!==i.status&&(2!==i.status?3!==i.status?(i.status=1,a=Nt.fromTag("link",y.dom),$n(a,{rel:"stylesheet",type:"text/css",id:i.id}),u=Date.now(),p.contentCssCors&&qn(a,"crossOrigin","anonymous"),p.referrerPolicy&&qn(a,"referrerpolicy",p.referrerPolicy),(r=a.dom).onload=d,r.onerror=f,s=a,un(en(v),s),qn(a,"href",o)):f():l())},o=function(t){return lr(function(e){n(t,a(e,N(pr.value(t))),a(e,N(pr.error(t))))})},t=function(e){var r=xt._addCacheSuffix(e);de(h,r).each(function(e){var t,n;0==--e.count&&(delete h[r],t=e.id,n=en(v),Er(n,"#"+t).each(ln))})};return{load:n,loadAll:function(e,n,r){var t;t=F(e,o),fr(t,lr).get(function(e){var t=function(e,t){for(var n=[],r=[],o=0,i=e.length;o<i;o++){var a=e[o];(t(a,o)?n:r).push(a)}return{pass:n,fail:r}}(e,function(e){return e.isValue()});0<t.fail.length?r(t.fail.map(hr)):n(t.pass.map(hr))})},unload:t,unloadAll:function(e){$(e,function(e){t(e)})},_setReferrerPolicy:function(e){p.referrerPolicy=e}}}var zr,jr=(zr=new WeakMap,{forElement:function(e,t){var n=Zt(e).dom;return U.from(zr.get(n)).getOrThunk(function(){var e=Ur(n,t);return zr.set(n,e),e})}}),Hr=(Vr.prototype.current=function(){return this.node},Vr.prototype.next=function(e){return this.node=this.findSibling(this.node,"firstChild","nextSibling",e),this.node},Vr.prototype.prev=function(e){return this.node=this.findSibling(this.node,"lastChild","previousSibling",e),this.node},Vr.prototype.prev2=function(e){return this.node=this.findPreviousNode(this.node,"lastChild","previousSibling",e),this.node},Vr.prototype.findSibling=function(e,t,n,r){var o,i;if(e){if(!r&&e[t])return e[t];if(e!==this.rootNode){if(o=e[n])return o;for(i=e.parentNode;i&&i!==this.rootNode;i=i.parentNode)if(o=i[n])return o}}},Vr.prototype.findPreviousNode=function(e,t,n,r){var o,i,a;if(e){if(o=e[n],this.rootNode&&o===this.rootNode)return;if(o){if(!r)for(a=o[t];a;a=a[t])if(!a[t])return a;return o}if((i=e.parentNode)&&i!==this.rootNode)return i}},Vr);function Vr(e,t){this.node=e,this.rootNode=t,this.current=this.current.bind(this),this.next=this.next.bind(this),this.prev=this.prev.bind(this),this.prev2=this.prev2.bind(this)}var qr,$r,Wr=function(t){var n;return function(e){return(n=n||function(e,t){for(var n={},r=0,o=e.length;r<o;r++){var i=e[r];n[String(i)]=t(i,r)}return n}(t,k)).hasOwnProperty(Dt(e))}},Kr=Wr(["h1","h2","h3","h4","h5","h6"]),Xr=Wr(["article","aside","details","div","dt","figcaption","footer","form","fieldset","header","hgroup","html","main","nav","section","summary","body","p","dl","multicol","dd","figure","address","center","blockquote","h1","h2","h3","h4","h5","h6","listing","xmp","pre","plaintext","menu","dir","ul","ol","li","hr","table","tbody","thead","tfoot","th","tr","td","caption"]),Yr=function(e){return Pt(e)&&!Xr(e)},Gr=function(e){return Pt(e)&&"br"===Dt(e)},Jr=Wr(["h1","h2","h3","h4","h5","h6","p","div","address","pre","form","blockquote","center","dir","fieldset","header","footer","article","section","hgroup","aside","nav","figure"]),Qr=Wr(["ul","ol","dl"]),Zr=Wr(["li","dd","dt"]),eo=Wr(["thead","tbody","tfoot"]),to=Wr(["td","th"]),no=Wr(["pre","script","textarea","style"]),ro="\ufeff",oo="\xa0",io=ro,ao=function(e){return e===ro},uo=function(e){return e.replace(/\uFEFF/g,"")},so=Nn,co=On,lo=function(e){return co(e)&&(e=e.parentNode),so(e)&&e.hasAttribute("data-mce-caret")},fo=function(e){return co(e)&&ao(e.data)},mo=function(e){return lo(e)||fo(e)},po=function(e){return e.firstChild!==e.lastChild||!In(e.firstChild)},go=function(e){var t=e.container();return!!On(t)&&(t.data.charAt(e.offset())===io||e.isAtStart()&&fo(t.previousSibling))},ho=function(e){var t=e.container();return!!On(t)&&(t.data.charAt(e.offset()-1)===io||e.isAtEnd()&&fo(t.nextSibling))},vo=function(e,t,n){var r,o=t.ownerDocument.createElement(e);o.setAttribute("data-mce-caret",n?"before":"after"),o.setAttribute("data-mce-bogus","all"),o.appendChild(((r=document.createElement("br")).setAttribute("data-mce-bogus","1"),r));var i=t.parentNode;return n?i.insertBefore(o,t):t.nextSibling?i.insertBefore(o,t.nextSibling):i.appendChild(o),o},yo=function(e){return co(e)&&e.data[0]===io},bo=function(e){return co(e)&&e.data[e.data.length-1]===io},Co=function(e){return e&&e.hasAttribute("data-mce-caret")?(t=e.getElementsByTagName("br"),n=t[t.length-1],Rn(n)&&n.parentNode.removeChild(n),e.removeAttribute("data-mce-caret"),e.removeAttribute("data-mce-bogus"),e.removeAttribute("style"),e.removeAttribute("_moz_abspos"),e):null;var t,n},wo=Fn,xo=Un,So=In,No=On,Eo=En(["script","style","textarea"]),ko=En(["img","input","textarea","hr","iframe","video","audio","object","embed"]),_o=En(["table"]),Ro=mo,To=function(e){return!Ro(e)&&(No(e)?!Eo(e.parentNode):ko(e)||So(e)||_o(e)||Ao(e))},Ao=function(e){return!1===(Nn(t=e)&&"true"===t.getAttribute("unselectable"))&&xo(e);var t},Do=function(e,t){return To(e)&&function(e,t){for(e=e.parentNode;e&&e!==t;e=e.parentNode){if(Ao(e))return!1;if(wo(e))return!0}return!0}(e,t)},Oo=/^[ \t\r\n]*$/,Bo=function(e){return Oo.test(e)},Po=function(e,t){var n,r,o,i=Nt.fromDom(t),a=Nt.fromDom(e);return n=a,r="pre,code",o=E(Rt,i),Nr(n,r,o).isSome()},Lo=function(e,t){return To(e)&&!1===(o=t,On(r=e)&&Bo(r.data)&&!1===Po(r,o))||Nn(n=e)&&"A"===n.nodeName&&!n.hasAttribute("href")&&(n.hasAttribute("name")||n.hasAttribute("id"))||Io(e);var n,r,o},Io=_n("data-mce-bookmark"),Mo=_n("data-mce-bogus"),Fo=(qr="data-mce-bogus",$r="all",function(e){return Nn(e)&&e.getAttribute(qr)===$r}),Uo=function(e,t){return void 0===t&&(t=!0),function(e,t){var n,r=0;if(Lo(e,e))return!1;if(!(n=e.firstChild))return!0;var o=new Hr(n,e);do{if(t){if(Fo(n)){n=o.next(!0);continue}if(Mo(n)){n=o.next();continue}}if(In(n))r++,n=o.next();else{if(Lo(n,e))return!1;n=o.next()}}while(n);return r<=1}(e.dom,t)},zo=function(e,t){return T(e)&&(Lo(e,t)||Yr(Nt.fromDom(e)))},jo=function(e){return"span"===e.nodeName.toLowerCase()&&"bookmark"===e.getAttribute("data-mce-type")},Ho=function(e,t){return On(e)&&0<e.data.length&&(o=new Hr(n=e,r=t).prev(!1),i=new Hr(n,r).next(!1),a=R(o)||zo(o,r),u=R(i)||zo(i,r),a&&u);var n,r,o,i,a,u},Vo=function(e,t,n){var r=n||t;if(Nn(t)&&jo(t))return t;for(var o,i,a,u=t.childNodes,s=u.length-1;0<=s;s--)Vo(e,u[s],r);return!Nn(t)||1===(o=t.childNodes).length&&jo(o[0])&&t.parentNode.insertBefore(o[0],t),Ln(a=t)||Pn(a)||Lo(t,r)||Nn(i=t)&&0<i.childNodes.length||Ho(t,r)||e.remove(t),t},qo=xt.makeMap,$o=/[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,Wo=/[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,Ko=/[<>&\"\']/g,Xo=/&#([a-z0-9]+);?|&([a-z0-9]+);/gi,Yo={128:"\u20ac",130:"\u201a",131:"\u0192",132:"\u201e",133:"\u2026",134:"\u2020",135:"\u2021",136:"\u02c6",137:"\u2030",138:"\u0160",139:"\u2039",140:"\u0152",142:"\u017d",145:"\u2018",146:"\u2019",147:"\u201c",148:"\u201d",149:"\u2022",150:"\u2013",151:"\u2014",152:"\u02dc",153:"\u2122",154:"\u0161",155:"\u203a",156:"\u0153",158:"\u017e",159:"\u0178"},Go={'"':"&quot;","'":"&#39;","<":"&lt;",">":"&gt;","&":"&amp;","`":"&#96;"},Jo={"&lt;":"<","&gt;":">","&amp;":"&","&quot;":'"',"&apos;":"'"},Qo=function(e,t){var n,r,o,i={};if(e){for(e=e.split(","),t=t||10,n=0;n<e.length;n+=2)r=String.fromCharCode(parseInt(e[n],t)),Go[r]||(o="&"+e[n+1]+";",i[r]=o,i[o]=r);return i}},Zo=Qo("50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,t9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4,nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro",32),ei=function(e,t){return e.replace(t?$o:Wo,function(e){return Go[e]||e})},ti=function(e,t){return e.replace(t?$o:Wo,function(e){return 1<e.length?"&#"+(1024*(e.charCodeAt(0)-55296)+(e.charCodeAt(1)-56320)+65536)+";":Go[e]||"&#"+e.charCodeAt(0)+";"})},ni=function(e,t,n){return n=n||Zo,e.replace(t?$o:Wo,function(e){return Go[e]||n[e]||e})},ri={encodeRaw:ei,encodeAllRaw:function(e){return(""+e).replace(Ko,function(e){return Go[e]||e})},encodeNumeric:ti,encodeNamed:ni,getEncodeFunc:function(e,t){var n=Qo(t)||Zo,r=qo(e.replace(/\+/g,","));return r.named&&r.numeric?function(e,t){return e.replace(t?$o:Wo,function(e){return Go[e]!==undefined?Go[e]:n[e]!==undefined?n[e]:1<e.length?"&#"+(1024*(e.charCodeAt(0)-55296)+(e.charCodeAt(1)-56320)+65536)+";":"&#"+e.charCodeAt(0)+";"})}:r.named?t?function(e,t){return ni(e,t,n)}:ni:r.numeric?ti:ei},decode:function(e){return e.replace(Xo,function(e,t){return t?65535<(t="x"===t.charAt(0).toLowerCase()?parseInt(t.substr(1),16):parseInt(t,10))?(t-=65536,String.fromCharCode(55296+(t>>10),56320+(1023&t))):Yo[t]||String.fromCharCode(t):Jo[e]||Zo[e]||(n=e,(r=Nt.fromTag("div").dom).innerHTML=n,r.textContent||r.innerText||n);var n,r})}},oi={},ii={},ai=xt.makeMap,ui=xt.each,si=xt.extend,ci=xt.explode,li=xt.inArray,fi=function(e,t){return(e=xt.trim(e))?e.split(t||" "):[]},di=function(e){var s,t,n,r,o,i,c={},a=function(e,t,n){var r,o,i=function(e,t){for(var n={},r=0,o=e.length;r<o;r++)n[e[r]]=t||{};return n};t=t||"","string"==typeof(n=n||[])&&(n=fi(n));for(var a=fi(e),u=a.length;u--;)o={attributes:i(r=fi([s,t].join(" "))),attributesOrder:r,children:i(n,ii)},c[a[u]]=o},u=function(e,t){for(var n,r,o,i=fi(e),a=i.length,u=fi(t);a--;)for(n=c[i[a]],r=0,o=u.length;r<o;r++)n.attributes[u[r]]={},n.attributesOrder.push(u[r])};return oi[e]?oi[e]:(s="id accesskey class dir lang style tabindex title role",t="address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul",n="a abbr b bdo br button cite code del dfn em embed i iframe img input ins kbd label map noscript object q s samp script select small span strong sub sup textarea u var #text #comment","html4"!==e&&(s+=" contenteditable contextmenu draggable dropzone hidden spellcheck translate",t+=" article aside details dialog figure main header footer hgroup section nav",n+=" audio canvas command datalist mark meter output picture progress time wbr video ruby bdi keygen"),"html5-strict"!==e&&(s+=" xml:lang",n=[n,i="acronym applet basefont big font strike tt"].join(" "),ui(fi(i),function(e){a(e,"",n)}),t=[t,o="center dir isindex noframes"].join(" "),r=[t,n].join(" "),ui(fi(o),function(e){a(e,"",r)})),r=r||[t,n].join(" "),a("html","manifest","head body"),a("head","","base command link meta noscript script style title"),a("title hr noscript br"),a("base","href target"),a("link","href rel media hreflang type sizes hreflang"),a("meta","name http-equiv content charset"),a("style","media type scoped"),a("script","src async defer type charset"),a("body","onafterprint onbeforeprint onbeforeunload onblur onerror onfocus onhashchange onload onmessage onoffline ononline onpagehide onpageshow onpopstate onresize onscroll onstorage onunload",r),a("address dt dd div caption","",r),a("h1 h2 h3 h4 h5 h6 pre p abbr code var samp kbd sub sup i b u bdo span legend em strong small s cite dfn","",n),a("blockquote","cite",r),a("ol","reversed start type","li"),a("ul","","li"),a("li","value",r),a("dl","","dt dd"),a("a","href target rel media hreflang type",n),a("q","cite",n),a("ins del","cite datetime",r),a("img","src sizes srcset alt usemap ismap width height"),a("iframe","src name width height",r),a("embed","src type width height"),a("object","data type typemustmatch name usemap form width height",[r,"param"].join(" ")),a("param","name value"),a("map","name",[r,"area"].join(" ")),a("area","alt coords shape href target rel media hreflang type"),a("table","border","caption colgroup thead tfoot tbody tr"+("html4"===e?" col":"")),a("colgroup","span","col"),a("col","span"),a("tbody thead tfoot","","tr"),a("tr","","td th"),a("td","colspan rowspan headers",r),a("th","colspan rowspan headers scope abbr",r),a("form","accept-charset action autocomplete enctype method name novalidate target",r),a("fieldset","disabled form name",[r,"legend"].join(" ")),a("label","form for",n),a("input","accept alt autocomplete checked dirname disabled form formaction formenctype formmethod formnovalidate formtarget height list max maxlength min multiple name pattern readonly required size src step type value width"),a("button","disabled form formaction formenctype formmethod formnovalidate formtarget name type value","html4"===e?r:n),a("select","disabled form multiple name required size","option optgroup"),a("optgroup","disabled label","option"),a("option","disabled label selected value"),a("textarea","cols dirname disabled form maxlength name readonly required rows wrap"),a("menu","type label",[r,"li"].join(" ")),a("noscript","",r),"html4"!==e&&(a("wbr"),a("ruby","",[n,"rt rp"].join(" ")),a("figcaption","",r),a("mark rt rp summary bdi","",n),a("canvas","width height",r),a("video","src crossorigin poster preload autoplay mediagroup loop muted controls width height buffered",[r,"track source"].join(" ")),a("audio","src crossorigin preload autoplay mediagroup loop muted controls buffered volume",[r,"track source"].join(" ")),a("picture","","img source"),a("source","src srcset type media sizes"),a("track","kind src srclang label default"),a("datalist","",[n,"option"].join(" ")),a("article section nav aside main header footer","",r),a("hgroup","","h1 h2 h3 h4 h5 h6"),a("figure","",[r,"figcaption"].join(" ")),a("time","datetime",n),a("dialog","open",r),a("command","type label icon disabled checked radiogroup command"),a("output","for form name",n),a("progress","value max",n),a("meter","value min max low high optimum",n),a("details","open",[r,"summary"].join(" ")),a("keygen","autofocus challenge disabled form keytype name")),"html5-strict"!==e&&(u("script","language xml:space"),u("style","xml:space"),u("object","declare classid code codebase codetype archive standby align border hspace vspace"),u("embed","align name hspace vspace"),u("param","valuetype type"),u("a","charset name rev shape coords"),u("br","clear"),u("applet","codebase archive code object alt name width height align hspace vspace"),u("img","name longdesc align border hspace vspace"),u("iframe","longdesc frameborder marginwidth marginheight scrolling align"),u("font basefont","size color face"),u("input","usemap align"),u("select"),u("textarea"),u("h1 h2 h3 h4 h5 h6 div p legend caption","align"),u("ul","type compact"),u("li","type"),u("ol dl menu dir","compact"),u("pre","width xml:space"),u("hr","align noshade size width"),u("isindex","prompt"),u("table","summary width frame rules cellspacing cellpadding align bgcolor"),u("col","width align char charoff valign"),u("colgroup","width align char charoff valign"),u("thead","align char charoff valign"),u("tr","align char charoff valign bgcolor"),u("th","axis align char charoff valign nowrap bgcolor width height"),u("form","accept"),u("td","abbr axis scope align char charoff valign nowrap bgcolor width height"),u("tfoot","align char charoff valign"),u("tbody","align char charoff valign"),u("area","nohref"),u("body","background bgcolor text link vlink alink")),"html4"!==e&&(u("input button select textarea","autofocus"),u("input textarea","placeholder"),u("a","download"),u("link script img","crossorigin"),u("img","loading"),u("iframe","sandbox seamless allowfullscreen loading")),ui(fi("a form meter progress dfn"),function(e){c[e]&&delete c[e].children[e]}),delete c.caption.children.table,delete c.script,oi[e]=c)},mi=function(e,n){var r;return e&&(r={},"string"==typeof e&&(e={"*":e}),ui(e,function(e,t){r[t]=r[t.toUpperCase()]=("map"===n?ai:ci)(e,/[, ]/)})),r};function pi(i){var S={},u={},N=[],s={},t={},e=function(e,t,n){var r=i[e];return r?r=ai(r,/[, ]/,ai(r.toUpperCase(),/[, ]/)):(r=oi[e])||(r=ai(t," ",ai(t.toUpperCase()," ")),r=si(r,n),oi[e]=r),r},n=di((i=i||{}).schema);!1===i.verify_html&&(i.valid_elements="*[*]");var r=mi(i.valid_styles),o=mi(i.invalid_styles,"map"),a=mi(i.valid_classes,"map"),c=e("whitespace_elements","pre script noscript style textarea video audio iframe object code"),l=e("self_closing_elements","colgroup dd dt li option p td tfoot th thead tr"),f=e("short_ended_elements","area base basefont br col frame hr img input isindex link meta param embed source wbr track"),d=e("boolean_attributes","checked compact declare defer disabled ismap multiple nohref noresize noshade nowrap readonly selected autoplay loop controls"),m="td th iframe video audio object script code",p=e("non_empty_elements",m+" pre",f),g=e("move_caret_before_on_enter_elements",m+" table",f),h=e("text_block_elements","h1 h2 h3 h4 h5 h6 p div address pre form blockquote center dir fieldset header footer article section hgroup aside main nav figure"),v=e("block_elements","hr table tbody thead tfoot th tr td li ol ul caption dl dt dd noscript menu isindex option datalist select optgroup figcaption details summary",h),y=e("text_inline_elements","span strong b em i font strike u var cite dfn code mark q sup sub samp");ui((i.special||"script noscript iframe noframes noembed title style textarea xmp").split(" "),function(e){t[e]=new RegExp("</"+e+"[^>]*>","gi")});var E=function(e){return new RegExp("^"+e.replace(/([?+*])/g,".$1")+"$")},b=function(e){var t,n,r,o,i,a,u,s,c,l,f,d,m,p,g,h,v,y,b=/^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)])?$/,C=/^([!\-])?(\w+[\\:]:\w+|[^=:<]+)?(?:([=:<])(.*))?$/,w=/[*?+]/;if(e){var x=fi(e,",");for(S["@"]&&(h=S["@"].attributes,v=S["@"].attributesOrder),t=0,n=x.length;t<n;t++)if(i=b.exec(x[t])){if(p=i[1],c=i[2],g=i[3],s=i[5],a={attributes:d={},attributesOrder:m=[]},"#"===p&&(a.paddEmpty=!0),"-"===p&&(a.removeEmpty=!0),"!"===i[4]&&(a.removeEmptyAttrs=!0),h&&(oe(h,function(e,t){d[t]=e}),m.push.apply(m,v)),s)for(r=0,o=(s=fi(s,"|")).length;r<o;r++)if(i=C.exec(s[r])){if(u={},f=i[1],l=i[2].replace(/[\\:]:/g,":"),p=i[3],y=i[4],"!"===f&&(a.attributesRequired=a.attributesRequired||[],a.attributesRequired.push(l),u.required=!0),"-"===f){delete d[l],m.splice(li(m,l),1);continue}p&&("="===p&&(a.attributesDefault=a.attributesDefault||[],a.attributesDefault.push({name:l,value:y}),u.defaultValue=y),":"===p&&(a.attributesForced=a.attributesForced||[],a.attributesForced.push({name:l,value:y}),u.forcedValue=y),"<"===p&&(u.validValues=ai(y,"?"))),w.test(l)?(a.attributePatterns=a.attributePatterns||[],u.pattern=E(l),a.attributePatterns.push(u)):(d[l]||m.push(l),d[l]=u)}h||"@"!==c||(h=d,v=m),g&&(a.outputName=c,S[g]=a),w.test(c)?(a.pattern=E(c),N.push(a)):S[c]=a}}},C=function(e){S={},N=[],b(e),ui(n,function(e,t){u[t]=e.children})},w=function(e){var a=/^(~)?(.+)$/;e&&(oi.text_block_elements=oi.block_elements=null,ui(fi(e,","),function(e){var t,n=a.exec(e),r="~"===n[1],o=r?"span":"div",i=n[2];u[i]=u[o],s[i]=o,r||(v[i.toUpperCase()]={},v[i]={}),S[i]||(t=S[o],delete(t=si({},t)).removeEmptyAttrs,delete t.removeEmpty,S[i]=t),ui(u,function(e,t){e[o]&&(u[t]=e=si({},u[t]),e[i]=e[o])})}))},x=function(e){var o=/^([+\-]?)([A-Za-z0-9_\-.\u00b7\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]+)\[([^\]]+)]$/;oi[i.schema]=null,e&&ui(fi(e,","),function(e){var t,n,r=o.exec(e);r&&(n=r[1],t=n?u[r[2]]:u[r[2]]={"#comment":{}},t=u[r[2]],ui(fi(r[3],"|"),function(e){"-"===n?delete t[e]:t[e]={}}))})},k=function(e){var t,n=S[e];if(n)return n;for(t=N.length;t--;)if((n=N[t]).pattern.test(e))return n};i.valid_elements?C(i.valid_elements):(ui(n,function(e,t){S[t]={attributes:e.attributes,attributesOrder:e.attributesOrder},u[t]=e.children}),"html5"!==i.schema&&ui(fi("strong/b em/i"),function(e){var t=fi(e,"/");S[t[1]].outputName=t[0]}),ui(fi("ol ul sub sup blockquote span font a table tbody tr strong em b i"),function(e){S[e]&&(S[e].removeEmpty=!0)}),ui(fi("p h1 h2 h3 h4 h5 h6 th td pre div address caption li"),function(e){S[e].paddEmpty=!0}),ui(fi("span"),function(e){S[e].removeEmptyAttrs=!0})),w(i.custom_elements),x(i.valid_children),b(i.extended_valid_elements),x("+ol[ul|ol],+ul[ul|ol]"),ui({dd:"dl",dt:"dl",li:"ul ol",td:"tr",th:"tr",tr:"tbody thead tfoot",tbody:"table",thead:"table",tfoot:"table",legend:"fieldset",area:"map",param:"video audio object"},function(e,t){S[t]&&(S[t].parentsRequired=fi(e))}),i.invalid_elements&&ui(ci(i.invalid_elements),function(e){S[e]&&delete S[e]}),k("span")||b("span[!data-mce-type|*]");return{children:u,elements:S,getValidStyles:function(){return r},getValidClasses:function(){return a},getBlockElements:function(){return v},getInvalidStyles:function(){return o},getShortEndedElements:function(){return f},getTextBlockElements:function(){return h},getTextInlineElements:function(){return y},getBoolAttrs:function(){return d},getElementRule:k,getSelfClosingElements:function(){return l},getNonEmptyElements:function(){return p},getMoveCaretBeforeOnEnterElements:function(){return g},getWhiteSpaceElements:function(){return c},getSpecialElements:function(){return t},isValidChild:function(e,t){var n=u[e.toLowerCase()];return!(!n||!n[t.toLowerCase()])},isValid:function(e,t){var n,r,o=k(e);if(o){if(!t)return!0;if(o.attributes[t])return!0;if(n=o.attributePatterns)for(r=n.length;r--;)if(n[r].pattern.test(e))return!0}return!1},getCustomElements:function(){return s},addValidElements:b,setValidElements:C,addCustomElements:w,addValidChildren:x}}var gi=function(e,t,n,r){var o=function(e){return 1<(e=parseInt(e,10).toString(16)).length?e:"0"+e};return"#"+o(t)+o(n)+o(r)},hi=function(b,e){var s,c,C=/rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi,w=/(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi,x=/\s*([^:]+):\s*([^;]+);?/g,S=/\s+$/,N={},E=ro;b=b||{},e&&(s=e.getValidStyles(),c=e.getInvalidStyles());for(var t=("\\\" \\' \\; \\: ; : "+E).split(" "),k=0;k<t.length;k++)N[t[k]]=E+k,N[E+k]=t[k];return{toHex:function(e){return e.replace(C,gi)},parse:function(e){var t,n,r,o,i,a,u,s,c={},l=b.url_converter,f=b.url_converter_scope||this,d=function(e,t,n){var r=c[e+"-top"+t];if(r){var o=c[e+"-right"+t];if(o){var i=c[e+"-bottom"+t];if(i){var a=c[e+"-left"+t];if(a){var u=[r,o,i,a];for(k=u.length-1;k--&&u[k]===u[k+1];);-1<k&&n||(c[e+t]=-1===k?u[0]:u.join(" "),delete c[e+"-top"+t],delete c[e+"-right"+t],delete c[e+"-bottom"+t],delete c[e+"-left"+t])}}}}},m=function(e){var t,n=c[e];if(n){for(t=(n=n.split(" ")).length;t--;)if(n[t]!==n[0])return!1;return c[e]=n[0],!0}},p=function(e){return o=!0,N[e]},g=function(e,t){return o&&(e=e.replace(/\uFEFF[0-9]/g,function(e){return N[e]})),t||(e=e.replace(/\\([\'\";:])/g,"$1")),e},h=function(e){return String.fromCharCode(parseInt(e.slice(1),16))},v=function(e){return e.replace(/\\[0-9a-f]+/gi,h)},y=function(e,t,n,r,o,i){if(o=o||i)return"'"+(o=g(o)).replace(/\'/g,"\\'")+"'";if(t=g(t||n||r),!b.allow_script_urls){var a=t.replace(/[\s\r\n]+/g,"");if(/(java|vb)script:/i.test(a))return"";if(!b.allow_svg_data_urls&&/^data:image\/svg/i.test(a))return""}return l&&(t=l.call(f,t,"style")),"url('"+t.replace(/\'/g,"\\'")+"')"};if(e){for(e=(e=e.replace(/[\u0000-\u001F]/g,"")).replace(/\\[\"\';:\uFEFF]/g,p).replace(/\"[^\"]+\"|\'[^\']+\'/g,function(e){return e.replace(/[;:]/g,p)});t=x.exec(e);)if(x.lastIndex=t.index+t[0].length,n=t[1].replace(S,"").toLowerCase(),r=t[2].replace(S,""),n&&r){if(n=v(n),r=v(r),-1!==n.indexOf(E)||-1!==n.indexOf('"'))continue;if(!b.allow_script_urls&&("behavior"===n||/expression\s*\(|\/\*|\*\//.test(r)))continue;"font-weight"===n&&"700"===r?r="bold":"color"!==n&&"background-color"!==n||(r=r.toLowerCase()),r=(r=r.replace(C,gi)).replace(w,y),c[n]=o?g(r,!0):r}d("border","",!0),d("border","-width"),d("border","-color"),d("border","-style"),d("padding",""),d("margin",""),i="border",u="border-style",s="border-color",m(a="border-width")&&m(u)&&m(s)&&(c[i]=c[a]+" "+c[u]+" "+c[s],delete c[a],delete c[u],delete c[s]),"medium none"===c.border&&delete c.border,"none"===c["border-image"]&&delete c["border-image"]}return c},serialize:function(i,a){var u="",e=function(e){var t,n=s[e];if(n)for(var r=0,o=n.length;r<o;r++)e=n[r],(t=i[e])&&(u+=(0<u.length?" ":"")+e+": "+t+";")};return a&&s?(e("*"),e(a)):oe(i,function(e,t){var n,r,o;!e||c&&(n=t,r=a,(o=c["*"])&&o[n]||(o=c[r])&&o[n])||(u+=(0<u.length?" ":"")+t+": "+e+";")}),u}}},vi=/^(?:mouse|contextmenu)|click/,yi={keyLocation:1,layerX:1,layerY:1,returnValue:1,webkitMovementX:1,webkitMovementY:1,keyIdentifier:1,mozPressure:1},bi=function(){return!1},Ci=function(){return!0},wi=function(e,t,n,r){e.addEventListener?e.addEventListener(t,n,r||!1):e.attachEvent&&e.attachEvent("on"+t,n)},xi=function(e,t,n,r){e.removeEventListener?e.removeEventListener(t,n,r||!1):e.detachEvent&&e.detachEvent("on"+t,n)},Si=function(e,t){var n,r,o,i,a,u,s=t||{};for(n in e)yi[n]||(s[n]=e[n]);return s.target||(s.target=s.srcElement||document),s.composedPath&&(s.composedPath=function(){return e.composedPath()}),e&&(a=e,vi.test(a.type))&&e.pageX===undefined&&e.clientX!==undefined&&(o=(r=s.target.ownerDocument||document).documentElement,i=r.body,s.pageX=e.clientX+(o&&o.scrollLeft||i&&i.scrollLeft||0)-(o&&o.clientLeft||i&&i.clientLeft||0),s.pageY=e.clientY+(o&&o.scrollTop||i&&i.scrollTop||0)-(o&&o.clientTop||i&&i.clientTop||0)),s.preventDefault=function(){s.isDefaultPrevented=Ci,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},s.stopPropagation=function(){s.isPropagationStopped=Ci,e&&(e.stopPropagation?e.stopPropagation():e.cancelBubble=!0)},!(s.stopImmediatePropagation=function(){s.isImmediatePropagationStopped=Ci,s.stopPropagation()})==((u=s).isDefaultPrevented===Ci||u.isDefaultPrevented===bi)&&(s.isDefaultPrevented=bi,s.isPropagationStopped=bi,s.isImmediatePropagationStopped=bi),"undefined"==typeof s.metaKey&&(s.metaKey=!1),s},Ni=(Ei.prototype.bind=function(e,t,n,r){var o,i,a,u,s,c,l=this,f=window,d=function(e){l.executeHandlers(Si(e||f.event),o)};if(e&&3!==e.nodeType&&8!==e.nodeType){e[l.expando]?o=e[l.expando]:(o=l.count++,e[l.expando]=o,l.events[o]={}),r=r||e;for(var m=t.split(" "),p=m.length;p--;)s=d,u=c=!1,"DOMContentLoaded"===(a=m[p])&&(a="ready"),l.domLoaded&&"ready"===a&&"complete"===e.readyState?n.call(r,Si({type:a})):(l.hasMouseEnterLeave||(u=l.mouseEnterLeave[a])&&(s=function(e){var t=e.currentTarget,n=e.relatedTarget;if(n&&t.contains)n=t.contains(n);else for(;n&&n!==t;)n=n.parentNode;n||((e=Si(e||f.event)).type="mouseout"===e.type?"mouseleave":"mouseenter",e.target=t,l.executeHandlers(e,o))}),l.hasFocusIn||"focusin"!==a&&"focusout"!==a||(c=!0,u="focusin"===a?"focus":"blur",s=function(e){(e=Si(e||f.event)).type="focus"===e.type?"focusin":"focusout",l.executeHandlers(e,o)}),(i=l.events[o][a])?"ready"===a&&l.domLoaded?n(Si({type:a})):i.push({func:n,scope:r}):(l.events[o][a]=i=[{func:n,scope:r}],i.fakeName=u,i.capture=c,i.nativeHandler=s,"ready"===a?function(e,t,n){var r,o=e.document,i={type:"ready"};n.domLoaded?t(i):(r=function(){xi(e,"DOMContentLoaded",r),xi(e,"load",r),n.domLoaded||(n.domLoaded=!0,t(i))},"complete"===o.readyState||"interactive"===o.readyState&&o.body?r():wi(e,"DOMContentLoaded",r),wi(e,"load",r))}(e,s,l):wi(e,u||a,s,c)));return e=i=null,n}},Ei.prototype.unbind=function(n,e,t){var r,o,i;if(!n||3===n.nodeType||8===n.nodeType)return this;var a=n[this.expando];if(a){if(i=this.events[a],e){for(var u,s,c,l,f=e.split(" "),d=f.length;d--;)if(l=i[o=f[d]]){if(t)for(r=l.length;r--;)l[r].func===t&&(u=l.nativeHandler,s=l.fakeName,c=l.capture,(l=l.slice(0,r).concat(l.slice(r+1))).nativeHandler=u,l.fakeName=s,l.capture=c,i[o]=l);t&&0!==l.length||(delete i[o],xi(n,l.fakeName||o,l.nativeHandler,l.capture))}}else oe(i,function(e,t){xi(n,e.fakeName||t,e.nativeHandler,e.capture)}),i={};for(o in i)if(me(i,o))return this;delete this.events[a];try{delete n[this.expando]}catch(m){n[this.expando]=null}}return this},Ei.prototype.fire=function(e,t,n){var r;if(!e||3===e.nodeType||8===e.nodeType)return this;var o=Si(null,n);for(o.type=t,o.target=e;(r=e[this.expando])&&this.executeHandlers(o,r),(e=e.parentNode||e.ownerDocument||e.defaultView||e.parentWindow)&&!o.isPropagationStopped(););return this},Ei.prototype.clean=function(e){var t,n;if(!e||3===e.nodeType||8===e.nodeType)return this;if(e[this.expando]&&this.unbind(e),e.getElementsByTagName||(e=e.document),e&&e.getElementsByTagName)for(this.unbind(e),t=(n=e.getElementsByTagName("*")).length;t--;)(e=n[t])[this.expando]&&this.unbind(e);return this},Ei.prototype.destroy=function(){this.events={}},Ei.prototype.cancel=function(e){return e&&(e.preventDefault(),e.stopImmediatePropagation()),!1},Ei.prototype.executeHandlers=function(e,t){var n=this.events[t],r=n&&n[e.type];if(r)for(var o=0,i=r.length;o<i;o++){var a=r[o];if(a&&!1===a.func.call(a.scope,e)&&e.preventDefault(),e.isImmediatePropagationStopped())return}},Ei.Event=new Ei,Ei);function Ei(){this.domLoaded=!1,this.events={},this.count=1,this.expando="mce-data-"+(+new Date).toString(32),this.hasMouseEnterLeave="onmouseenter"in document.documentElement,this.hasFocusIn="onfocusin"in document.documentElement,this.count=1}var ki,_i,Ri,Ti,Ai,Di,Oi,Bi,Pi,Li,Ii,Mi,Fi,Ui,zi,ji,Hi,Vi="sizzle"+-new Date,qi=window.document,$i=0,Wi=0,Ki=Ea(),Xi=Ea(),Yi=Ea(),Gi=function(e,t){return e===t&&(Li=!0),0},Ji=typeof undefined,Qi={}.hasOwnProperty,Zi=[],ea=Zi.pop,ta=Zi.push,na=Zi.push,ra=Zi.slice,oa=Zi.indexOf||function(e){for(var t=0,n=this.length;t<n;t++)if(this[t]===e)return t;return-1},ia="[\\x20\\t\\r\\n\\f]",aa="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",ua="\\["+ia+"*("+aa+")(?:"+ia+"*([*^$|!~]?=)"+ia+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+aa+"))|)"+ia+"*\\]",sa=":("+aa+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+ua+")*)|.*)\\)|)",ca=new RegExp("^"+ia+"+|((?:^|[^\\\\])(?:\\\\.)*)"+ia+"+$","g"),la=new RegExp("^"+ia+"*,"+ia+"*"),fa=new RegExp("^"+ia+"*([>+~]|"+ia+")"+ia+"*"),da=new RegExp("="+ia+"*([^\\]'\"]*?)"+ia+"*\\]","g"),ma=new RegExp(sa),pa=new RegExp("^"+aa+"$"),ga={ID:new RegExp("^#("+aa+")"),CLASS:new RegExp("^\\.("+aa+")"),TAG:new RegExp("^("+aa+"|[*])"),ATTR:new RegExp("^"+ua),PSEUDO:new RegExp("^"+sa),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+ia+"*(even|odd|(([+-]|)(\\d*)n|)"+ia+"*(?:([+-]|)"+ia+"*(\\d+)|))"+ia+"*\\)|)","i"),bool:new RegExp("^(?:checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)$","i"),needsContext:new RegExp("^"+ia+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+ia+"*((?:-\\d)?\\d*)"+ia+"*\\)|)(?=[^-]|$)","i")},ha=/^(?:input|select|textarea|button)$/i,va=/^h\d$/i,ya=/^[^{]+\{\s*\[native \w/,ba=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,Ca=/[+~]/,wa=/'|\\/g,xa=new RegExp("\\\\([\\da-f]{1,6}"+ia+"?|("+ia+")|.)","ig"),Sa=function(e,t,n){var r="0x"+t-65536;return r!=r||n?t:r<0?String.fromCharCode(65536+r):String.fromCharCode(r>>10|55296,1023&r|56320)};try{na.apply(Zi=ra.call(qi.childNodes),qi.childNodes),Zi[qi.childNodes.length].nodeType}catch(pk){na={apply:Zi.length?function(e,t){ta.apply(e,ra.call(t))}:function(e,t){for(var n=e.length,r=0;e[n++]=t[r++];);e.length=n-1}}}var Na=function(e,t,n,r){var o,i,a,u,s,c,l,f,d,m;if((t?t.ownerDocument||t:qi)!==Mi&&Ii(t),n=n||[],!e||"string"!=typeof e)return n;if(1!==(u=(t=t||Mi).nodeType)&&9!==u)return[];if(Ui&&!r){if(o=ba.exec(e))if(a=o[1]){if(9===u){if(!(i=t.getElementById(a))||!i.parentNode)return n;if(i.id===a)return n.push(i),n}else if(t.ownerDocument&&(i=t.ownerDocument.getElementById(a))&&Hi(t,i)&&i.id===a)return n.push(i),n}else{if(o[2])return na.apply(n,t.getElementsByTagName(e)),n;if((a=o[3])&&ki.getElementsByClassName)return na.apply(n,t.getElementsByClassName(a)),n}if(ki.qsa&&(!zi||!zi.test(e))){if(f=l=Vi,d=t,m=9===u&&e,1===u&&"object"!==t.nodeName.toLowerCase()){for(c=Ai(e),(l=t.getAttribute("id"))?f=l.replace(wa,"\\$&"):t.setAttribute("id",f),f="[id='"+f+"'] ",s=c.length;s--;)c[s]=f+Da(c[s]);d=Ca.test(e)&&Ta(t.parentNode)||t,m=c.join(",")}if(m)try{return na.apply(n,d.querySelectorAll(m)),n}catch(p){}finally{l||t.removeAttribute("id")}}}return Oi(e.replace(ca,"$1"),t,n,r)};function Ea(){var n=[];function r(e,t){return n.push(e+" ")>_i.cacheLength&&delete r[n.shift()],r[e+" "]=t}return r}function ka(e){return e[Vi]=!0,e}function _a(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||1<<31)-(~e.sourceIndex||1<<31);if(r)return r;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function Ra(a){return ka(function(i){return i=+i,ka(function(e,t){for(var n,r=a([],e.length,i),o=r.length;o--;)e[n=r[o]]&&(e[n]=!(t[n]=e[n]))})})}function Ta(e){return e&&typeof e.getElementsByTagName!=Ji&&e}function Aa(){}function Da(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function Oa(a,e,t){var u=e.dir,s=t&&"parentNode"===u,c=Wi++;return e.first?function(e,t,n){for(;e=e[u];)if(1===e.nodeType||s)return a(e,t,n)}:function(e,t,n){var r,o,i=[$i,c];if(n){for(;e=e[u];)if((1===e.nodeType||s)&&a(e,t,n))return!0}else for(;e=e[u];)if(1===e.nodeType||s){if((r=(o=e[Vi]||(e[Vi]={}))[u])&&r[0]===$i&&r[1]===c)return i[2]=r[2];if((o[u]=i)[2]=a(e,t,n))return!0}}}function Ba(o){return 1<o.length?function(e,t,n){for(var r=o.length;r--;)if(!o[r](e,t,n))return!1;return!0}:o[0]}function Pa(e,t,n,r,o){for(var i,a=[],u=0,s=e.length,c=null!=t;u<s;u++)(i=e[u])&&(n&&!n(i,r,o)||(a.push(i),c&&t.push(u)));return a}function La(m,p,g,h,v,e){return h&&!h[Vi]&&(h=La(h)),v&&!v[Vi]&&(v=La(v,e)),ka(function(e,t,n,r){var o,i,a,u=[],s=[],c=t.length,l=e||function(e,t,n){for(var r=0,o=t.length;r<o;r++)Na(e,t[r],n);return n}(p||"*",n.nodeType?[n]:n,[]),f=!m||!e&&p?l:Pa(l,u,m,n,r),d=g?v||(e?m:c||h)?[]:t:f;if(g&&g(f,d,n,r),h)for(o=Pa(d,s),h(o,[],n,r),i=o.length;i--;)(a=o[i])&&(d[s[i]]=!(f[s[i]]=a));if(e){if(v||m){if(v){for(o=[],i=d.length;i--;)(a=d[i])&&o.push(f[i]=a);v(null,d=[],o,r)}for(i=d.length;i--;)(a=d[i])&&-1<(o=v?oa.call(e,a):u[i])&&(e[o]=!(t[o]=a))}}else d=Pa(d===t?d.splice(c,d.length):d),v?v(null,t,d,r):na.apply(t,d)})}ki=Na.support={},Ti=Na.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return!!t&&"HTML"!==t.nodeName},Ii=Na.setDocument=function(e){var t,s=e?e.ownerDocument||e:qi,n=s.defaultView;return s!==Mi&&9===s.nodeType&&s.documentElement?(Fi=(Mi=s).documentElement,Ui=!Ti(s),n&&n!==function(e){try{return e.top}catch(t){}return null}(n)&&(n.addEventListener?n.addEventListener("unload",function(){Ii()},!1):n.attachEvent&&n.attachEvent("onunload",function(){Ii()})),ki.attributes=!0,ki.getElementsByTagName=!0,ki.getElementsByClassName=ya.test(s.getElementsByClassName),ki.getById=!0,_i.find.ID=function(e,t){if(typeof t.getElementById!=Ji&&Ui){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},_i.filter.ID=function(e){var t=e.replace(xa,Sa);return function(e){return e.getAttribute("id")===t}},_i.find.TAG=ki.getElementsByTagName?function(e,t){if(typeof t.getElementsByTagName!=Ji)return t.getElementsByTagName(e)}:function(e,t){var n,r=[],o=0,i=t.getElementsByTagName(e);if("*"!==e)return i;for(;n=i[o++];)1===n.nodeType&&r.push(n);return r},_i.find.CLASS=ki.getElementsByClassName&&function(e,t){if(Ui)return t.getElementsByClassName(e)},ji=[],zi=[],ki.disconnectedMatch=!0,zi=zi.length&&new RegExp(zi.join("|")),ji=ji.length&&new RegExp(ji.join("|")),t=ya.test(Fi.compareDocumentPosition),Hi=t||ya.test(Fi.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},Gi=t?function(e,t){if(e===t)return Li=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!ki.sortDetached&&t.compareDocumentPosition(e)===n?e===s||e.ownerDocument===qi&&Hi(qi,e)?-1:t===s||t.ownerDocument===qi&&Hi(qi,t)?1:Pi?oa.call(Pi,e)-oa.call(Pi,t):0:4&n?-1:1)}:function(e,t){if(e===t)return Li=!0,0;var n,r=0,o=e.parentNode,i=t.parentNode,a=[e],u=[t];if(!o||!i)return e===s?-1:t===s?1:o?-1:i?1:Pi?oa.call(Pi,e)-oa.call(Pi,t):0;if(o===i)return _a(e,t);for(n=e;n=n.parentNode;)a.unshift(n);for(n=t;n=n.parentNode;)u.unshift(n);for(;a[r]===u[r];)r++;return r?_a(a[r],u[r]):a[r]===qi?-1:u[r]===qi?1:0},s):Mi},Na.matches=function(e,t){return Na(e,null,null,t)},Na.matchesSelector=function(e,t){if((e.ownerDocument||e)!==Mi&&Ii(e),t=t.replace(da,"='$1']"),ki.matchesSelector&&Ui&&(!ji||!ji.test(t))&&(!zi||!zi.test(t)))try{var n=(void 0).call(e,t);if(n||ki.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(pk){}return 0<Na(t,Mi,null,[e]).length},Na.contains=function(e,t){return(e.ownerDocument||e)!==Mi&&Ii(e),Hi(e,t)},Na.attr=function(e,t){(e.ownerDocument||e)!==Mi&&Ii(e);var n=_i.attrHandle[t.toLowerCase()],r=n&&Qi.call(_i.attrHandle,t.toLowerCase())?n(e,t,!Ui):undefined;return r!==undefined?r:ki.attributes||!Ui?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},Na.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},Na.uniqueSort=function(e){var t,n=[],r=0,o=0;if(Li=!ki.detectDuplicates,Pi=!ki.sortStable&&e.slice(0),e.sort(Gi),Li){for(;t=e[o++];)t===e[o]&&(r=n.push(o));for(;r--;)e.splice(n[r],1)}return Pi=null,e},Ri=Na.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=Ri(e)}else if(3===o||4===o)return e.nodeValue}else for(;t=e[r++];)n+=Ri(t);return n},(_i=Na.selectors={cacheLength:50,createPseudo:ka,match:ga,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(xa,Sa),e[3]=(e[3]||e[4]||e[5]||"").replace(xa,Sa),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||Na.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&Na.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return ga.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&ma.test(n)&&(t=Ai(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(xa,Sa).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=Ki[e+" "];return t||(t=new RegExp("(^|"+ia+")"+e+"("+ia+"|$)"))&&Ki(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!=Ji&&e.getAttribute("class")||"")})},ATTR:function(n,r,o){return function(e){var t=Na.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===o:"!="===r?t!==o:"^="===r?o&&0===t.indexOf(o):"*="===r?o&&-1<t.indexOf(o):"$="===r?o&&t.slice(-o.length)===o:"~="===r?-1<(" "+t+" ").indexOf(o):"|="===r&&(t===o||t.slice(0,o.length+1)===o+"-"))}},CHILD:function(m,e,t,p,g){var h="nth"!==m.slice(0,3),v="last"!==m.slice(-4),y="of-type"===e;return 1===p&&0===g?function(e){return!!e.parentNode}:function(e,t,n){var r,o,i,a,u,s,c=h!=v?"nextSibling":"previousSibling",l=e.parentNode,f=y&&e.nodeName.toLowerCase(),d=!n&&!y;if(l){if(h){for(;c;){for(i=e;i=i[c];)if(y?i.nodeName.toLowerCase()===f:1===i.nodeType)return!1;s=c="only"===m&&!s&&"nextSibling"}return!0}if(s=[v?l.firstChild:l.lastChild],v&&d){for(u=(r=(o=l[Vi]||(l[Vi]={}))[m]||[])[0]===$i&&r[1],a=r[0]===$i&&r[2],i=u&&l.childNodes[u];i=++u&&i&&i[c]||(a=u=0)||s.pop();)if(1===i.nodeType&&++a&&i===e){o[m]=[$i,u,a];break}}else if(d&&(r=(e[Vi]||(e[Vi]={}))[m])&&r[0]===$i)a=r[1];else for(;(i=++u&&i&&i[c]||(a=u=0)||s.pop())&&((y?i.nodeName.toLowerCase()!==f:1!==i.nodeType)||!++a||(d&&((i[Vi]||(i[Vi]={}))[m]=[$i,a]),i!==e)););return(a-=g)===p||a%p==0&&0<=a/p}}},PSEUDO:function(e,i){var t,a=_i.pseudos[e]||_i.setFilters[e.toLowerCase()]||Na.error("unsupported pseudo: "+e);return a[Vi]?a(i):1<a.length?(t=[e,e,"",i],_i.setFilters.hasOwnProperty(e.toLowerCase())?ka(function(e,t){for(var n,r=a(e,i),o=r.length;o--;)e[n=oa.call(e,r[o])]=!(t[n]=r[o])}):function(e){return a(e,0,t)}):a}},pseudos:{not:ka(function(e){var r=[],o=[],u=Di(e.replace(ca,"$1"));return u[Vi]?ka(function(e,t,n,r){for(var o,i=u(e,null,r,[]),a=e.length;a--;)(o=i[a])&&(e[a]=!(t[a]=o))}):function(e,t,n){return r[0]=e,u(r,null,n,o),!o.pop()}}),has:ka(function(t){return function(e){return 0<Na(t,e).length}}),contains:ka(function(t){return t=t.replace(xa,Sa),function(e){return-1<(e.textContent||e.innerText||Ri(e)).indexOf(t)}}),lang:ka(function(n){return pa.test(n||"")||Na.error("unsupported lang: "+n),n=n.replace(xa,Sa).toLowerCase(),function(e){var t;do{if(t=Ui?e.lang:e.getAttribute("xml:lang")||e.getAttribute("lang"))return(t=t.toLowerCase())===n||0===t.indexOf(n+"-")}while((e=e.parentNode)&&1===e.nodeType);return!1}}),target:function(e){var t=window.location&&window.location.hash;return t&&t.slice(1)===e.id},root:function(e){return e===Fi},focus:function(e){return e===Mi.activeElement&&(!Mi.hasFocus||Mi.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return!1===e.disabled},disabled:function(e){return!0===e.disabled},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!_i.pseudos.empty(e)},header:function(e){return va.test(e.nodeName)},input:function(e){return ha.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:Ra(function(){return[0]}),last:Ra(function(e,t){return[t-1]}),eq:Ra(function(e,t,n){return[n<0?n+t:n]}),even:Ra(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:Ra(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:Ra(function(e,t,n){for(var r=n<0?n+t:n;0<=--r;)e.push(r);return e}),gt:Ra(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=_i.pseudos.eq,$(["radio","checkbox","file","password","image"],function(e){var t;_i.pseudos[e]=(t=e,function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t})}),$(["submit","reset"],function(e){var n;_i.pseudos[e]=(n=e,function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n})}),Aa.prototype=_i.filters=_i.pseudos,_i.setFilters=new Aa,Ai=Na.tokenize=function(e,t){var n,r,o,i,a,u,s,c=Xi[e+" "];if(c)return t?0:c.slice(0);for(a=e,u=[],s=_i.preFilter;a;){for(i in n&&!(r=la.exec(a))||(r&&(a=a.slice(r[0].length)||a),u.push(o=[])),n=!1,(r=fa.exec(a))&&(n=r.shift(),o.push({value:n,type:r[0].replace(ca," ")}),a=a.slice(n.length)),_i.filter)_i.filter.hasOwnProperty(i)&&(!(r=ga[i].exec(a))||s[i]&&!(r=s[i](r))||(n=r.shift(),o.push({value:n,type:i,matches:r}),a=a.slice(n.length)));if(!n)break}return t?a.length:a?Na.error(e):Xi(e,u).slice(0)},Di=Na.compile=function(e,t){var n,h,v,y,b,r,o=[],i=[],a=Yi[e+" "];if(!a){for(n=(t=t||Ai(e)).length;n--;)(a=function f(e){for(var r,t,n,o=e.length,i=_i.relative[e[0].type],a=i||_i.relative[" "],u=i?1:0,s=Oa(function(e){return e===r},a,!0),c=Oa(function(e){return-1<oa.call(r,e)},a,!0),l=[function(e,t,n){return!i&&(n||t!==Bi)||((r=t).nodeType?s:c)(e,t,n)}];u<o;u++)if(t=_i.relative[e[u].type])l=[Oa(Ba(l),t)];else{if((t=_i.filter[e[u].type].apply(null,e[u].matches))[Vi]){for(n=++u;n<o&&!_i.relative[e[n].type];n++);return La(1<u&&Ba(l),1<u&&Da(e.slice(0,u-1).concat({value:" "===e[u-2].type?"*":""})).replace(ca,"$1"),t,u<n&&f(e.slice(u,n)),n<o&&f(e=e.slice(n)),n<o&&Da(e))}l.push(t)}return Ba(l)}(t[n]))[Vi]?o.push(a):i.push(a);(a=Yi(e,(h=i,y=0<(v=o).length,b=0<h.length,r=function(e,t,n,r,o){var i,a,u,s=0,c="0",l=e&&[],f=[],d=Bi,m=e||b&&_i.find.TAG("*",o),p=$i+=null==d?1:Math.random()||.1,g=m.length;for(o&&(Bi=t!==Mi&&t);c!==g&&null!=(i=m[c]);c++){if(b&&i){for(a=0;u=h[a++];)if(u(i,t,n)){r.push(i);break}o&&($i=p)}y&&((i=!u&&i)&&s--,e&&l.push(i))}if(s+=c,y&&c!==s){for(a=0;u=v[a++];)u(l,f,t,n);if(e){if(0<s)for(;c--;)l[c]||f[c]||(f[c]=ea.call(r));f=Pa(f)}na.apply(r,f),o&&!e&&0<f.length&&1<s+v.length&&Na.uniqueSort(r)}return o&&($i=p,Bi=d),l},y?ka(r):r))).selector=e}return a},Oi=Na.select=function(e,t,n,r){var o,i,a,u,s,c="function"==typeof e&&e,l=!r&&Ai(e=c.selector||e);if(n=n||[],1===l.length){if(2<(i=l[0]=l[0].slice(0)).length&&"ID"===(a=i[0]).type&&ki.getById&&9===t.nodeType&&Ui&&_i.relative[i[1].type]){if(!(t=(_i.find.ID(a.matches[0].replace(xa,Sa),t)||[])[0]))return n;c&&(t=t.parentNode),e=e.slice(i.shift().value.length)}for(o=ga.needsContext.test(e)?0:i.length;o--&&(a=i[o],!_i.relative[u=a.type]);)if((s=_i.find[u])&&(r=s(a.matches[0].replace(xa,Sa),Ca.test(i[0].type)&&Ta(t.parentNode)||t))){if(i.splice(o,1),!(e=r.length&&Da(i)))return na.apply(n,r),n;break}}return(c||Di(e,l))(r,t,!Ui,n,Ca.test(e)&&Ta(t.parentNode)||t),n},ki.sortStable=Vi.split("").sort(Gi).join("")===Vi,ki.detectDuplicates=!!Li,Ii(),ki.sortDetached=!0;var Ia=document,Ma=Array.prototype.push,Fa=Array.prototype.slice,Ua=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,za=Ni.Event,ja=xt.makeMap("children,contents,next,prev"),Ha=function(e){return void 0!==e},Va=function(e){return"string"==typeof e},qa=function(e,t){var n,r=(t=t||Ia).createElement("div"),o=t.createDocumentFragment();for(r.innerHTML=e;n=r.firstChild;)o.appendChild(n);return o},$a=function(e,t,n,r){var o;if(Va(t))t=qa(t,iu(e[0]));else if(t.length&&!t.nodeType){if(t=lu.makeArray(t),r)for(o=t.length-1;0<=o;o--)$a(e,t[o],n,r);else for(o=0;o<t.length;o++)$a(e,t[o],n,r);return e}if(t.nodeType)for(o=e.length;o--;)n.call(e[o],t);return e},Wa=function(e,t){return e&&t&&-1!==(" "+e.className+" ").indexOf(" "+t+" ")},Ka=function(e,t,n){var r,o;return t=lu(t)[0],e.each(function(){n&&r===this.parentNode||(r=this.parentNode,o=t.cloneNode(!1),this.parentNode.insertBefore(o,this)),o.appendChild(this)}),e},Xa=xt.makeMap("fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom"," "),Ya=xt.makeMap("checked compact declare defer disabled ismap multiple nohref noshade nowrap readonly selected"," "),Ga={"for":"htmlFor","class":"className",readonly:"readOnly"},Ja={"float":"cssFloat"},Qa={},Za={},eu=function(e,t){return new lu.fn.init(e,t)},tu=/^\s*|\s*$/g,nu=function(e){return null===e||e===undefined?"":(""+e).replace(tu,"")},ru=function(e,t){var n,r,o,i;if(e)if((n=e.length)===undefined){for(r in e)if(e.hasOwnProperty(r)&&(i=e[r],!1===t.call(i,r,i)))break}else for(o=0;o<n&&(i=e[o],!1!==t.call(i,o,i));o++);return e},ou=function(e,n){var r=[];return ru(e,function(e,t){n(t,e)&&r.push(t)}),r},iu=function(e){return e?9===e.nodeType?e:e.ownerDocument:Ia};eu.fn=eu.prototype={constructor:eu,selector:"",context:null,length:0,init:function(e,t){var n,r,o=this;if(!e)return o;if(e.nodeType)return o.context=o[0]=e,o.length=1,o;if(t&&t.nodeType)o.context=t;else{if(t)return lu(e).attr(t);o.context=t=document}if(Va(e)){if(!(n="<"===(o.selector=e).charAt(0)&&">"===e.charAt(e.length-1)&&3<=e.length?[null,e,null]:Ua.exec(e)))return lu(t).find(e);if(n[1])for(r=qa(e,iu(t)).firstChild;r;)Ma.call(o,r),r=r.nextSibling;else{if(!(r=iu(t).getElementById(n[2])))return o;if(r.id!==n[2])return o.find(e);o.length=1,o[0]=r}}else this.add(e,!1);return o},toArray:function(){return xt.toArray(this)},add:function(e,t){var n,r;if(Va(e))return this.add(lu(e));if(!1!==t)for(n=lu.unique(this.toArray().concat(lu.makeArray(e))),this.length=n.length,r=0;r<n.length;r++)this[r]=n[r];else Ma.apply(this,lu.makeArray(e));return this},attr:function(t,n){var e,r=this;if("object"==typeof t)ru(t,function(e,t){r.attr(e,t)});else{if(!Ha(n)){if(r[0]&&1===r[0].nodeType){if((e=Qa[t])&&e.get)return e.get(r[0],t);if(Ya[t])return r.prop(t)?t:undefined;null===(n=r[0].getAttribute(t,2))&&(n=undefined)}return n}this.each(function(){var e;if(1===this.nodeType){if((e=Qa[t])&&e.set)return void e.set(this,n);null===n?this.removeAttribute(t,2):this.setAttribute(t,n,2)}})}return r},removeAttr:function(e){return this.attr(e,null)},prop:function(e,t){var n=this;if("object"==typeof(e=Ga[e]||e))ru(e,function(e,t){n.prop(e,t)});else{if(!Ha(t))return n[0]&&n[0].nodeType&&e in n[0]?n[0][e]:t;this.each(function(){1===this.nodeType&&(this[e]=t)})}return n},css:function(n,r){var e,o,i=this,t=function(e){return e.replace(/-(\D)/g,function(e,t){return t.toUpperCase()})},a=function(e){return e.replace(/[A-Z]/g,function(e){return"-"+e})};if("object"==typeof n)ru(n,function(e,t){i.css(e,t)});else if(Ha(r))n=t(n),"number"!=typeof r||Xa[n]||(r=r.toString()+"px"),i.each(function(){var e=this.style;if((o=Za[n])&&o.set)o.set(this,r);else{try{this.style[Ja[n]||n]=r}catch(t){}null!==r&&""!==r||(e.removeProperty?e.removeProperty(a(n)):e.removeAttribute(n))}});else{if(e=i[0],(o=Za[n])&&o.get)return o.get(e);if(!e.ownerDocument.defaultView)return e.currentStyle?e.currentStyle[t(n)]:"";try{return e.ownerDocument.defaultView.getComputedStyle(e,null).getPropertyValue(a(n))}catch(u){return undefined}}return i},remove:function(){for(var e,t=this.length;t--;)e=this[t],za.clean(e),e.parentNode&&e.parentNode.removeChild(e);return this},empty:function(){for(var e,t=this.length;t--;)for(e=this[t];e.firstChild;)e.removeChild(e.firstChild);return this},html:function(e){var t;if(Ha(e)){t=this.length;try{for(;t--;)this[t].innerHTML=e}catch(n){lu(this[t]).empty().append(e)}return this}return this[0]?this[0].innerHTML:""},text:function(e){var t;if(Ha(e)){for(t=this.length;t--;)"innerText"in this[t]?this[t].innerText=e:this[0].textContent=e;return this}return this[0]?this[0].innerText||this[0].textContent:""},append:function(){return $a(this,arguments,function(e){(1===this.nodeType||this.host&&1===this.host.nodeType)&&this.appendChild(e)})},prepend:function(){return $a(this,arguments,function(e){(1===this.nodeType||this.host&&1===this.host.nodeType)&&this.insertBefore(e,this.firstChild)},!0)},before:function(){return this[0]&&this[0].parentNode?$a(this,arguments,function(e){this.parentNode.insertBefore(e,this)}):this},after:function(){return this[0]&&this[0].parentNode?$a(this,arguments,function(e){this.parentNode.insertBefore(e,this.nextSibling)},!0):this},appendTo:function(e){return lu(e).append(this),this},prependTo:function(e){return lu(e).prepend(this),this},replaceWith:function(e){return this.before(e).remove()},wrap:function(e){return Ka(this,e)},wrapAll:function(e){return Ka(this,e,!0)},wrapInner:function(e){return this.each(function(){lu(this).contents().wrapAll(e)}),this},unwrap:function(){return this.parent().each(function(){lu(this).replaceWith(this.childNodes)})},clone:function(){var e=[];return this.each(function(){e.push(this.cloneNode(!0))}),lu(e)},addClass:function(e){return this.toggleClass(e,!0)},removeClass:function(e){return this.toggleClass(e,!1)},toggleClass:function(o,i){var e=this;return"string"!=typeof o||(-1!==o.indexOf(" ")?ru(o.split(" "),function(){e.toggleClass(this,i)}):e.each(function(e,t){var n,r=Wa(t,o);r!==i&&(n=t.className,r?t.className=nu((" "+n+" ").replace(" "+o+" "," ")):t.className+=n?" "+o:o)})),e},hasClass:function(e){return Wa(this[0],e)},each:function(e){return ru(this,e)},on:function(e,t){return this.each(function(){za.bind(this,e,t)})},off:function(e,t){return this.each(function(){za.unbind(this,e,t)})},trigger:function(e){return this.each(function(){"object"==typeof e?za.fire(this,e.type,e):za.fire(this,e)})},show:function(){return this.css("display","")},hide:function(){return this.css("display","none")},slice:function(){return new lu(Fa.apply(this,arguments))},eq:function(e){return-1===e?this.slice(e):this.slice(e,+e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},find:function(e){for(var t=[],n=0,r=this.length;n<r;n++)lu.find(e,this[n],t);return lu(t)},filter:function(n){return lu("function"==typeof n?ou(this.toArray(),function(e,t){return n(t,e)}):lu.filter(n,this.toArray()))},closest:function(n){var r=[];return n instanceof lu&&(n=n[0]),this.each(function(e,t){for(;t;){if("string"==typeof n&&lu(t).is(n)){r.push(t);break}if(t===n){r.push(t);break}t=t.parentNode}}),lu(r)},offset:function(e){var t,n,r,o,i=0,a=0;return e?this.css(e):((t=this[0])&&(r=(n=t.ownerDocument).documentElement,t.getBoundingClientRect&&(i=(o=t.getBoundingClientRect()).left+(r.scrollLeft||n.body.scrollLeft)-r.clientLeft,a=o.top+(r.scrollTop||n.body.scrollTop)-r.clientTop)),{left:i,top:a})},push:Ma,sort:Array.prototype.sort,splice:Array.prototype.splice},xt.extend(eu,{extend:xt.extend,makeArray:function(e){return(t=e)&&t===t.window||e.nodeType?[e]:xt.toArray(e);var t},inArray:function(e,t){var n;if(t.indexOf)return t.indexOf(e);for(n=t.length;n--;)if(t[n]===e)return n;return-1},isArray:xt.isArray,each:ru,trim:nu,grep:ou,find:Na,expr:Na.selectors,unique:Na.uniqueSort,text:Na.getText,contains:Na.contains,filter:function(e,t,n){var r=t.length;for(n&&(e=":not("+e+")");r--;)1!==t[r].nodeType&&t.splice(r,1);return t=1===t.length?lu.find.matchesSelector(t[0],e)?[t[0]]:[]:lu.find.matches(e,t)}});var au=function(e,t,n){var r=[],o=e[t];for("string"!=typeof n&&n instanceof lu&&(n=n[0]);o&&9!==o.nodeType;){if(n!==undefined){if(o===n)break;if("string"==typeof n&&lu(o).is(n))break}1===o.nodeType&&r.push(o),o=o[t]}return r},uu=function(e,t,n,r){var o=[];for(r instanceof lu&&(r=r[0]);e;e=e[t])if(!n||e.nodeType===n){if(r!==undefined){if(e===r)break;if("string"==typeof r&&lu(e).is(r))break}o.push(e)}return o},su=function(e,t,n){for(e=e[t];e;e=e[t])if(e.nodeType===n)return e;return null};ru({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return au(e,"parentNode")},next:function(e){return su(e,"nextSibling",1)},prev:function(e){return su(e,"previousSibling",1)},children:function(e){return uu(e.firstChild,"nextSibling",1)},contents:function(e){return xt.toArray(("iframe"===e.nodeName?e.contentDocument||e.contentWindow.document:e).childNodes)}},function(r,o){eu.fn[r]=function(t){var n=[];this.each(function(){var e=o.call(n,this,t,n);e&&(lu.isArray(e)?n.push.apply(n,e):n.push(e))}),1<this.length&&(ja[r]||(n=lu.unique(n)),0===r.indexOf("parents")&&(n=n.reverse()));var e=lu(n);return t?e.filter(t):e}}),ru({parentsUntil:function(e,t){return au(e,"parentNode",t)},nextUntil:function(e,t){return uu(e,"nextSibling",1,t).slice(1)},prevUntil:function(e,t){return uu(e,"previousSibling",1,t).slice(1)}},function(o,i){eu.fn[o]=function(t,e){var n=[];this.each(function(){var e=i.call(n,this,t,n);e&&(lu.isArray(e)?n.push.apply(n,e):n.push(e))}),1<this.length&&(n=lu.unique(n),0!==o.indexOf("parents")&&"prevUntil"!==o||(n=n.reverse()));var r=lu(n);return e?r.filter(e):r}}),eu.fn.is=function(e){return!!e&&0<this.filter(e).length},eu.fn.init.prototype=eu.fn,eu.overrideDefaults=function(n){var r,o=function(e,t){return r=r||n(),0===arguments.length&&(e=r.element),t=t||r.context,new o.fn.init(e,t)};return lu.extend(o,this),o},eu.attrHooks=Qa,eu.cssHooks=Za;var cu,lu=eu,fu=xt.each,du=xt.grep,mu=vt.ie,pu=/^([a-z0-9],?)+$/i,gu=function(n,r,o){var i=r.keep_values,e={set:function(e,t,n){r.url_converter&&(t=r.url_converter.call(r.url_converter_scope||o(),t,n,e[0])),e.attr("data-mce-"+n,t).attr(n,t)},get:function(e,t){return e.attr("data-mce-"+t)||e.attr(t)}},t={style:{set:function(e,t){null===t||"object"!=typeof t?(i&&e.attr("data-mce-style",t),null!==t&&"string"==typeof t?(e.removeAttr("style"),e.css(n.parse(t))):e.attr("style",t)):e.css(t)},get:function(e){var t=e.attr("data-mce-style")||e.attr("style");return t=n.serialize(n.parse(t),e[0].nodeName)}}};return i&&(t.href=t.src=e),t},hu=function(e,t){var n=t.attr("style"),r=(r=e.serialize(e.parse(n),t[0].nodeName))||null;t.attr("data-mce-style",r)},vu=function(e,t){var n,r,o=0;if(e)for(n=e.nodeType,e=e.previousSibling;e;e=e.previousSibling)r=e.nodeType,(!t||3!==r||r!==n&&e.nodeValue.length)&&(o++,n=r);return o};function yu(a,u){var s=this;void 0===u&&(u={});var r={},c=window,n={},t=0,o=jr.forElement(Nt.fromDom(a),{contentCssCors:u.contentCssCors,referrerPolicy:u.referrerPolicy}),l=[],f=u.schema?u.schema:pi({}),i=hi({url_converter:u.url_converter,url_converter_scope:u.url_converter_scope},u.schema),d=u.ownEvents?new Ni:Ni.Event,m=f.getBlockElements(),p=lu.overrideDefaults(function(){return{context:a,element:j.getRoot()}}),g=function(e){return e&&a&&q(e)?a.getElementById(e):e},h=function(e){return p("string"==typeof e?g(e):e)},v=function(e,t,n){var r,o,i=h(e);return i.length&&(o=(r=H[t])&&r.get?r.get(i,t):i.attr(t)),void 0===o&&(o=n||""),o},y=function(e){var t=g(e);return t?t.attributes:[]},b=function(e,t,n){""===n&&(n=null);var r,o=h(e),i=o.attr(t);o.length&&((r=H[t])&&r.set?r.set(o,n,t):o.attr(t,n),i!==n&&u.onSetAttrib&&u.onSetAttrib({attrElm:o,attrName:t,attrValue:n}))},C=function(){return u.root_element||a.body},w=function(e,t){return nr(a.body,g(e),t)},x=function(e,t,n){var r=h(e);return n?r.css(t):("float"===(t=t.replace(/-(\D)/g,function(e,t){return t.toUpperCase()}))&&(t=vt.browser.isIE()?"styleFloat":"cssFloat"),r[0]&&r[0].style?r[0].style[t]:undefined)},S=function(e){var t,n;return e=g(e),t=x(e,"width"),n=x(e,"height"),-1===t.indexOf("px")&&(t=0),-1===n.indexOf("px")&&(n=0),{w:parseInt(t,10)||e.offsetWidth||e.clientWidth,h:parseInt(n,10)||e.offsetHeight||e.clientHeight}},N=function(e,t){if(!e)return!1;if(!Array.isArray(e)){if("*"===t)return 1===e.nodeType;if(pu.test(t)){for(var n=t.toLowerCase().split(/,/),r=e.nodeName.toLowerCase(),o=n.length-1;0<=o;o--)if(n[o]===r)return!0;return!1}if(e.nodeType&&1!==e.nodeType)return!1}var i=Array.isArray(e)?e:[e];return 0<Na(t,i[0].ownerDocument||i[0],null,i).length},E=function(e,t,n,r){var o,i=[],a=g(e);for(r=r===undefined,n=n||("BODY"!==C().nodeName?C().parentNode:null),xt.is(t,"string")&&(t="*"===(o=t)?function(e){return 1===e.nodeType}:function(e){return N(e,o)});a&&a!==n&&a.nodeType&&9!==a.nodeType;){if(!t||"function"==typeof t&&t(a)){if(!r)return[a];i.push(a)}a=a.parentNode}return r?i:null},k=function(e,t,n){var r=t;if(e)for("string"==typeof t&&(r=function(e){return N(e,t)}),e=e[n];e;e=e[n])if("function"==typeof r&&r(e))return e;return null},_=function(e,n,r){var o,t="string"==typeof e?g(e):e;if(!t)return!1;if(xt.isArray(t)&&(t.length||0===t.length))return o=[],fu(t,function(e,t){e&&o.push(n.call(r,"string"==typeof e?g(e):e,t))}),o;var i=r||s;return n.call(i,t)},R=function(e,t){h(e).each(function(e,n){fu(t,function(e,t){b(n,t,e)})})},T=function(e,r){var t=h(e);mu?t.each(function(e,t){if(!1!==t.canHaveHTML){for(;t.firstChild;)t.removeChild(t.firstChild);try{t.innerHTML="<br>"+r,t.removeChild(t.firstChild)}catch(n){lu("<div></div>").html("<br>"+r).contents().slice(1).appendTo(t)}return r}}):t.html(r)},A=function(e,n,r,o,i){return _(e,function(e){var t="string"==typeof n?a.createElement(n):n;return R(t,r),o&&("string"!=typeof o&&o.nodeType?t.appendChild(o):"string"==typeof o&&T(t,o)),i?t:e.appendChild(t)})},D=function(e,t,n){return A(a.createElement(e),e,t,n,!0)},e=ri.decode,O=ri.encodeAllRaw,B=function(e,t){var n=h(e);return t?n.each(function(){for(var e;e=this.firstChild;)3===e.nodeType&&0===e.data.length?this.removeChild(e):this.parentNode.insertBefore(e,this)}).remove():n.remove(),1<n.length?n.toArray():n[0]},P=function(e,t,n){h(e).toggleClass(t,n).each(function(){""===this.className&&lu(this).attr("class",null)})},L=function(t,e,n){return _(e,function(e){return xt.is(e,"array")&&(t=t.cloneNode(!0)),n&&fu(du(e.childNodes),function(e){t.appendChild(e)}),e.parentNode.replaceChild(t,e)})},I=function(e){if(Nn(e)){var t="a"===e.nodeName.toLowerCase()&&!v(e,"href")&&v(e,"id");if(v(e,"name")||v(e,"data-mce-bookmark")||t)return!0}return!1},M=function(){return a.createRange()},F=function(e,t,n,r){if(xt.isArray(e)){for(var o=e.length,i=[];o--;)i[o]=F(e[o],t,n,r);return i}return!u.collect||e!==a&&e!==c||l.push([e,t,n,r]),d.bind(e,t,n,r||j)},U=function(e,t,n){if(xt.isArray(e)){for(var r=e.length,o=[];r--;)o[r]=U(e[r],t,n);return o}if(0<l.length&&(e===a||e===c))for(r=l.length;r--;){var i=l[r];e!==i[0]||t&&t!==i[1]||n&&n!==i[2]||d.unbind(i[0],i[1],i[2])}return d.unbind(e,t,n)},z=function(e){if(e&&Nn(e)){var t=e.getAttribute("data-mce-contenteditable");return t&&"inherit"!==t?t:"inherit"!==e.contentEditable?e.contentEditable:null}return null},j={doc:a,settings:u,win:c,files:n,stdMode:!0,boxModel:!0,styleSheetLoader:o,boundEvents:l,styles:i,schema:f,events:d,isBlock:function(e){if("string"==typeof e)return!!m[e];if(e){var t=e.nodeType;if(t)return!(1!==t||!m[e.nodeName])}return!1},$:p,$$:h,root:null,clone:function(t,e){if(!mu||1!==t.nodeType||e)return t.cloneNode(e);var n=a.createElement(t.nodeName);return fu(y(t),function(e){b(n,e.nodeName,v(t,e.nodeName))}),n},getRoot:C,getViewPort:function(e){var t=wn(e);return{x:t.x,y:t.y,w:t.width,h:t.height}},getRect:function(e){e=g(e);var t=w(e),n=S(e);return{x:t.x,y:t.y,w:n.w,h:n.h}},getSize:S,getParent:function(e,t,n){var r=E(e,t,n,!1);return r&&0<r.length?r[0]:null},getParents:E,get:g,getNext:function(e,t){return k(e,t,"nextSibling")},getPrev:function(e,t){return k(e,t,"previousSibling")},select:function(e,t){return Na(e,g(t)||u.root_element||a,[])},is:N,add:A,create:D,createHTML:function(e,t,n){var r,o="";for(r in o+="<"+e,t)t.hasOwnProperty(r)&&null!==t[r]&&"undefined"!=typeof t[r]&&(o+=" "+r+'="'+O(t[r])+'"');return void 0!==n?o+">"+n+"</"+e+">":o+" />"},createFragment:function(e){var t,n=a.createElement("div"),r=a.createDocumentFragment();for(r.appendChild(n),e&&(n.innerHTML=e);t=n.firstChild;)r.appendChild(t);return r.removeChild(n),r},remove:B,setStyle:function(e,t,n){var r=q(t)?h(e).css(t,n):h(e).css(t);u.update_styles&&hu(i,r)},getStyle:x,setStyles:function(e,t){var n=h(e).css(t);u.update_styles&&hu(i,n)},removeAllAttribs:function(e){return _(e,function(e){for(var t=e.attributes,n=t.length-1;0<=n;n--)e.removeAttributeNode(t.item(n))})},setAttrib:b,setAttribs:R,getAttrib:v,getPos:w,parseStyle:function(e){return i.parse(e)},serializeStyle:function(e,t){return i.serialize(e,t)},addStyle:function(e){var t,n;if(j!==yu.DOM&&a===document){if(r[e])return;r[e]=!0}(n=a.getElementById("mceDefaultStyles"))||((n=a.createElement("style")).id="mceDefaultStyles",n.type="text/css",(t=a.getElementsByTagName("head")[0]).firstChild?t.insertBefore(n,t.firstChild):t.appendChild(n)),n.styleSheet?n.styleSheet.cssText+=e:n.appendChild(a.createTextNode(e))},loadCSS:function(e){$((e=e||"").split(","),function(e){n[e]=!0,o.load(e,V)})},addClass:function(e,t){h(e).addClass(t)},removeClass:function(e,t){P(e,t,!1)},hasClass:function(e,t){return h(e).hasClass(t)},toggleClass:P,show:function(e){h(e).show()},hide:function(e){h(e).hide()},isHidden:function(e){return"none"===h(e).css("display")},uniqueId:function(e){return(e||"mce_")+t++},setHTML:T,getOuterHTML:function(e){var t="string"==typeof e?g(e):e;return Nn(t)?t.outerHTML:lu("<div></div>").append(lu(t).clone()).html()},setOuterHTML:function(e,t){h(e).each(function(){try{if("outerHTML"in this)return void(this.outerHTML=t)}catch(e){}B(lu(this).html(t),!0)})},decode:e,encode:O,insertAfter:function(e,t){var r=g(t);return _(e,function(e){var t=r.parentNode,n=r.nextSibling;return n?t.insertBefore(e,n):t.appendChild(e),e})},replace:L,rename:function(t,e){var n;return t.nodeName!==e.toUpperCase()&&(n=D(e),fu(y(t),function(e){b(n,e.nodeName,v(t,e.nodeName))}),L(n,t,!0)),n||t},findCommonAncestor:function(e,t){for(var n,r=e;r;){for(n=t;n&&r!==n;)n=n.parentNode;if(r===n)break;r=r.parentNode}return!r&&e.ownerDocument?e.ownerDocument.documentElement:r},toHex:function(e){return i.toHex(xt.trim(e))},run:_,getAttribs:y,isEmpty:function(e,t){var n,r,o=0;if(I(e))return!1;if(e=e.firstChild){var i=new Hr(e,e.parentNode),a=f?f.getWhiteSpaceElements():{};t=t||(f?f.getNonEmptyElements():null);do{if(n=e.nodeType,Nn(e)){var u=e.getAttribute("data-mce-bogus");if(u){e=i.next("all"===u);continue}if(r=e.nodeName.toLowerCase(),t&&t[r]){if("br"!==r)return!1;o++,e=i.next();continue}if(I(e))return!1}if(8===n)return!1;if(3===n&&!Bo(e.nodeValue))return!1;if(3===n&&e.parentNode&&a[e.parentNode.nodeName]&&Bo(e.nodeValue))return!1;e=i.next()}while(e)}return o<=1},createRng:M,nodeIndex:vu,split:function(e,t,n){var r,o,i,a=M();if(e&&t)return a.setStart(e.parentNode,vu(e)),a.setEnd(t.parentNode,vu(t)),r=a.extractContents(),(a=M()).setStart(t.parentNode,vu(t)+1),a.setEnd(e.parentNode,vu(e)+1),o=a.extractContents(),(i=e.parentNode).insertBefore(Vo(j,r),e),n?i.insertBefore(n,e):i.insertBefore(t,e),i.insertBefore(Vo(j,o),e),B(e),n||t},bind:F,unbind:U,fire:function(e,t,n){return d.fire(e,t,n)},getContentEditable:z,getContentEditableParent:function(e){for(var t=C(),n=null;e&&e!==t&&null===(n=z(e));e=e.parentNode);return n},destroy:function(){if(0<l.length)for(var e=l.length;e--;){var t=l[e];d.unbind(t[0],t[1],t[2])}oe(n,function(e,t){o.unload(t),delete n[t]}),Na.setDocument&&Na.setDocument()},isChildOf:function(e,t){for(;e;){if(t===e)return!0;e=e.parentNode}return!1},dumpRng:function(e){return"startContainer: "+e.startContainer.nodeName+", startOffset: "+e.startOffset+", endContainer: "+e.endContainer.nodeName+", endOffset: "+e.endOffset}},H=gu(i,u,function(){return j});return j}(cu=yu=yu||{}).DOM=cu(document),cu.nodeIndex=vu;var bu=yu,Cu=bu.DOM,wu=xt.each,xu=xt.grep,Su=(Nu.prototype._setReferrerPolicy=function(e){this.settings.referrerPolicy=e},Nu.prototype.loadScript=function(e,t,n){var r=Cu,o=r.uniqueId(),i=document.createElement("script");i.id=o,i.type="text/javascript",i.src=xt._addCacheSuffix(e),this.settings.referrerPolicy&&r.setAttrib(i,"referrerpolicy",this.settings.referrerPolicy),i.onload=function(){r.remove(o),i&&(i.onreadystatechange=i.onload=i=null),t()},i.onerror=function(){A(n)?n():"undefined"!=typeof console&&console.log&&console.log("Failed to load script: "+e)},(document.getElementsByTagName("head")[0]||document.body).appendChild(i)},Nu.prototype.isDone=function(e){return 2===this.states[e]},Nu.prototype.markDone=function(e){this.states[e]=2},Nu.prototype.add=function(e,t,n,r){this.states[e]===undefined&&(this.queue.push(e),this.states[e]=0),t&&(this.scriptLoadedCallbacks[e]||(this.scriptLoadedCallbacks[e]=[]),this.scriptLoadedCallbacks[e].push({success:t,failure:r,scope:n||this}))},Nu.prototype.load=function(e,t,n,r){return this.add(e,t,n,r)},Nu.prototype.remove=function(e){delete this.states[e],delete this.scriptLoadedCallbacks[e]},Nu.prototype.loadQueue=function(e,t,n){this.loadScripts(this.queue,e,t,n)},Nu.prototype.loadScripts=function(n,e,t,r){var o=this,i=[],a=function(t,e){wu(o.scriptLoadedCallbacks[e],function(e){A(e[t])&&e[t].call(e.scope)}),o.scriptLoadedCallbacks[e]=undefined};o.queueLoadedCallbacks.push({success:e,failure:r,scope:t||this});var u=function(){var e,t=xu(n);n.length=0,wu(t,function(e){2!==o.states[e]?3!==o.states[e]?1!==o.states[e]&&(o.states[e]=1,o.loading++,o.loadScript(e,function(){o.states[e]=2,o.loading--,a("success",e),u()},function(){o.states[e]=3,o.loading--,i.push(e),a("failure",e),u()})):a("failure",e):a("success",e)}),o.loading||(e=o.queueLoadedCallbacks.slice(0),o.queueLoadedCallbacks.length=0,wu(e,function(e){0===i.length?A(e.success)&&e.success.call(e.scope):A(e.failure)&&e.failure.call(e.scope,i)}))};u()},Nu.ScriptLoader=new Nu,Nu);function Nu(e){void 0===e&&(e={}),this.states={},this.queue=[],this.scriptLoadedCallbacks={},this.queueLoadedCallbacks=[],this.loading=0,this.settings=e}var Eu,ku=function(e){var t=e;return{get:function(){return t},set:function(e){t=e}}},_u={},Ru=ku("en"),Tu=function(){return de(_u,Ru.get())},Au={getData:function(){return ie(_u,function(e){return xe({},e)})},setCode:function(e){e&&Ru.set(e)},getCode:function(){return Ru.get()},add:function(e,t){var n=_u[e];n||(_u[e]=n={}),oe(t,function(e,t){n[t.toLowerCase()]=e})},translate:function(e){var t,n,r=Tu().getOr({}),o=function(e){return A(e)?Object.prototype.toString.call(e):i(e)?"":""+e},i=function(e){return""===e||null===e||e===undefined},a=function(e){var t=o(e);return de(r,t.toLowerCase()).map(o).getOr(t)},u=function(e){return e.replace(/{context:\w+}$/,"")};if(i(e))return"";if(_(t=e)&&me(t,"raw"))return o(e.raw);if(S(n=e)&&1<n.length){var s=e.slice(1);return u(a(e[0]).replace(/\{([0-9]+)\}/g,function(e,t){return me(s,t)?o(s[t]):e}))}return u(a(e))},isRtl:function(){return Tu().bind(function(e){return de(e,"_dir")}).exists(function(e){return"rtl"===e})},hasCode:function(e){return me(_u,e)}};function Du(){var r=this,o=[],s={},c={},i=[],l=function(t,n){var e=j(i,function(e){return e.name===t&&e.state===n});$(e,function(e){return e.callback()})},f=function(e){var t;return c[e]&&(t=c[e].dependencies),t||[]},d=function(e,t){return"object"==typeof t?t:"string"==typeof e?{prefix:"",resource:t,suffix:""}:{prefix:e.prefix,resource:t,suffix:e.suffix}},m=function(o,i,a,u,e){var t,n;s[o]||(0!==(t="string"==typeof i?i:i.prefix+i.resource+i.suffix).indexOf("/")&&-1===t.indexOf("://")&&(t=Du.baseURL+"/"+t),s[o]=t.substring(0,t.lastIndexOf("/")),n=function(){var n,e,t,r;l(o,"loaded"),n=i,e=a,t=u,r=f(o),$(r,function(e){var t=d(n,e);m(t.resource,t,undefined,undefined)}),e&&(t?e.call(t):e.call(Su))},c[o]?n():Su.ScriptLoader.add(t,n,u,e))},e=function(e,t,n){void 0===n&&(n="added"),me(c,e)&&"added"===n||me(s,e)&&"loaded"===n?t():i.push({name:e,state:n,callback:t})};return{items:o,urls:s,lookup:c,_listeners:i,get:function(e){return c[e]?c[e].instance:undefined},dependencies:f,requireLangPack:function(t,n){!1!==Du.languageLoad&&e(t,function(){var e=Au.getCode();!e||n&&-1===(","+(n||"")+",").indexOf(","+e+",")||Su.ScriptLoader.add(s[t]+"/langs/"+e+".js")},"loaded")},add:function(e,t,n){var r=t;return o.push(r),c[e]={instance:r,dependencies:n},l(e,"added"),r},remove:function(e){delete s[e],delete c[e]},createUrl:d,addComponents:function(e,t){var n=r.urls[e];$(t,function(e){Su.ScriptLoader.add(n+"/"+e)})},load:m,waitFor:e}}(Eu=Du=Du||{}).PluginManager=Eu(),Eu.ThemeManager=Eu();var Ou,Bu=Du,Pu=function(n,r){var o=null;return{cancel:function(){null!==o&&(clearTimeout(o),o=null)},throttle:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];null===o&&(o=setTimeout(function(){n.apply(null,e),o=null},r))}}},Lu=function(n,r){var o=null;return{cancel:function(){null!==o&&(clearTimeout(o),o=null)},throttle:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];null!==o&&clearTimeout(o),o=setTimeout(function(){n.apply(null,e),o=null},r)}}},Iu=function(e,t){var n=Wn(e,t);return n===undefined||""===n?[]:n.split(" ")},Mu=function(e){return e.dom.classList!==undefined},Fu=function(e,t){return o=t,i=Iu(n=e,r="class").concat([o]),qn(n,r,i.join(" ")),!0;var n,r,o,i},Uu=function(e,t){return o=t,0<(i=j(Iu(n=e,r="class"),function(e){return e!==o})).length?qn(n,r,i.join(" ")):Kn(n,r),!1;var n,r,o,i},zu=function(e,t){Mu(e)?e.dom.classList.add(t):Fu(e,t)},ju=function(e){0===(Mu(e)?e.dom.classList:Iu(e,"class")).length&&Kn(e,"class")},Hu=function(e,t){return Mu(e)&&e.dom.classList.contains(t)},Vu=function(e,t){var n=[];return $(Wt(e),function(e){t(e)&&(n=n.concat([e])),n=n.concat(Vu(e,t))}),n},qu=function(e,t){return n=t,o=(r=e)===undefined?document:r.dom,_t(o)?[]:F(o.querySelectorAll(n),Nt.fromDom);var n,r,o},$u=N("mce-annotation"),Wu=N("data-mce-annotation"),Ku=N("data-mce-annotation-uid"),Xu=function(r,e){var t=r.selection.getRng(),n=Nt.fromDom(t.startContainer),o=Nt.fromDom(r.getBody()),i=e.fold(function(){return"."+$u()},function(e){return"["+Wu()+'="'+e+'"]'}),a=Kt(n,t.startOffset).getOr(n),u=kr(a,i,function(e){return Rt(e,o)}),s=function(e,t){return n=t,(r=e.dom)&&r.hasAttribute&&r.hasAttribute(n)?U.some(Wn(e,t)):U.none();var n,r};return u.bind(function(e){return s(e,""+Ku()).bind(function(n){return s(e,""+Wu()).map(function(e){var t=Yu(r,n);return{uid:n,name:e,elements:t}})})})},Yu=function(e,t){var n=Nt.fromDom(e.getBody());return qu(n,"["+Ku()+'="'+t+'"]')},Gu=function(i,e){var a=ku({}),c=function(e,t){u(e,function(e){return t(e),e})},u=function(e,t){var n=a.get(),r=t(n.hasOwnProperty(e)?n[e]:{listeners:[],previous:ku(U.none())});n[e]=r,a.set(n)},t=Lu(function(){var e,t,n,r=a.get(),o=(e=ne(r),(n=O.call(e,0)).sort(t),n);$(o,function(e){u(e,function(u){var s=u.previous.get();return Xu(i,U.some(e)).fold(function(){var t;s.isSome()&&(c(t=e,function(e){$(e.listeners,function(e){return e(!1,t)})}),u.previous.set(U.none()))},function(e){var t,n,r,o=e.uid,i=e.name,a=e.elements;s.is(o)||(n=o,r=a,c(t=i,function(e){$(e.listeners,function(e){return e(!0,t,{uid:n,nodes:F(r,function(e){return e.dom})})})}),u.previous.set(U.some(o)))}),{previous:u.previous,listeners:u.listeners}})})},30);i.on("remove",function(){t.cancel()}),i.on("NodeChange",function(){t.throttle()});return{addListener:function(e,t){u(e,function(e){return{previous:e.previous,listeners:e.listeners.concat([t])}})}}},Ju=function(e,n){e.on("init",function(){e.serializer.addNodeFilter("span",function(e){$(e,function(t){var e;e=t,U.from(e.attr(Wu())).bind(n.lookup).each(function(e){!1===e.persistent&&t.unwrap()})})})})},Qu=0,Zu=function(e){var t=(new Date).getTime();return e+"_"+Math.floor(1e9*Math.random())+ ++Qu+String(t)},es=function(e,t){var n,r,o=Ft(e).dom,i=Nt.fromDom(o.createDocumentFragment()),a=(n=t,(r=(o||document).createElement("div")).innerHTML=n,Wt(Nt.fromDom(r)));sn(i,a),cn(e),un(e,i)},ts=function(e,t){return Nt.fromDom(e.dom.cloneNode(t))},ns=function(e){return ts(e,!1)},rs=function(e){return ts(e,!0)},os=function(e,t,n){void 0===n&&(n=p);var r=new Hr(e,t),o=function(e){for(var t;(t=r[e]())&&!On(t)&&!n(t););return U.from(t).filter(On)};return{current:function(){return U.from(r.current()).filter(On)},next:function(){return o("next")},prev:function(){return o("prev")},prev2:function(){return o("prev2")}}},is=function(t,e){var i=e||function(e){return t.isBlock(e)||In(e)||Un(e)},a=function(e,t,n,r){if(On(e)){var o=r(e,t,e.data);if(-1!==o)return U.some({container:e,offset:o})}return n().bind(function(e){return a(e.container,e.offset,n,r)})};return{backwards:function(e,t,n,r){var o=os(e,r,i);return a(e,t,function(){return o.prev().map(function(e){return{container:e,offset:e.length}})},n).getOrNull()},forwards:function(e,t,n,r){var o=os(e,r,i);return a(e,t,function(){return o.next().map(function(e){return{container:e,offset:0}})},n).getOrNull()}}},as=function(e,t,n){return e.isSome()&&t.isSome()?U.some(n(e.getOrDie(),t.getOrDie())):U.none()},us=Math.round,ss=function(e){return e?{left:us(e.left),top:us(e.top),bottom:us(e.bottom),right:us(e.right),width:us(e.width),height:us(e.height)}:{left:0,top:0,bottom:0,right:0,width:0,height:0}},cs=function(e,t){return e=ss(e),t||(e.left=e.left+e.width),e.right=e.left,e.width=0,e},ls=function(e,t,n){return 0<=e&&e<=Math.min(t.height,n.height)/2},fs=function(e,t){var n=Math.min(t.height/2,e.height/2);return e.bottom-n<t.top||!(e.top>t.bottom)&&ls(t.top-e.bottom,e,t)},ds=function(e,t){return e.top>t.bottom||!(e.bottom<t.top)&&ls(t.bottom-e.top,e,t)},ms=function(e,t,n){return t>=e.left&&t<=e.right&&n>=e.top&&n<=e.bottom},ps=function(e){var t=e.startContainer,n=e.startOffset;return t.hasChildNodes()&&e.endOffset===n+1?t.childNodes[n]:null},gs=function(e,t){return 1===e.nodeType&&e.hasChildNodes()&&(t>=e.childNodes.length&&(t=e.childNodes.length-1),e=e.childNodes[t]),e},hs=new RegExp("[\u0300-\u036f\u0483-\u0487\u0488-\u0489\u0591-\u05bd\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7\u0610-\u061a\u064b-\u065f\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7-\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e3-\u0902\u093a\u093c\u0941-\u0948\u094d\u0951-\u0957\u0962-\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2-\u09e3\u0a01-\u0a02\u0a3c\u0a41-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a51\u0a70-\u0a71\u0a75\u0a81-\u0a82\u0abc\u0ac1-\u0ac5\u0ac7-\u0ac8\u0acd\u0ae2-\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62-\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c00\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56\u0c62-\u0c63\u0c81\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc-\u0ccd\u0cd5-\u0cd6\u0ce2-\u0ce3\u0d01\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62-\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb-\u0ebc\u0ec8-\u0ecd\u0f18-\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039-\u103a\u103d-\u103e\u1058-\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085-\u1086\u108d\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752-\u1753\u1772-\u1773\u17b4-\u17b5\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927-\u1928\u1932\u1939-\u193b\u1a17-\u1a18\u1a1b\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1ab0-\u1abd\u1abe\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80-\u1b81\u1ba2-\u1ba5\u1ba8-\u1ba9\u1bab-\u1bad\u1be6\u1be8-\u1be9\u1bed\u1bef-\u1bf1\u1c2c-\u1c33\u1c36-\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1cf4\u1cf8-\u1cf9\u1dc0-\u1df5\u1dfc-\u1dff\u200c-\u200d\u20d0-\u20dc\u20dd-\u20e0\u20e1\u20e2-\u20e4\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302d\u302e-\u302f\u3099-\u309a\ua66f\ua670-\ua672\ua674-\ua67d\ua69e-\ua69f\ua6f0-\ua6f1\ua802\ua806\ua80b\ua825-\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\ua9e5\uaa29-\uaa2e\uaa31-\uaa32\uaa35-\uaa36\uaa43\uaa4c\uaa7c\uaab0\uaab2-\uaab4\uaab7-\uaab8\uaabe-\uaabf\uaac1\uaaec-\uaaed\uaaf6\uabe5\uabe8\uabed\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\uff9e-\uff9f]"),vs=function(e){return"string"==typeof e&&768<=e.charCodeAt(0)&&hs.test(e)},ys=Nn,bs=To,Cs=kn("display","block table"),ws=kn("float","left right"),xs=function(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];return function(e){for(var t=0;t<n.length;t++)if(!n[t](e))return!1;return!0}}(ys,bs,d(ws)),Ss=d(kn("white-space","pre pre-line pre-wrap")),Ns=On,Es=In,ks=bu.nodeIndex,_s=gs,Rs=function(e){return"createRange"in e?e.createRange():bu.DOM.createRng()},Ts=function(e){return e&&/[\r\n\t ]/.test(e)},As=function(e){return!!e.setStart&&!!e.setEnd},Ds=function(e){var t,n=e.startContainer,r=e.startOffset;return!!(Ts(e.toString())&&Ss(n.parentNode)&&On(n)&&(t=n.data,Ts(t[r-1])||Ts(t[r+1])))},Os=function(e){return 0===e.left&&0===e.right&&0===e.top&&0===e.bottom},Bs=function(e){var t=e.getClientRects(),n=0<t.length?ss(t[0]):ss(e.getBoundingClientRect());return!As(e)&&Es(e)&&Os(n)?function(e){var t=e.ownerDocument,n=Rs(t),r=t.createTextNode(oo),o=e.parentNode;o.insertBefore(r,e),n.setStart(r,0),n.setEnd(r,1);var i=ss(n.getBoundingClientRect());return o.removeChild(r),i}(e):Os(n)&&As(e)?function(e){var t=e.startContainer,n=e.endContainer,r=e.startOffset,o=e.endOffset;if(t===n&&On(n)&&0===r&&1===o){var i=e.cloneRange();return i.setEndAfter(n),Bs(i)}return null}(e):n},Ps=function(e,t){var n=cs(e,t);return n.width=1,n.right=n.left+1,n},Ls=function(e){var t,n,r=[],o=function(e){var t,n;0!==e.height&&(0<r.length&&(t=e,n=r[r.length-1],t.left===n.left&&t.top===n.top&&t.bottom===n.bottom&&t.right===n.right)||r.push(e))},i=function(e,t){var n=Rs(e.ownerDocument);if(t<e.data.length){if(vs(e.data[t]))return r;if(vs(e.data[t-1])&&(n.setStart(e,t),n.setEnd(e,t+1),!Ds(n)))return o(Ps(Bs(n),!1)),r}0<t&&(n.setStart(e,t-1),n.setEnd(e,t),Ds(n)||o(Ps(Bs(n),!1))),t<e.data.length&&(n.setStart(e,t),n.setEnd(e,t+1),Ds(n)||o(Ps(Bs(n),!0)))};if(Ns(e.container()))return i(e.container(),e.offset()),r;if(ys(e.container()))if(e.isAtEnd())n=_s(e.container(),e.offset()),Ns(n)&&i(n,n.data.length),xs(n)&&!Es(n)&&o(Ps(Bs(n),!1));else{if(n=_s(e.container(),e.offset()),Ns(n)&&i(n,0),xs(n)&&e.isAtEnd())return o(Ps(Bs(n),!1)),r;t=_s(e.container(),e.offset()-1),xs(t)&&!Es(t)&&(!Cs(t)&&!Cs(n)&&xs(n)||o(Ps(Bs(t),!1))),xs(n)&&o(Ps(Bs(n),!0))}return r};function Is(t,n,e){var r=function(){return e=e||Ls(Is(t,n))};return{container:N(t),offset:N(n),toRange:function(){var e=Rs(t.ownerDocument);return e.setStart(t,n),e.setEnd(t,n),e},getClientRects:r,isVisible:function(){return 0<r().length},isAtStart:function(){return Ns(t),0===n},isAtEnd:function(){return Ns(t)?n>=t.data.length:n>=t.childNodes.length},isEqual:function(e){return e&&t===e.container()&&n===e.offset()},getNode:function(e){return _s(t,e?n-1:n)}}}(Ou=Is=Is||{}).fromRangeStart=function(e){return Ou(e.startContainer,e.startOffset)},Ou.fromRangeEnd=function(e){return Ou(e.endContainer,e.endOffset)},Ou.after=function(e){return Ou(e.parentNode,ks(e)+1)},Ou.before=function(e){return Ou(e.parentNode,ks(e))},Ou.isAbove=function(e,t){return as(Z(t.getClientRects()),ee(e.getClientRects()),fs).getOr(!1)},Ou.isBelow=function(e,t){return as(ee(t.getClientRects()),Z(e.getClientRects()),ds).getOr(!1)},Ou.isAtStart=function(e){return!!e&&e.isAtStart()},Ou.isAtEnd=function(e){return!!e&&e.isAtEnd()},Ou.isTextPosition=function(e){return!!e&&On(e.container())},Ou.isElementPosition=function(e){return!1===Ou.isTextPosition(e)};var Ms,Fs,Us=Is,zs=function(e,t){On(t)&&0===t.data.length&&e.remove(t)},js=function(e,t,n){var r,o,i,a,u,s,c;Ln(n)?(i=e,a=t,u=n,s=U.from(u.firstChild),c=U.from(u.lastChild),a.insertNode(u),s.each(function(e){return zs(i,e.previousSibling)}),c.each(function(e){return zs(i,e.nextSibling)})):(r=e,o=n,t.insertNode(o),zs(r,o.previousSibling),zs(r,o.nextSibling))},Hs=On,Vs=Rn,qs=bu.nodeIndex,$s=function(e){var t=e.parentNode;return Vs(t)?$s(t):t},Ws=function(e){return e?be(e.childNodes,function(e,t){return Vs(t)&&"BR"!==t.nodeName?e=e.concat(Ws(t)):e.push(t),e},[]):[]},Ks=function(t){return function(e){return t===e}},Xs=function(e){var t=Hs(e)?"text()":e.nodeName.toLowerCase();return t+"["+function(e){var r=Ws($s(e)),t=Ce(r,Ks(e),e);r=r.slice(0,t+1);var n=be(r,function(e,t,n){return Hs(t)&&Hs(r[n-1])&&e++,e},0);return r=ve(r,En([e.nodeName])),(t=Ce(r,Ks(e),e))-n}(e)+"]"},Ys=function(e,t){var n,r,o,i=[],a=t.container(),u=t.offset();return Hs(a)?n=function(e,t){for(;(e=e.previousSibling)&&Hs(e);)t+=e.data.length;return t}(a,u):(u>=(r=a.childNodes).length?(n="after",u=r.length-1):n="before",a=r[u]),i.push(Xs(a)),o=function(e,t,n){var r=[];for(t=t.parentNode;t!==e&&(!n||!n(t));t=t.parentNode)r.push(t);return r}(e,a),o=ve(o,d(Rn)),(i=i.concat(he(o,Xs))).reverse().join("/")+","+n},Gs=function(e,t){if(!t)return null;var n=t.split(","),r=n[0].split("/"),o=1<n.length?n[1]:"before",i=be(r,function(e,t){var n,r,o,i,a=/([\w\-\(\)]+)\[([0-9]+)\]/.exec(t);return a?("text()"===a[1]&&(a[1]="#text"),n=e,r=a[1],o=parseInt(a[2],10),i=Ws(n),i=ve(i,function(e,t){return!Hs(e)||!Hs(i[t-1])}),(i=ve(i,En([r])))[o]):null},e);return i?Hs(i)?function(e,t){for(var n,r=e,o=0;Hs(r);){if(n=r.data.length,o<=t&&t<=o+n){e=r,t-=o;break}if(!Hs(r.nextSibling)){e=r,t=n;break}o+=n,r=r.nextSibling}return Hs(e)&&t>e.data.length&&(t=e.data.length),Us(e,t)}(i,parseInt(o,10)):(o="after"===o?qs(i)+1:qs(i),Us(i.parentNode,o)):null},Js=Un,Qs=function(e,t,n,r,o){var i,a=r[o?"startContainer":"endContainer"],u=r[o?"startOffset":"endOffset"],s=[],c=0,l=e.getRoot();for(On(a)?s.push(n?function(e,t,n){for(var r=e(t.data.slice(0,n)).length,o=t.previousSibling;o&&On(o);o=o.previousSibling)r+=e(o.data).length;return r}(t,a,u):u):(u>=(i=a.childNodes).length&&i.length&&(c=1,u=Math.max(0,i.length-1)),s.push(e.nodeIndex(i[u],n)+c));a&&a!==l;a=a.parentNode)s.push(e.nodeIndex(a,n));return s},Zs=function(e,t,n){var r=0;return xt.each(e.select(t),function(e){if("all"!==e.getAttribute("data-mce-bogus"))return e!==n&&void r++}),r},ec=function(e,t){var n,r=t?"start":"end",o=e[r+"Container"],i=e[r+"Offset"];Nn(o)&&"TR"===o.nodeName&&(o=(n=o.childNodes)[Math.min(t?i:i-1,n.length-1)])&&(i=t?0:o.childNodes.length,e["set"+(t?"Start":"End")](o,i))},tc=function(e){return ec(e,!0),ec(e,!1),e},nc=function(e,t){var n;if(Nn(e)&&(e=gs(e,t),Js(e)))return e;if(mo(e)){if(On(e)&&lo(e)&&(e=e.parentNode),n=e.previousSibling,Js(n))return n;if(n=e.nextSibling,Js(n))return n}},rc=function(e,t,n){var r=n.getNode(),o=r?r.nodeName:null,i=n.getRng();if(Js(r)||"IMG"===o)return{name:o,index:Zs(n.dom,o,r)};var a,u,s,c,l,f,d,m=nc((a=i).startContainer,a.startOffset)||nc(a.endContainer,a.endOffset);return m?{name:o=m.tagName,index:Zs(n.dom,o,m)}:(u=e,c=t,l=i,f=(s=n).dom,(d={}).start=Qs(f,u,c,l,!0),s.isCollapsed()||(d.end=Qs(f,u,c,l,!1)),d)},oc=function(e,t,n){var r={"data-mce-type":"bookmark",id:t,style:"overflow:hidden;line-height:0px"};return n?e.create("span",r,"&#xFEFF;"):e.create("span",r)},ic=function(e,t){var n=e.dom,r=e.getRng(),o=n.uniqueId(),i=e.isCollapsed(),a=e.getNode(),u=a.nodeName;if("IMG"===u)return{name:u,index:Zs(n,u,a)};var s,c=tc(r.cloneRange());i||(c.collapse(!1),s=oc(n,o+"_end",t),js(n,c,s)),(r=tc(r)).collapse(!0);var l=oc(n,o+"_start",t);return js(n,r,l),e.moveToBookmark({id:o,keep:!0}),{id:o}},ac=function(e,t,n){return 2===t?rc(uo,n,e):3===t?(o=(r=e).getRng(),{start:Ys(r.dom.getRoot(),Us.fromRangeStart(o)),end:Ys(r.dom.getRoot(),Us.fromRangeEnd(o))}):t?{rng:e.getRng()}:ic(e,!1);var r,o},uc=E(rc,o,!0),sc=bu.DOM,cc=function(e,t,n){var r=e.getParam(t,n);if(-1===r.indexOf("="))return r;var o=e.getParam(t,"","hash");return o.hasOwnProperty(e.id)?o[e.id]:n},lc=function(e){return e.getParam("content_security_policy","")},fc=function(e){if(e.getParam("force_p_newlines",!1))return"p";var t=e.getParam("forced_root_block","p");return!1===t?"":!0===t?"p":t},dc=function(e){return e.getParam("forced_root_block_attrs",{})},mc=function(e){return e.getParam("automatic_uploads",!0,"boolean")},pc=function(e){return e.getParam("icons","","string")},gc=function(e){return e.getParam("referrer_policy","","string")},hc=function(e){return e.getParam("language","en","string")},vc=function(e){return e.getParam("indent_use_margin",!1)},yc=function(e){var t=e.getParam("object_resizing");return!1!==t&&!vt.iOS&&(q(t)?t:"table,img,figure.image,div")},bc=function(e){return e.getParam("event_root")},Cc=function(e){return e.getParam("theme")},wc=function(e){return!1!==e.getParam("inline_boundaries")},xc=function(e){return e.getParam("plugins","","string")},Sc=Nn,Nc=On,Ec=function(e){var t=e.parentNode;t&&t.removeChild(e)},kc=function(e){var t=uo(e);return{count:e.length-t.length,text:t}},_c=function(e){for(var t;-1!==(t=e.data.lastIndexOf(io));)e.deleteData(t,1)},Rc=function(e,t){return Oc(e),t},Tc=function(e,t){var n,r,o=t.container(),i=(n=te(o.childNodes),(-1===(r=L(n,e))?U.none():U.some(r)).map(function(e){return e<t.offset()?Us(o,t.offset()-1):t}).getOr(t));return Oc(e),i},Ac=function(e,t){return Nc(e)&&t.container()===e?(r=t,o=kc((n=e).data.substr(0,r.offset())),i=kc(n.data.substr(r.offset())),0<(o.text+i.text).length?(_c(n),Us(n,r.offset()-o.count)):r):Rc(e,t);var n,r,o,i},Dc=function(e,t){return Us.isTextPosition(t)?Ac(e,t):(n=e,((r=t).container()===n.parentNode?Tc:Rc)(n,r));var n,r},Oc=function(e){Sc(e)&&mo(e)&&(po(e)?e.removeAttribute("data-mce-caret"):Ec(e)),Nc(e)&&(_c(e),0===e.data.length&&Ec(e))},Bc=st().browser,Pc=Un,Lc=jn,Ic=zn,Mc=function(e,t,n){var r,o,i,a,u=cs(t.getBoundingClientRect(),n),s="BODY"===e.tagName?(r=e.ownerDocument.documentElement,o=e.scrollLeft||r.scrollLeft,e.scrollTop||r.scrollTop):(a=e.getBoundingClientRect(),o=e.scrollLeft-a.left,e.scrollTop-a.top);return u.left+=o,u.right+=o,u.top+=s,u.bottom+=s,u.width=1,0<(i=t.offsetWidth-t.clientWidth)&&(n&&(i*=-1),u.left+=i,u.right+=i),u},Fc=function(e,i,a,t){var n,u,s=ku(U.none()),r=fc(e),c=0<r.length?r:"p",l=function(){!function(e){for(var t=qu(Nt.fromDom(e),"*[contentEditable=false],video,audio,embed,object"),n=0;n<t.length;n++){var r,o=t[n].dom,i=o.previousSibling;bo(i)&&(1===(r=i.data).length?i.parentNode.removeChild(i):i.deleteData(r.length-1,1)),i=o.nextSibling,yo(i)&&(1===(r=i.data).length?i.parentNode.removeChild(i):i.deleteData(0,1))}}(i),u&&(Oc(u),u=null),s.get().each(function(e){lu(e.caret).remove(),s.set(U.none())}),n&&(Fr.clearInterval(n),n=null)},f=function(){n=Fr.setInterval(function(){t()?lu("div.mce-visual-caret",i).toggleClass("mce-visual-caret-hidden"):lu("div.mce-visual-caret",i).addClass("mce-visual-caret-hidden")},500)};return{show:function(t,e){var n,r;if(l(),Ic(e))return null;if(!a(e))return u=function(e,t){var n,r=e.ownerDocument.createTextNode(io),o=e.parentNode;if(t){if(n=e.previousSibling,co(n)){if(mo(n))return n;if(bo(n))return n.splitText(n.data.length-1)}o.insertBefore(r,e)}else{if(n=e.nextSibling,co(n)){if(mo(n))return n;if(yo(n))return n.splitText(1),n}e.nextSibling?o.insertBefore(r,e.nextSibling):o.appendChild(r)}return r}(e,t),r=e.ownerDocument.createRange(),zc(u.nextSibling)?(r.setStart(u,0),r.setEnd(u,0)):(r.setStart(u,1),r.setEnd(u,1)),r;u=vo(c,e,t),n=Mc(i,e,t),lu(u).css("top",n.top);var o=lu('<div class="mce-visual-caret" data-mce-bogus="all"></div>').css(n).appendTo(i)[0];return s.set(U.some({caret:o,element:e,before:t})),s.get().each(function(e){t&&lu(e.caret).addClass("mce-visual-caret-before")}),f(),(r=e.ownerDocument.createRange()).setStart(u,0),r.setEnd(u,0),r},hide:l,getCss:function(){return".mce-visual-caret {position: absolute;background-color: black;background-color: currentcolor;}.mce-visual-caret-hidden {display: none;}*[data-mce-caret] {position: absolute;left: -1000px;right: auto;top: 0;margin: 0;padding: 0;}"},reposition:function(){s.get().each(function(e){var t=Mc(i,e.element,e.before);lu(e.caret).css(xe({},t))})},destroy:function(){return Fr.clearInterval(n)}}},Uc=function(){return Bc.isIE()||Bc.isEdge()||Bc.isFirefox()},zc=function(e){return Pc(e)||Lc(e)},jc=function(e){return zc(e)||Tn(e)&&Uc()},Hc=Un,Vc=jn,qc=kn("display","block table table-cell table-caption list-item"),$c=mo,Wc=lo,Kc=Nn,Xc=To,Yc=function(e,t){for(var n;n=e(t);)if(!Wc(n))return n;return null},Gc=function(e,t,n,r,o){var i=new Hr(e,r),a=Hc(e)||Wc(e);if(t<0){if(a&&n(e=Yc(i.prev,!0)))return e;for(;e=Yc(i.prev,o);)if(n(e))return e}if(0<t){if(a&&n(e=Yc(i.next,!0)))return e;for(;e=Yc(i.next,o);)if(n(e))return e}return null},Jc=function(e,t){for(;e&&e!==t;){if(qc(e))return e;e=e.parentNode}return null},Qc=function(e,t,n){return Jc(e.container(),n)===Jc(t.container(),n)},Zc=function(e,t){if(!t)return null;var n=t.container(),r=t.offset();return Kc(n)?n.childNodes[r+e]:null},el=function(e,t){var n=t.ownerDocument.createRange();return e?(n.setStartBefore(t),n.setEndBefore(t)):(n.setStartAfter(t),n.setEndAfter(t)),n},tl=function(e,t,n){for(var r,o,i,a=e?"previousSibling":"nextSibling";n&&n!==t;){if(r=n[a],$c(r)&&(r=r[a]),Hc(r)||Vc(r)){if(i=n,Jc(r,o=t)===Jc(i,o))return r;break}if(Xc(r))break;n=n.parentNode}return null},nl=E(el,!0),rl=E(el,!1),ol=function(e,t,n){var r,o,i=E(tl,!0,t),a=E(tl,!1,t),u=n.startContainer,s=n.startOffset;if(lo(u)){if(Kc(u)||(u=u.parentNode),"before"===(o=u.getAttribute("data-mce-caret"))&&(r=u.nextSibling,jc(r)))return nl(r);if("after"===o&&(r=u.previousSibling,jc(r)))return rl(r)}if(!n.collapsed)return n;if(On(u)){if($c(u)){if(1===e){if(r=a(u))return nl(r);if(r=i(u))return rl(r)}if(-1===e){if(r=i(u))return rl(r);if(r=a(u))return nl(r)}return n}if(bo(u)&&s>=u.data.length-1)return 1===e&&(r=a(u))?nl(r):n;if(yo(u)&&s<=1)return-1===e&&(r=i(u))?rl(r):n;if(s===u.data.length)return(r=a(u))?nl(r):n;if(0===s)return(r=i(u))?rl(r):n}return n},il=function(e,t){return U.from(Zc(e?0:-1,t)).filter(Hc)},al=function(e,t,n){var r=ol(e,t,n);return-1===e?Is.fromRangeStart(r):Is.fromRangeEnd(r)},ul=function(e){return U.from(e.getNode()).map(Nt.fromDom)},sl=function(e,t){for(;t=e(t);)if(t.isVisible())return t;return t},cl=function(e,t){var n=Qc(e,t);return!(n||!In(e.getNode()))||n};(Fs=Ms=Ms||{})[Fs.Backwards=-1]="Backwards",Fs[Fs.Forwards=1]="Forwards";var ll,fl=Un,dl=On,ml=Nn,pl=In,gl=To,hl=function(e){return ko(e)||!!Ao(t=e)&&!0!==W(te(t.getElementsByTagName("*")),function(e,t){return e||wo(t)},!1);var t},vl=Do,yl=function(e,t){return e.hasChildNodes()&&t<e.childNodes.length?e.childNodes[t]:null},bl=function(e,t){if(0<e){if(gl(t.previousSibling)&&!dl(t.previousSibling))return Us.before(t);if(dl(t))return Us(t,0)}if(e<0){if(gl(t.nextSibling)&&!dl(t.nextSibling))return Us.after(t);if(dl(t))return Us(t,t.data.length)}return!(e<0)||pl(t)?Us.before(t):Us.after(t)},Cl=function(e,t,n){var r,o,i,a;if(!ml(n)||!t)return null;if(t.isEqual(Us.after(n))&&n.lastChild){if(a=Us.after(n.lastChild),e<0&&gl(n.lastChild)&&ml(n.lastChild))return pl(n.lastChild)?Us.before(n.lastChild):a}else a=t;var u,s,c,l=a.container(),f=a.offset();if(dl(l)){if(e<0&&0<f)return Us(l,--f);if(0<e&&f<l.length)return Us(l,++f);r=l}else{if(e<0&&0<f&&(o=yl(l,f-1),gl(o)))return!hl(o)&&(i=Gc(o,e,vl,o))?dl(i)?Us(i,i.data.length):Us.after(i):dl(o)?Us(o,o.data.length):Us.before(o);if(0<e&&f<l.childNodes.length&&(o=yl(l,f),gl(o)))return pl(o)?(u=n,(c=(s=o).nextSibling)&&gl(c)?dl(c)?Us(c,0):Us.before(c):Cl(Ms.Forwards,Us.after(s),u)):!hl(o)&&(i=Gc(o,e,vl,o))?dl(i)?Us(i,0):Us.before(i):dl(o)?Us(o,0):Us.after(o);r=o||a.getNode()}if((0<e&&a.isAtEnd()||e<0&&a.isAtStart())&&(r=Gc(r,e,k,n,!0),vl(r,n)))return bl(e,r);o=Gc(r,e,vl,n);var d=we(j(function(e,t){for(var n=[];e&&e!==t;)n.push(e),e=e.parentNode;return n}(l,n),fl));return!d||o&&d.contains(o)?o?bl(e,o):null:a=0<e?Us.after(d):Us.before(d)},wl=function(t){return{next:function(e){return Cl(Ms.Forwards,e,t)},prev:function(e){return Cl(Ms.Backwards,e,t)}}},xl=function(e){return Us.isTextPosition(e)?0===e.offset():To(e.getNode())},Sl=function(e){if(Us.isTextPosition(e)){var t=e.container();return e.offset()===t.data.length}return To(e.getNode(!0))},Nl=function(e,t){return!Us.isTextPosition(e)&&!Us.isTextPosition(t)&&e.getNode()===t.getNode(!0)},El=function(e,t,n){return e?!Nl(t,n)&&(r=t,!(!Us.isTextPosition(r)&&In(r.getNode())))&&Sl(t)&&xl(n):!Nl(n,t)&&xl(t)&&Sl(n);var r},kl=function(e,t,n){var r=wl(t);return U.from(e?r.next(n):r.prev(n))},_l=function(t,n,r){return kl(t,n,r).bind(function(e){return Qc(r,e,n)&&El(t,r,e)?kl(t,n,e):U.some(e)})},Rl=function(t,n,e,r){return _l(t,n,e).bind(function(e){return r(e)?Rl(t,n,e,r):U.some(e)})},Tl=function(e,t){var n,r,o,i,a,u=e?t.firstChild:t.lastChild;return On(u)?U.some(Us(u,e?0:u.data.length)):u?To(u)?U.some(e?Us.before(u):In(a=u)?Us.before(a):Us.after(a)):(r=t,o=u,i=(n=e)?Us.before(o):Us.after(o),kl(n,r,i)):U.none()},Al=E(kl,!0),Dl=E(kl,!1),Ol=E(Tl,!0),Bl=E(Tl,!1),Pl="_mce_caret",Ll=function(e){return Nn(e)&&e.id===Pl},Il=function(e,t){for(;t&&t!==e;){if(t.id===Pl)return t;t=t.parentNode}return null},Ml=function(e,t){return Nn(t)&&e.isBlock(t)&&!t.innerHTML&&!vt.ie&&(t.innerHTML='<br data-mce-bogus="1" />'),t},Fl=function(e,t,n){return!(!1!==t.hasChildNodes()||!Il(e,t))&&(o=n,i=(r=t).ownerDocument.createTextNode(io),r.appendChild(i),o.setStart(i,0),o.setEnd(i,0),!0);var r,o,i},Ul=function(e,t,n,r){var o,i,a,u,s=n[t?"start":"end"],c=e.getRoot();if(s){for(a=s[0],i=c,o=s.length-1;1<=o;o--){if(u=i.childNodes,Fl(c,i,r))return!0;if(s[o]>u.length-1)return!!Fl(c,i,r)||function(e,t){return Bl(e).fold(function(){return!1},function(e){return t.setStart(e.container(),e.offset()),t.setEnd(e.container(),e.offset()),!0})}(i,r);i=u[s[o]]}3===i.nodeType&&(a=Math.min(s[0],i.nodeValue.length)),1===i.nodeType&&(a=Math.min(s[0],i.childNodes.length)),t?r.setStart(i,a):r.setEnd(i,a)}return!0},zl=function(e){return On(e)&&0<e.data.length},jl=function(e,t,n){var r,o,i,a,u,s,c=e.get(n.id+"_"+t),l=n.keep;if(c){if(r=c.parentNode,s=(u=(o="start"===t?l?c.hasChildNodes()?(r=c.firstChild,1):zl(c.nextSibling)?(r=c.nextSibling,0):zl(c.previousSibling)?(r=c.previousSibling,c.previousSibling.data.length):(r=c.parentNode,e.nodeIndex(c)+1):e.nodeIndex(c):l?c.hasChildNodes()?(r=c.firstChild,1):zl(c.previousSibling)?(r=c.previousSibling,c.previousSibling.data.length):(r=c.parentNode,e.nodeIndex(c)):e.nodeIndex(c),r),o),!l){for(a=c.previousSibling,i=c.nextSibling,xt.each(xt.grep(c.childNodes),function(e){On(e)&&(e.nodeValue=e.nodeValue.replace(/\uFEFF/g,""))});c=e.get(n.id+"_"+t);)e.remove(c,!0);a&&i&&a.nodeType===i.nodeType&&On(a)&&!vt.opera&&(o=a.nodeValue.length,a.appendData(i.nodeValue),e.remove(i),u=a,s=o)}return U.some(Us(u,s))}return U.none()},Hl=function(e,t){var n,r,o,i,a,u,s,c,l,f,d,m,p,g,h=e.dom;if(t){if(g=t,xt.isArray(g.start))return m=t,p=(d=h).createRng(),Ul(d,!0,m,p)&&Ul(d,!1,m,p)?U.some(p):U.none();if("string"==typeof t.start)return U.some((c=t,l=(s=h).createRng(),f=Gs(s.getRoot(),c.start),l.setStart(f.container(),f.offset()),f=Gs(s.getRoot(),c.end),l.setEnd(f.container(),f.offset()),l));if(t.hasOwnProperty("id"))return a=jl(o=h,"start",i=t),u=jl(o,"end",i),as(a,u.or(a),function(e,t){var n=o.createRng();return n.setStart(Ml(o,e.container()),e.offset()),n.setEnd(Ml(o,t.container()),t.offset()),n});if(t.hasOwnProperty("name"))return n=h,r=t,U.from(n.select(r.name)[r.index]).map(function(e){var t=n.createRng();return t.selectNode(e),t});if(t.hasOwnProperty("rng"))return U.some(t.rng)}return U.none()},Vl=ac,ql=function(t,e){Hl(t,e).each(function(e){t.setRng(e)})},$l=function(e){return Nn(e)&&"SPAN"===e.tagName&&"bookmark"===e.getAttribute("data-mce-type")},Wl=(ll=oo,function(e){return ll===e}),Kl=function(e){return""!==e&&-1!==" \f\n\r\t\x0B".indexOf(e)},Xl=function(e){return!Kl(e)&&!Wl(e)},Yl=function(e){return!!e.nodeType},Gl=function(e,t,n){var r,o,i,a,u=n.startOffset,s=n.startContainer;if((n.startContainer!==n.endContainer||!(a=n.startContainer.childNodes[n.startOffset])||!/^(IMG)$/.test(a.nodeName))&&1===s.nodeType)for(u<(i=s.childNodes).length?(s=i[u],r=new Hr(s,e.getParent(s,e.isBlock))):(s=i[i.length-1],(r=new Hr(s,e.getParent(s,e.isBlock))).next(!0)),o=r.current();o;o=r.next())if(3===o.nodeType&&!ef(o))return n.setStart(o,0),void t.setRng(n)},Jl=function(e,t,n){if(e){var r=t?"nextSibling":"previousSibling";for(e=n?e:e[r];e;e=e[r])if(1===e.nodeType||!ef(e))return e}},Ql=function(e,t){return Yl(t)&&(t=t.nodeName),!!e.schema.getTextBlockElements()[t.toLowerCase()]},Zl=function(e,t,n){return e.schema.isValidChild(t,n)},ef=function(e){return e&&On(e)&&/^([\t \r\n]+|)$/.test(e.nodeValue)},tf=function(e,n){return"string"!=typeof e?e=e(n):n&&(e=e.replace(/%(\w+)/g,function(e,t){return n[t]||e})),e},nf=function(e,t){return e=""+((e=e||"").nodeName||e),t=""+((t=t||"").nodeName||t),e.toLowerCase()===t.toLowerCase()},rf=function(e,t,n){return"color"!==n&&"backgroundColor"!==n||(t=e.toHex(t)),"fontWeight"===n&&700===t&&(t="bold"),"fontFamily"===n&&(t=t.replace(/[\'\"]/g,"").replace(/,\s+/g,",")),""+t},of=function(e,t,n){return rf(e,e.getStyle(t,n),n)},af=function(t,e){var n;return t.getParent(e,function(e){return(n=t.getStyle(e,"text-decoration"))&&"none"!==n}),n},uf=function(e,t,n){return e.getParents(t,n,e.getRoot())},sf=function(t,e,n){var r=["inline","block","selector","attributes","styles","classes"],a=function(e){return le(e,function(e,t){return M(r,function(e){return e===t})})};return M(t.formatter.get(e),function(e){var i=a(e);return M(t.formatter.get(n),function(e){var t,n,r,o=a(e);return t=i,n=o,void 0===r&&(r=l),u(r).eq(t,n)})})},cf=$l,lf=uf,ff=ef,df=Ql,mf=function(e,t){for(var n=t;n;){if(Nn(n)&&e.getContentEditable(n))return"false"===e.getContentEditable(n)?n:t;n=n.parentNode}return t},pf=function(e,t,n,r){for(var o=t.data,i=n;e?0<=i:i<o.length;e?i--:i++)if(r(o.charAt(i)))return e?i+1:i;return-1},gf=function(e,t,n){return pf(e,t,n,function(e){return Wl(e)||Kl(e)})},hf=function(e,t,n){return pf(e,t,n,Xl)},vf=function(i,e,t,n,a,r){var u,s=i.getParent(t,i.isBlock)||e,o=function(e,t,n){var r=is(i),o=a?r.backwards:r.forwards;return U.from(o(e,t,function(e,t){return cf(e.parentNode)?-1:n(a,u=e,t)},s))};return o(t,n,gf).bind(function(e){return r?o(e.container,e.offset+(a?-1:0),hf):U.some(e)}).orThunk(function(){return u?U.some({container:u,offset:a?0:u.length}):U.none()})},yf=function(e,t,n,r,o){On(r)&&0===r.nodeValue.length&&r[o]&&(r=r[o]);for(var i=lf(e,r),a=0;a<i.length;a++)for(var u=0;u<t.length;u++){var s=t[u];if(!("collapsed"in s&&s.collapsed!==n.collapsed)&&e.is(i[a],s.selector))return i[a]}return r},bf=function(t,e,n,r){var o,i,a=t.dom,u=a.getRoot();if(e[0].wrapper||(i=a.getParent(n,e[0].block,u)),i||(o=a.getParent(n,"LI,TD,TH"),i=a.getParent(On(n)?n.parentNode:n,function(e){return e!==u&&df(t,e)},o)),i&&e[0].wrapper&&(i=lf(a,i,"ul,ol").reverse()[0]||i),!i)for(i=n;i[r]&&!a.isBlock(i[r])&&(i=i[r],!nf(i,"br")););return i||n},Cf=function(e,t,n,r,o,i,a){var u,s,c,l=u=a?n:o,f=a?"previousSibling":"nextSibling",d=e.getRoot();if(On(l)&&!ff(l)&&(a?0<r:i<l.nodeValue.length))return l;for(;;){if(!t[0].block_expand&&e.isBlock(u))return u;for(s=u[f];s;s=s[f])if(!cf(s)&&!ff(s)&&("BR"!==(c=s).nodeName||!c.getAttribute("data-mce-bogus")||c.nextSibling))return u;if(u===d||u.parentNode===d){l=u;break}u=u.parentNode}return l},wf=function(e,t,n,r){void 0===r&&(r=!1);var o=t.startContainer,i=t.startOffset,a=t.endContainer,u=t.endOffset,s=e.dom;return Nn(o)&&o.hasChildNodes()&&(o=gs(o,i),On(o)&&(i=0)),Nn(a)&&a.hasChildNodes()&&(a=gs(a,t.collapsed?u:u-1),On(a)&&(u=a.nodeValue.length)),o=mf(s,o),a=mf(s,a),(cf(o.parentNode)||cf(o))&&(o=cf(o)?o:o.parentNode,o=t.collapsed?o.previousSibling||o:o.nextSibling||o,On(o)&&(i=t.collapsed?o.length:0)),(cf(a.parentNode)||cf(a))&&(a=cf(a)?a:a.parentNode,a=t.collapsed?a.nextSibling||a:a.previousSibling||a,On(a)&&(u=t.collapsed?0:a.length)),t.collapsed&&(vf(s,e.getBody(),o,i,!0,r).each(function(e){var t=e.container,n=e.offset;o=t,i=n}),vf(s,e.getBody(),a,u,!1,r).each(function(e){var t=e.container,n=e.offset;a=t,u=n})),(n[0].inline||n[0].block_expand)&&(n[0].inline&&On(o)&&0!==i||(o=Cf(s,n,o,i,a,u,!0)),n[0].inline&&On(a)&&u!==a.nodeValue.length||(a=Cf(s,n,o,i,a,u,!1))),n[0].selector&&!1!==n[0].expand&&!n[0].inline&&(o=yf(s,n,t,o,"previousSibling"),a=yf(s,n,t,a,"nextSibling")),(n[0].block||n[0].selector)&&(o=bf(e,n,o,"previousSibling"),a=bf(e,n,a,"nextSibling"),n[0].block&&(s.isBlock(o)||(o=Cf(s,n,o,i,a,u,!0)),s.isBlock(a)||(a=Cf(s,n,o,i,a,u,!1)))),Nn(o)&&(i=s.nodeIndex(o),o=o.parentNode),Nn(a)&&(u=s.nodeIndex(a)+1,a=a.parentNode),{startContainer:o,startOffset:i,endContainer:a,endOffset:u}},xf=function(e,t){var n=e.childNodes;return t>=n.length?t=n.length-1:t<0&&(t=0),n[t]||e},Sf=function(e,t,u){var n=t.startContainer,r=t.startOffset,o=t.endContainer,i=t.endOffset,s=function(e){var t=e[0];return 3===t.nodeType&&t===n&&r>=t.nodeValue.length&&e.splice(0,1),t=e[e.length-1],0===i&&0<e.length&&t===o&&3===t.nodeType&&e.splice(e.length-1,1),e},c=function(e,t,n){for(var r=[];e&&e!==n;e=e[t])r.push(e);return r},a=function(e,t){do{if(e.parentNode===t)return e;e=e.parentNode}while(e)},l=function(e,t,n){for(var r=n?"nextSibling":"previousSibling",o=e,i=o.parentNode;o&&o!==t;o=i){i=o.parentNode;var a=c(o===e?o:o[r],r);a.length&&(n||a.reverse(),u(s(a)))}};if(1===n.nodeType&&n.hasChildNodes()&&(n=xf(n,r)),1===o.nodeType&&o.hasChildNodes()&&(o=xf(o,i-1)),n===o)return u(s([n]));for(var f=e.findCommonAncestor(n,o),d=n;d;d=d.parentNode){if(d===o)return l(n,f,!0);if(d===f)break}for(d=o;d;d=d.parentNode){if(d===n)return l(o,f);if(d===f)break}var m=a(n,f)||n,p=a(o,f)||o;l(n,m,!0);var g=c(m===n?m:m.nextSibling,"nextSibling",p===o?p.nextSibling:p);g.length&&u(s(g)),l(o,p)},Nf=function(e){var t=[];if(e)for(var n=0;n<e.rangeCount;n++)t.push(e.getRangeAt(n));return t},Ef=function(e){return j(Y(e,function(e){var t=ps(e);return t?[Nt.fromDom(t)]:[]}),to)},kf=function(e,t){var n=qu(t,"td[data-mce-selected],th[data-mce-selected]");return 0<n.length?n:Ef(e)},_f=function(e){return kf(Nf(e.selection.getSel()),Nt.fromDom(e.getBody()))},Rf=function(t){return Xt(t).fold(N([t]),function(e){return[t].concat(Rf(e))})},Tf=function(t){return Yt(t).fold(N([t]),function(e){return"br"===Dt(e)?Ht(e).map(function(e){return[t].concat(Tf(e))}).getOr([]):[t].concat(Tf(e))})},Af=function(o,e){return as((a=(i=e).startContainer,u=i.startOffset,On(a)?0===u?U.some(Nt.fromDom(a)):U.none():U.from(a.childNodes[u]).map(Nt.fromDom)),(n=(t=e).endContainer,r=t.endOffset,On(n)?r===n.data.length?U.some(Nt.fromDom(n)):U.none():U.from(n.childNodes[r-1]).map(Nt.fromDom)),function(e,t){var n=K(Rf(o),E(Rt,e)),r=K(Tf(o),E(Rt,t));return n.isSome()&&r.isSome()}).getOr(!1);var t,n,r,i,a,u},Df=function(e,t,n,r){var o=n,i=new Hr(n,o),a=le(e.schema.getMoveCaretBeforeOnEnterElements(),function(e,t){return!I(["td","th","table"],t.toLowerCase())});do{if(On(n)&&0!==xt.trim(n.nodeValue).length)return void(r?t.setStart(n,0):t.setEnd(n,n.nodeValue.length));if(a[n.nodeName])return void(r?t.setStartBefore(n):"BR"===n.nodeName?t.setEndBefore(n):t.setEndAfter(n))}while(n=r?i.next():i.prev());"BODY"===o.nodeName&&(r?t.setStart(o,0):t.setEnd(o,o.childNodes.length))},Of=function(e){var t=e.selection.getSel();return t&&0<t.rangeCount},Bf=function(r,o){var e=_f(r);0<e.length?$(e,function(e){var t=e.dom,n=r.dom.createRng();n.setStartBefore(t),n.setEndAfter(t),o(n,!0)}):o(r.selection.getRng(),!1)},Pf=function(e,t,n){var r=ic(e,t);n(r),e.moveToBookmark(r)};var Lf,If,Mf,Ff=(Lf=Lt,If="text",{get:function(e){if(!Lf(e))throw new Error("Can only get "+If+" value of a "+If+" node");return Mf(e).getOr("")},getOption:Mf=function(e){return Lf(e)?U.from(e.dom.nodeValue):U.none()},set:function(e,t){if(!Lf(e))throw new Error("Can only set raw "+If+" value of a "+If+" node");e.dom.nodeValue=t}}),Uf=function(e){return Ff.get(e)},zf=function(r,o,i,a){return jt(o).fold(function(){return"skipping"},function(e){return"br"===a||Lt(n=o)&&Uf(n)===io?"valid":Pt(t=o)&&Hu(t,$u())?"existing":Ll(o.dom)?"caret":Zl(r,i,a)&&Zl(r,Dt(e),i)?"valid":"invalid-child";var t,n})},jf=function(e,t,n,r){var o=t.uid,i=void 0===o?Zu("mce-annotation"):o,a=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}(t,["uid"]),u=Nt.fromTag("span",e);zu(u,$u()),qn(u,""+Ku(),i),qn(u,""+Wu(),n);var s,c=r(i,a),l=c.attributes,f=void 0===l?{}:l,d=c.classes,m=void 0===d?[]:d;return $n(u,f),s=u,$(m,function(e){zu(s,e)}),u},Hf=function(i,e,t,n,r){var a=[],u=jf(i.getDoc(),r,t,n),s=ku(U.none()),c=function(){s.set(U.none())},l=function(e){$(e,o)},o=function(e){var t,n;switch(zf(i,e,"span",Dt(e))){case"invalid-child":c();var r=Wt(e);l(r),c();break;case"valid":var o=s.get().getOrThunk(function(){var e=ns(u);return a.push(e),s.set(U.some(e)),e});rn(t=e,n=o),un(n,t)}};return Sf(i.dom,e,function(e){var t;c(),t=F(e,Nt.fromDom),l(t)}),a},Vf=function(u,s,c,l){u.undoManager.transact(function(){var e,t,n,r,o=u.selection,i=o.getRng(),a=0<_f(u).length;i.collapsed&&!a&&(n=wf(e=u,t=i,[{inline:!0}]),t.setStart(n.startContainer,n.startOffset),t.setEnd(n.endContainer,n.endOffset),e.selection.setRng(t)),o.getRng().collapsed&&!a?(r=jf(u.getDoc(),l,s,c.decorate),es(r,oo),o.getRng().insertNode(r.dom),o.select(r.dom)):Pf(o,!1,function(){Bf(u,function(e){Hf(u,e,s,c.decorate,l)})})})},qf=function(u){var n,r=(n={},{register:function(e,t){n[e]={name:e,settings:t}},lookup:function(e){return n.hasOwnProperty(e)?U.from(n[e]).map(function(e){return e.settings}):U.none()}});Ju(u,r);var o=Gu(u);return{register:function(e,t){r.register(e,t)},annotate:function(t,n){r.lookup(t).each(function(e){Vf(u,t,e,n)})},annotationChanged:function(e,t){o.addListener(e,t)},remove:function(e){Xu(u,U.some(e)).each(function(e){var t=e.elements;$(t,fn)})},getAll:function(e){var t,n,r,o,i,a=(t=u,n=e,r=Nt.fromDom(t.getBody()),o=qu(r,"["+Wu()+'="'+n+'"]'),i={},$(o,function(e){var t=Wn(e,Ku()),n=i.hasOwnProperty(t)?i[t]:[];i[t]=n.concat([e])}),i);return ie(a,function(e){return F(e,function(e){return e.dom})})}}};function $f(e){return{getBookmark:E(Vl,e),moveToBookmark:E(ql,e)}}($f=$f||{}).isBookmarkNode=$l;var Wf,Kf=$f,Xf=function(e,t){for(;t&&t!==e;){if(Fn(t)||Un(t))return t;t=t.parentNode}return null},Yf=function(t,n,e){if(e.collapsed)return!1;if(vt.browser.isIE()&&e.startOffset===e.endOffset-1&&e.startContainer===e.endContainer){var r=e.startContainer.childNodes[e.startOffset];if(Nn(r))return M(r.getClientRects(),function(e){return ms(e,t,n)})}return M(e.getClientRects(),function(e){return ms(e,t,n)})},Gf={BACKSPACE:8,DELETE:46,DOWN:40,ENTER:13,LEFT:37,RIGHT:39,SPACEBAR:32,TAB:9,UP:38,END:35,HOME:36,modifierPressed:function(e){return e.shiftKey||e.ctrlKey||e.altKey||this.metaKeyPressed(e)},metaKeyPressed:function(e){return vt.mac?e.metaKey:e.ctrlKey&&!e.altKey}},Jf=Un,Qf=function(r,l){var f,d,m,p,g,h,v,y,b,C,w,x,S,N,E=l.dom,s=xt.each,c=l.getDoc(),k=document,_=Math.abs,R=Math.round,T=l.getBody(),A={nw:[0,0,-1,-1],ne:[1,0,1,-1],se:[1,1,1,1],sw:[0,1,-1,1]},D=function(e){return e&&("IMG"===e.nodeName||l.dom.is(e,"figure.image"))},n=function(e){var t=e.target;!function(e,t){if("longpress"!==e.type&&0!==e.type.indexOf("touch"))return D(e.target)&&!Yf(e.clientX,e.clientY,t);var n=e.touches[0];return D(e.target)&&!Yf(n.clientX,n.clientY,t)}(e,l.selection.getRng())||e.isDefaultPrevented()||l.selection.select(t)},O=function(e){return l.dom.is(e,"figure.image")?e.querySelector("img"):e},B=function(e){var t=yc(l);return!!t&&("false"!==e.getAttribute("data-mce-resize")&&(e!==l.getBody()&&kt(Nt.fromDom(e),t)))},P=function(e,t,n){E.setStyles(O(e),{width:t,height:n})},L=function(e){var t,n,r,o,i,a,u,s=e.screenX-g,c=e.screenY-h;w=s*p[2]+v,x=c*p[3]+y,w=w<5?5:w,x=x<5?5:x,(D(f)&&!1!==l.getParam("resize_img_proportional",!0,"boolean")?!Gf.modifierPressed(e):Gf.modifierPressed(e))&&(_(s)>_(c)?(x=R(w*b),w=R(x/b)):(w=R(x/b),x=R(w*b))),P(d,w,x),t=0<(t=p.startPos.x+s)?t:0,n=0<(n=p.startPos.y+c)?n:0,E.setStyles(m,{left:t,top:n,display:"block"}),m.innerHTML=w+" &times; "+x,p[2]<0&&d.clientWidth<=w&&E.setStyle(d,"left",void 0+(v-w)),p[3]<0&&d.clientHeight<=x&&E.setStyle(d,"top",void 0+(y-x)),(s=T.scrollWidth-S)+(c=T.scrollHeight-N)!==0&&E.setStyles(m,{left:t-s,top:n-c}),C||(r=l,o=f,i=v,a=y,u="corner-"+p.name,r.fire("ObjectResizeStart",{target:o,width:i,height:a,origin:u}),C=!0)},I=function(){var e=C;C=!1;var t,n,r,o,i,a=function(e,t){t&&(f.style[e]||!l.schema.isValid(f.nodeName.toLowerCase(),e)?E.setStyle(O(f),e,t):E.setAttrib(O(f),e,""+t))};e&&(a("width",w),a("height",x)),E.unbind(c,"mousemove",L),E.unbind(c,"mouseup",I),k!==c&&(E.unbind(k,"mousemove",L),E.unbind(k,"mouseup",I)),E.remove(d),E.remove(m),u(f),e&&(t=l,n=f,r=w,o=x,i="corner-"+p.name,t.fire("ObjectResized",{target:n,width:r,height:o,origin:i}),E.setAttrib(f,"style",E.getAttrib(f,"style"))),l.nodeChanged()},u=function(e){M(),F();var t=E.getPos(e,T),o=t.x,i=t.y,n=e.getBoundingClientRect(),a=n.width||n.right-n.left,u=n.height||n.bottom-n.top;f!==e&&(f=e,w=x=0);var r=l.fire("ObjectSelected",{target:e});B(e)&&!r.isDefaultPrevented()?s(A,function(n,r){var e=E.get("mceResizeHandle"+r);e&&E.remove(e),e=E.add(T,"div",{id:"mceResizeHandle"+r,"data-mce-bogus":"all","class":"mce-resizehandle",unselectable:!0,style:"cursor:"+r+"-resize; margin:0; padding:0"}),11===vt.ie&&(e.contentEditable=!1),E.bind(e,"mousedown",function(e){var t;e.stopImmediatePropagation(),e.preventDefault(),g=(t=e).screenX,h=t.screenY,v=O(f).clientWidth,y=O(f).clientHeight,b=y/v,(p=n).name=r,p.startPos={x:a*n[0]+o,y:u*n[1]+i},S=T.scrollWidth,N=T.scrollHeight,d=f.cloneNode(!0),E.addClass(d,"mce-clonedresizable"),E.setAttrib(d,"data-mce-bogus","all"),d.contentEditable=!1,d.unSelectabe=!0,E.setStyles(d,{left:o,top:i,margin:0}),P(d,a,u),d.removeAttribute("data-mce-selected"),T.appendChild(d),E.bind(c,"mousemove",L),E.bind(c,"mouseup",I),k!==c&&(E.bind(k,"mousemove",L),E.bind(k,"mouseup",I)),m=E.add(T,"div",{"class":"mce-resize-helper","data-mce-bogus":"all"},v+" &times; "+y)}),n.elm=e,E.setStyles(e,{left:a*n[0]+o-e.offsetWidth/2,top:u*n[1]+i-e.offsetHeight/2})}):M(),f.setAttribute("data-mce-selected","1")},M=function(){F(),f&&f.removeAttribute("data-mce-selected"),oe(A,function(e,t){var n=E.get("mceResizeHandle"+t);n&&(E.unbind(n),E.remove(n))})},o=function(e){var t,n=function(e,t){if(e)do{if(e===t)return!0}while(e=e.parentNode)};C||l.removed||(s(E.select("img[data-mce-selected],hr[data-mce-selected]"),function(e){e.removeAttribute("data-mce-selected")}),t="mousedown"===e.type?e.target:r.getNode(),n(t=E.$(t).closest("table,img,figure.image,hr")[0],T)&&(a(),n(r.getStart(!0),t)&&n(r.getEnd(!0),t))?u(t):M())},i=function(e){return Jf(Xf(l.getBody(),e))},F=function(){oe(A,function(e){e.elm&&(E.unbind(e.elm),delete e.elm)})},a=function(){try{l.getDoc().execCommand("enableObjectResizing",!1,"false")}catch(e){}};l.on("init",function(){var e;a(),(vt.browser.isIE()||vt.browser.isEdge())&&(l.on("mousedown click",function(e){var t=e.target,n=t.nodeName;C||!/^(TABLE|IMG|HR)$/.test(n)||i(t)||(2!==e.button&&l.selection.select(t,"TABLE"===n),"mousedown"===e.type&&l.nodeChanged())}),e=function(e){var t=function(e){Fr.setEditorTimeout(l,function(){return l.selection.select(e)})};if(i(e.target)||jn(e.target))return e.preventDefault(),void t(e.target);/^(TABLE|IMG|HR)$/.test(e.target.nodeName)&&(e.preventDefault(),"IMG"===e.target.tagName&&t(e.target))},E.bind(T,"mscontrolselect",e),l.on("remove",function(){return E.unbind(T,"mscontrolselect",e)}));var t=Fr.throttle(function(e){l.composing||o(e)});l.on("nodechange ResizeEditor ResizeWindow ResizeContent drop FullscreenStateChanged",t),l.on("keyup compositionend",function(e){f&&"TABLE"===f.nodeName&&t(e)}),l.on("hide blur",M),l.on("contextmenu longpress",n,!0)}),l.on("remove",F);return{isResizable:B,showResizeRect:u,hideResizeRect:M,updateResizeRect:o,destroy:function(){f=d=null}}},Zf=function(e){return Fn(e)||Un(e)},ed=function(e,t,n){var r,o,i,a,u,s=n;if(s.caretPositionFromPoint)(o=s.caretPositionFromPoint(e,t))&&((r=n.createRange()).setStart(o.offsetNode,o.offset),r.collapse(!0));else if(n.caretRangeFromPoint)r=n.caretRangeFromPoint(e,t);else if(s.body.createTextRange){r=s.body.createTextRange();try{r.moveToPoint(e,t),r.collapse(!0)}catch(c){r=function(e,n,t){var r,o=t.elementFromPoint(e,n),i=t.body.createTextRange();if(o&&"HTML"!==o.tagName||(o=t.body),i.moveToElementText(o),0<(r=(r=xt.toArray(i.getClientRects())).sort(function(e,t){return(e=Math.abs(Math.max(e.top-n,e.bottom-n)))-(t=Math.abs(Math.max(t.top-n,t.bottom-n)))})).length){n=(r[0].bottom+r[0].top)/2;try{return i.moveToPoint(e,n),i.collapse(!0),i}catch(a){}}return null}(e,t,n)}return i=r,a=n.body,u=i&&i.parentElement?i.parentElement():null,Un(function(e,t,n){for(;e&&e!==t;){if(n(e))return e;e=e.parentNode}return null}(u,a,Zf))?null:i}return r},td=function(e,t){return e&&t&&e.startContainer===t.startContainer&&e.startOffset===t.startOffset&&e.endContainer===t.endContainer&&e.endOffset===t.endOffset},nd=function(e,t,n){return null!==function(e,t,n){for(;e&&e!==t;){if(n(e))return e;e=e.parentNode}return null}(e,t,n)},rd=function(e){return e&&"TABLE"===e.nodeName},od=function(e,t,n){for(var r=new Hr(t,e.getParent(t.parentNode,e.isBlock)||e.getRoot());t=r[n?"prev":"next"]();)if(In(t))return!0},id=function(e,t,n,r,o){var i,a,u=e.getRoot(),s=e.schema.getNonEmptyElements(),c=e.getParent(o.parentNode,e.isBlock)||u;if(r&&In(o)&&t&&e.isEmpty(c))return U.some(Is(o.parentNode,e.nodeIndex(o)));for(var l,f,d=new Hr(o,c);a=d[r?"prev":"next"]();){if("false"===e.getContentEditableParent(a)||(f=u,mo(l=a)&&!1===nd(l,f,Ll)))return U.none();if(On(a)&&0<a.nodeValue.length)return!1===function(e,t,n){return nd(e,t,function(e){return e.nodeName===n})}(a,u,"A")?U.some(Is(a,r?a.nodeValue.length:0)):U.none();if(e.isBlock(a)||s[a.nodeName.toLowerCase()])return U.none();i=a}return n&&i?U.some(Is(i,0)):U.none()},ad=function(e,t,n,r){var o,i,a,u,s=e.getRoot(),c=!1,l=r[(n?"start":"end")+"Container"],f=r[(n?"start":"end")+"Offset"],d=Nn(l)&&f===l.childNodes.length,m=e.schema.getNonEmptyElements(),p=n;if(mo(l))return U.none();if(Nn(l)&&f>l.childNodes.length-1&&(p=!1),Pn(l)&&(l=s,f=0),l===s){if(p&&(o=l.childNodes[0<f?f-1:0])){if(mo(o))return U.none();if(m[o.nodeName]||rd(o))return U.none()}if(l.hasChildNodes()){if(f=Math.min(!p&&0<f?f-1:f,l.childNodes.length-1),l=l.childNodes[f],f=On(l)&&d?l.data.length:0,!t&&l===s.lastChild&&rd(l))return U.none();if(function(e,t){for(;t&&t!==e;){if(Un(t))return!0;t=t.parentNode}return!1}(s,l)||mo(l))return U.none();if(l.hasChildNodes()&&!1===rd(l)){var g=new Hr(o=l,s);do{if(Un(o)||mo(o)){c=!1;break}if(On(o)&&0<o.nodeValue.length){f=p?0:o.nodeValue.length,l=o,c=!0;break}if(m[o.nodeName.toLowerCase()]&&(!(i=o)||!/^(TD|TH|CAPTION)$/.test(i.nodeName))){f=e.nodeIndex(o),l=o.parentNode,p||f++,c=!0;break}}while(o=p?g.next():g.prev())}}}return t&&(On(l)&&0===f&&id(e,d,t,!0,l).each(function(e){l=e.container(),f=e.offset(),c=!0}),Nn(l)&&(!(o=(o=l.childNodes[f])||l.childNodes[f-1])||!In(o)||(u="A",(a=o).previousSibling&&a.previousSibling.nodeName===u)||od(e,o,!1)||od(e,o,!0)||id(e,d,t,!0,o).each(function(e){l=e.container(),f=e.offset(),c=!0}))),p&&!t&&On(l)&&f===l.nodeValue.length&&id(e,d,t,!1,l).each(function(e){l=e.container(),f=e.offset(),c=!0}),c?U.some(Is(l,f)):U.none()},ud=function(e,t){var n=t.collapsed,r=t.cloneRange(),o=Is.fromRangeStart(t);return ad(e,n,!0,r).each(function(e){n&&Is.isAbove(o,e)||r.setStart(e.container(),e.offset())}),n||ad(e,n,!1,r).each(function(e){r.setEnd(e.container(),e.offset())}),n&&r.collapse(!0),td(t,r)?U.none():U.some(r)},sd=function(e,t){return e.splitText(t)},cd=function(e){var t=e.startContainer,n=e.startOffset,r=e.endContainer,o=e.endOffset;return t===r&&On(t)?0<n&&n<t.nodeValue.length&&(t=(r=sd(t,n)).previousSibling,n<o?(t=r=sd(r,o-=n).previousSibling,o=r.nodeValue.length,n=0):o=0):(On(t)&&0<n&&n<t.nodeValue.length&&(t=sd(t,n),n=0),On(r)&&0<o&&o<r.nodeValue.length&&(o=(r=sd(r,o).previousSibling).nodeValue.length)),{startContainer:t,startOffset:n,endContainer:r,endOffset:o}};function ld(n){return{walk:function(e,t){return Sf(n,e,t)},split:cd,normalize:function(t){return ud(n,t).fold(p,function(e){return t.setStart(e.startContainer,e.startOffset),t.setEnd(e.endContainer,e.endOffset),!0})}}}(Wf=ld=ld||{}).compareRanges=td,Wf.getCaretRangeFromPoint=ed,Wf.getSelectedNode=ps,Wf.getNode=gs;var fd=ld;var dd,md,pd,gd,hd,vd=(dd="height",md=function(e){var t=e.dom;return dn(e)?t.getBoundingClientRect().height:t.offsetHeight},{set:function(e,t){if(!D(t)&&!t.match(/^[0-9]+$/))throw new Error(dd+".set accepts only positive integer values. Value was "+t);var n=e.dom;Hn(n)&&(n.style[dd]=t+"px")},get:pd=function(e){var t=md(e);if(t<=0||null===t){var n=Yn(e,dd);return parseFloat(n)||0}return t},getOuter:pd,aggregate:gd=function(o,e){return W(e,function(e,t){var n=Yn(o,t),r=n===undefined?0:parseInt(n,10);return isNaN(r)?e:e+r},0)},max:function(e,t,n){var r=gd(e,n);return r<t?t-r:0}}),yd=function(r,e){return r.view(e).fold(N([]),function(e){var t=r.owner(e),n=yd(r,t);return[e].concat(n)})},bd=/* */Object.freeze({__proto__:null,view:function(e){var t;return(e.dom===document?U.none():U.from(null===(t=e.dom.defaultView)||void 0===t?void 0:t.frameElement)).map(Nt.fromDom)},owner:Ut}),Cd=function(e){var t,n,r,o=Nt.fromDom(document),i=vn(o),a=(t=e,r=(n=bd).owner(t),yd(n,r)),u=hn(e),s=H(a,function(e,t){var n=hn(t);return{left:e.left+n.left,top:e.top+n.top}},{left:0,top:0});return pn(s.left+u.left+i.left,s.top+u.top+i.top)},wd=function(e){return"textarea"===Dt(e)},xd=function(e,t){var n,r=function(e){var t=e.dom.ownerDocument,n=t.body,r=t.defaultView,o=t.documentElement;if(n===e.dom)return pn(n.offsetLeft,n.offsetTop);var i=gn(null==r?void 0:r.pageYOffset,o.scrollTop),a=gn(null==r?void 0:r.pageXOffset,o.scrollLeft),u=gn(o.clientTop,n.clientTop),s=gn(o.clientLeft,n.clientLeft);return hn(e).translate(a-s,i-u)}(e),o=(n=e,vd.get(n));return{element:e,bottom:r.top+o,height:o,pos:r,cleanup:t}},Sd=function(e,t){var n=function(e,t){var n=Wt(e);if(0===n.length||wd(e))return{element:e,offset:t};if(t<n.length&&!wd(n[t]))return{element:n[t],offset:0};var r=n[n.length-1];return wd(r)?{element:e,offset:t}:"img"===Dt(r)?{element:r,offset:1}:Lt(r)?{element:r,offset:Uf(r).length}:{element:r,offset:Wt(r).length}}(e,t),r=Nt.fromHtml('<span data-mce-bogus="all">\ufeff</span>');return rn(n.element,r),xd(r,function(){return ln(r)})},Nd=function(n,r,o,i){Rd(n,function(e,t){return kd(n,r,o,i)},o)},Ed=function(e,t,n,r,o){var i,a,u={elm:r.element.dom,alignToTop:o};i=u,e.fire("ScrollIntoView",i).isDefaultPrevented()||(n(t,vn(t).top,r,o),a=u,e.fire("AfterScrollIntoView",a))},kd=function(e,t,n,r){var o=Nt.fromDom(e.getBody()),i=Nt.fromDom(e.getDoc());o.dom.offsetWidth;var a=Sd(Nt.fromDom(n.startContainer),n.startOffset);Ed(e,i,t,a,r),a.cleanup()},_d=function(e,t,n,r){var o,i=Nt.fromDom(e.getDoc());Ed(e,i,n,(o=t,xd(Nt.fromDom(o),V)),r)},Rd=function(e,t,n){var r=n.startContainer,o=n.startOffset,i=n.endContainer,a=n.endOffset;t(Nt.fromDom(r),Nt.fromDom(i));var u=e.dom.createRng();u.setStart(r,o),u.setEnd(i,a),e.selection.setRng(n)},Td=function(e,t,n,r){var o,i=e.pos;n?yn(i.left,i.top,r):(o=i.top-t+e.height,yn(i.left,o,r))},Ad=function(e,t,n,r,o){var i=n+t,a=r.pos.top,u=r.bottom,s=n<=u-a;a<t?Td(r,n,!1!==o,e):i<a?Td(r,n,s?!1!==o:!0===o,e):i<u&&!s&&Td(r,n,!0===o,e)},Dd=function(e,t,n,r){var o=e.dom.defaultView.innerHeight;Ad(e,t,o,n,r)},Od=function(e,t,n,r){var o=e.dom.defaultView.innerHeight;Ad(e,t,o,n,r);var i=Cd(n.element),a=wn(window);i.top<a.y?bn(n.element,!1!==r):i.top>a.bottom&&bn(n.element,!0===r)},Bd=function(e,t,n){return Nd(e,Dd,t,n)},Pd=function(e,t,n){return _d(e,t,Dd,n)},Ld=function(e,t,n){return Nd(e,Od,t,n)},Id=function(e,t,n){return _d(e,t,Od,n)},Md=function(e,t,n){(e.inline?Bd:Ld)(e,t,n)},Fd=function(e){var t=Zt(e).dom;return e.dom===t.activeElement},Ud=function(e){return void 0===e&&(e=Nt.fromDom(document)),U.from(e.dom.activeElement).map(Nt.fromDom)},zd=function(e,t,n,r){return{start:e,soffset:t,finish:n,foffset:r}},jd=gr([{before:["element"]},{on:["element","offset"]},{after:["element"]}]),Hd=(jd.before,jd.on,jd.after,function(e){return e.fold(o,o,o)}),Vd=gr([{domRange:["rng"]},{relative:["startSitu","finishSitu"]},{exact:["start","soffset","finish","foffset"]}]),qd={domRange:Vd.domRange,relative:Vd.relative,exact:Vd.exact,exactFromRange:function(e){return Vd.exact(e.start,e.soffset,e.finish,e.foffset)},getWin:function(e){var t=e.match({domRange:function(e){return Nt.fromDom(e.startContainer)},relative:function(e,t){return Hd(e)},exact:function(e,t,n,r){return e}});return zt(t)},range:zd},$d=st().browser,Wd=function(e,t){var n=Lt(t)?Uf(t).length:Wt(t).length+1;return n<e?n:e<0?0:e},Kd=function(e){return qd.range(e.start,Wd(e.soffset,e.start),e.finish,Wd(e.foffset,e.finish))},Xd=function(e,t){return!Sn(t.dom)&&(At(e,t)||Rt(e,t))},Yd=function(t){return function(e){return Xd(t,e.start)&&Xd(t,e.finish)}},Gd=function(e){return!0===e.inline||$d.isIE()},Jd=function(e){return qd.range(Nt.fromDom(e.startContainer),e.startOffset,Nt.fromDom(e.endContainer),e.endOffset)},Qd=function(e){var t,n,r=zt(e);return t=r.dom,((n=t.getSelection())&&0!==n.rangeCount?U.from(n.getRangeAt(0)):U.none()).map(Jd).filter(Yd(e))},Zd=function(e){var t=document.createRange();try{return t.setStart(e.start.dom,e.soffset),t.setEnd(e.finish.dom,e.foffset),U.some(t)}catch(n){return U.none()}},em=function(e){var t=Gd(e)?Qd(Nt.fromDom(e.getBody())):U.none();e.bookmark=t.isSome()?t:e.bookmark},tm=function(r){return(r.bookmark?r.bookmark:U.none()).bind(function(e){return t=Nt.fromDom(r.getBody()),n=e,U.from(n).filter(Yd(t)).map(Kd);var t,n}).bind(Zd)},nm={isEditorUIElement:function(e){var t=e.className.toString();return-1!==t.indexOf("tox-")||-1!==t.indexOf("mce-")}},rm=function(n,e){var t,r;st().browser.isIE()?(r=n).on("focusout",function(){em(r)}):(t=e,n.on("mouseup touchend",function(e){t.throttle()})),n.on("keyup NodeChange",function(e){var t;"nodechange"===(t=e).type&&t.selectionChange||em(n)})},om=function(r){var o=Pu(function(){em(r)},0);r.on("init",function(){var e,t,n;r.inline&&(e=r,t=o,n=function(){t.throttle()},bu.DOM.bind(document,"mouseup",n),e.on("remove",function(){bu.DOM.unbind(document,"mouseup",n)})),rm(r,o)}),r.on("remove",function(){o.cancel()})},im=bu.DOM,am=function(t,e){var n=t.getParam("custom_ui_selector","","string");return null!==im.getParent(e,function(e){return nm.isEditorUIElement(e)||!!n&&t.dom.is(e,n)})},um=function(n,e){var t=e.editor;om(t),t.on("focusin",function(){var e=n.focusedEditor;e!==this&&(e&&e.fire("blur",{focusedEditor:this}),n.setActive(this),(n.focusedEditor=this).fire("focus",{blurredEditor:e}),this.focus(!0))}),t.on("focusout",function(){var t=this;Fr.setEditorTimeout(t,function(){var e=n.focusedEditor;am(t,function(e){try{var t=Zt(Nt.fromDom(e.getElement()));return Ud(t).fold(function(){return document.body},function(e){return e.dom})}catch(n){return document.body}}(t))||e!==t||(t.fire("blur",{focusedEditor:null}),n.focusedEditor=null)})}),hd||(hd=function(e){var t=n.activeEditor;t&&function(e){if(Qt()&&T(e.target)){var t=Nt.fromDom(e.target);if(Pt(t)&&nn(t)&&e.composed&&e.composedPath){var n=e.composedPath();if(n)return Z(n)}}return U.from(e.target)}(e).each(function(e){e.ownerDocument===document&&(e===document.body||am(t,e)||n.focusedEditor!==t||(t.fire("blur",{focusedEditor:null}),n.focusedEditor=null))})},im.bind(document,"focusin",hd))},sm=function(e,t){e.focusedEditor===t.editor&&(e.focusedEditor=null),e.activeEditor||(im.unbind(document,"focusin",hd),hd=null)},cm=function(t,e){return((n=e).collapsed?U.from(gs(n.startContainer,n.startOffset)).map(Nt.fromDom):U.none()).bind(function(e){return eo(e)?U.some(e):!1===At(t,e)?U.some(t):U.none()});var n},lm=function(t,e){cm(Nt.fromDom(t.getBody()),e).bind(function(e){return Ol(e.dom)}).fold(function(){t.selection.normalize()},function(e){return t.selection.setRng(e.toRange())})},fm=function(e){if(e.setActive)try{e.setActive()}catch(t){e.focus()}else e.focus()},dm=function(e){return Fd(e)||Ud(Zt(t=e)).filter(function(e){return t.dom.contains(e.dom)}).isSome();var t},mm=function(r){return Ud().filter(function(e){return t=e.dom,!((n=t.classList)!==undefined&&(n.contains("tox-edit-area")||n.contains("tox-edit-area__iframe")||n.contains("mce-content-body")))&&am(r,e.dom);var t,n}).isSome()},pm=function(e){return e.inline?(n=e.getBody())&&dm(Nt.fromDom(n)):(t=e).iframeElement&&Fd(Nt.fromDom(t.iframeElement));var t,n},gm=function(t){var e=t.selection,n=t.getBody(),r=e.getRng();t.quirks.refreshContentEditable(),t.bookmark!==undefined&&!1===pm(t)&&tm(t).each(function(e){t.selection.setRng(e),r=e});var o,i,a=(o=t,i=e.getNode(),o.dom.getParent(i,function(e){return"true"===o.dom.getContentEditable(e)}));if(t.$.contains(n,a))return fm(a),lm(t,r),void hm(t);t.inline||(vt.opera||fm(n),t.getWin().focus()),(vt.gecko||t.inline)&&(fm(n),lm(t,r)),hm(t)},hm=function(e){return e.editorManager.setActive(e)},vm=function(e,t,n,r,o){var i=n?t.startContainer:t.endContainer,a=n?t.startOffset:t.endOffset;return U.from(i).map(Nt.fromDom).map(function(e){return r&&t.collapsed?e:Kt(e,o(e,a)).getOr(e)}).bind(function(e){return Pt(e)?U.some(e):jt(e).filter(Pt)}).map(function(e){return e.dom}).getOr(e)},ym=function(e,t,n){return vm(e,t,!0,n,function(e,t){return Math.min(e.dom.childNodes.length,t)})},bm=function(e,t,n){return vm(e,t,!1,n,function(e,t){return 0<t?t-1:t})},Cm=function(e,t){for(var n=e;e&&On(e)&&0===e.length;)e=t?e.nextSibling:e.previousSibling;return e||n},wm=function(n,e){return F(e,function(e){var t=n.fire("GetSelectionRange",{range:e});return t.range!==e?t.range:e})},xm={"#text":3,"#comment":8,"#cdata":4,"#pi":7,"#doctype":10,"#document-fragment":11},Sm=function(e,t,n){var r=n?"lastChild":"firstChild",o=n?"prev":"next";if(e[r])return e[r];if(e!==t){var i=e[o];if(i)return i;for(var a=e.parent;a&&a!==t;a=a.parent)if(i=a[o])return i}},Nm=function(e){var t="a"===e.name&&!e.attr("href")&&e.attr("id");return e.attr("name")||e.attr("id")&&!e.firstChild||e.attr("data-mce-bookmark")||t},Em=(km.create=function(e,t){var n=new km(e,xm[e]||1);return t&&oe(t,function(e,t){n.attr(t,e)}),n},km.prototype.replace=function(e){return e.parent&&e.remove(),this.insert(e,this),this.remove(),this},km.prototype.attr=function(e,t){var n,r=this;if("string"!=typeof e)return e!==undefined&&null!==e&&oe(e,function(e,t){r.attr(t,e)}),r;if(n=r.attributes){if(t===undefined)return n.map[e];if(null===t){if(e in n.map){delete n.map[e];for(var o=n.length;o--;)if(n[o].name===e)return n.splice(o,1),r}return r}if(e in n.map){for(o=n.length;o--;)if(n[o].name===e){n[o].value=t;break}}else n.push({name:e,value:t});return n.map[e]=t,r}},km.prototype.clone=function(){var e,t=new km(this.name,this.type);if(e=this.attributes){var n=[];n.map={};for(var r=0,o=e.length;r<o;r++){var i=e[r];"id"!==i.name&&(n[n.length]={name:i.name,value:i.value},n.map[i.name]=i.value)}t.attributes=n}return t.value=this.value,t.shortEnded=this.shortEnded,t},km.prototype.wrap=function(e){return this.parent.insert(e,this),e.append(this),this},km.prototype.unwrap=function(){for(var e=this.firstChild;e;){var t=e.next;this.insert(e,this,!0),e=t}this.remove()},km.prototype.remove=function(){var e=this.parent,t=this.next,n=this.prev;return e&&(e.firstChild===this?(e.firstChild=t)&&(t.prev=null):n.next=t,e.lastChild===this?(e.lastChild=n)&&(n.next=null):t.prev=n,this.parent=this.next=this.prev=null),this},km.prototype.append=function(e){e.parent&&e.remove();var t=this.lastChild;return t?((t.next=e).prev=t,this.lastChild=e):this.lastChild=this.firstChild=e,e.parent=this,e},km.prototype.insert=function(e,t,n){e.parent&&e.remove();var r=t.parent||this;return n?(t===r.firstChild?r.firstChild=e:t.prev.next=e,e.prev=t.prev,(e.next=t).prev=e):(t===r.lastChild?r.lastChild=e:t.next.prev=e,e.next=t.next,(e.prev=t).next=e),e.parent=r,e},km.prototype.getAll=function(e){for(var t=[],n=this.firstChild;n;n=Sm(n,this))n.name===e&&t.push(n);return t},km.prototype.empty=function(){if(this.firstChild){for(var e=[],t=this.firstChild;t;t=Sm(t,this))e.push(t);for(var n=e.length;n--;)(t=e[n]).parent=t.firstChild=t.lastChild=t.next=t.prev=null}return this.firstChild=this.lastChild=null,this},km.prototype.isEmpty=function(e,t,n){void 0===t&&(t={});var r=this.firstChild;if(Nm(this))return!1;if(r)do{if(1===r.type){if(r.attr("data-mce-bogus"))continue;if(e[r.name])return!1;if(Nm(r))return!1}if(8===r.type)return!1;if(3===r.type&&!function(e){if(Bo(e.value)){var t=e.parent;return!t||"span"===t.name&&!t.attr("style")||!/^[ ]+$/.test(e.value)}}(r))return!1;if(3===r.type&&r.parent&&t[r.parent.name]&&Bo(r.value))return!1;if(n&&n(r))return!1}while(r=Sm(r,this));return!0},km.prototype.walk=function(e){return Sm(this,null,e)},km);function km(e,t){this.name=e,1===(this.type=t)&&(this.attributes=[],this.attributes.map={})}var _m=xt.makeMap,Rm=function(e){var u=[],s=(e=e||{}).indent,c=_m(e.indent_before||""),l=_m(e.indent_after||""),f=ri.getEncodeFunc(e.entity_encoding||"raw",e.entities),d="html"===e.element_format;return{start:function(e,t,n){var r,o,i,a;if(s&&c[e]&&0<u.length&&0<(a=u[u.length-1]).length&&"\n"!==a&&u.push("\n"),u.push("<",e),t)for(r=0,o=t.length;r<o;r++)i=t[r],u.push(" ",i.name,'="',f(i.value,!0),'"');u[u.length]=!n||d?">":" />",n&&s&&l[e]&&0<u.length&&0<(a=u[u.length-1]).length&&"\n"!==a&&u.push("\n")},end:function(e){var t;u.push("</",e,">"),s&&l[e]&&0<u.length&&0<(t=u[u.length-1]).length&&"\n"!==t&&u.push("\n")},text:function(e,t){0<e.length&&(u[u.length]=t?e:f(e))},cdata:function(e){u.push("<![CDATA[",e,"]]>")},comment:function(e){u.push("\x3c!--",e,"--\x3e")},pi:function(e,t){t?u.push("<?",e," ",f(t),"?>"):u.push("<?",e,"?>"),s&&u.push("\n")},doctype:function(e){u.push("<!DOCTYPE",e,">",s?"\n":"")},reset:function(){u.length=0},getContent:function(){return u.join("").replace(/\n$/,"")}}},Tm=function(t,p){void 0===p&&(p=pi());var g=Rm(t);(t=t||{}).validate=!("validate"in t)||t.validate;return{serialize:function(e){var f=t.validate,d={3:function(e){g.text(e.value,e.raw)},8:function(e){g.comment(e.value)},7:function(e){g.pi(e.name,e.value)},10:function(e){g.doctype(e.value)},4:function(e){g.cdata(e.value)},11:function(e){if(e=e.firstChild)for(;m(e),e=e.next;);}};g.reset();var m=function(e){var t,n,r,o,i,a,u,s,c,l=d[e.type];if(l)l(e);else{if(t=e.name,n=e.shortEnded,r=e.attributes,f&&r&&1<r.length&&((a=[]).map={},c=p.getElementRule(e.name))){for(u=0,s=c.attributesOrder.length;u<s;u++)(o=c.attributesOrder[u])in r.map&&(i=r.map[o],a.map[o]=i,a.push({name:o,value:i}));for(u=0,s=r.length;u<s;u++)(o=r[u].name)in a.map||(i=r.map[o],a.map[o]=i,a.push({name:o,value:i}));r=a}if(g.start(e.name,r,n),!n){if(e=e.firstChild)for(;m(e),e=e.next;);g.end(t)}}};return 1!==e.type||t.inner?d[11](e):m(e),g.getContent()}}},Am=function(e,t){return e.replace(new RegExp(t.prefix+"_[0-9]+","g"),function(e){return de(t.uris,e).getOr(e)})},Dm=function(e,t,n){var r,o,i=1,a=e.getShortEndedElements(),u=/<([!?\/])?([A-Za-z0-9\-_\:\.]+)((?:\s+[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*|\/|\s+)>/g;for(u.lastIndex=r=n;o=u.exec(t);){if(r=u.lastIndex,"/"===o[1])i--;else if(!o[1]){if(o[2]in a)continue;i++}if(0===i)break}return r};function Om(W,K){void 0===K&&(K=pi());var e=function(){};!1!==(W=W||{}).fix_self_closing&&(W.fix_self_closing=!0);var X=W.comment?W.comment:e,Y=W.cdata?W.cdata:e,G=W.text?W.text:e,J=W.start?W.start:e,Q=W.end?W.end:e,Z=W.pi?W.pi:e,ee=W.doctype?W.doctype:e,n=function(m,e){void 0===e&&(e="html");for(var t,n,r,p,o,i,a,g,u,s,c,l,f,h,v,d,y,b,C,w=m.html,x=0,S=[],N=0,E=ri.decode,k=xt.makeMap("src,href,data,background,formaction,poster,xlink:href"),_=/((java|vb)script|mhtml):/i,R="html"===e?0:1,T=function(e){for(var t,n=S.length;n--&&S[n].name!==e;);if(0<=n){for(t=S.length-1;n<=t;t--)(e=S[t]).valid&&Q(e.name);S.length=n}},A=function(e,t){return G(Am(e,m),t)},D=function(e){""!==e&&(">"===e.charAt(0)&&(e=" "+e),W.allow_conditional_comments||"[if"!==e.substr(0,3).toLowerCase()||(e=" "+e),X(Am(e,m)))},O=function(e,t){var n=e||"",r=!Ue(n,"--"),o=function(e,t,n){void 0===n&&(n=0);var r=e.toLowerCase();if(-1!==r.indexOf("[if ",n)&&(u=n,/^\s*\[if [\w\W]+\]>.*<!\[endif\](--!?)?>/.test(r.substr(u)))){var o=r.indexOf("[endif]",n);return r.indexOf(">",o)}if(t){var i=r.indexOf(">",n);return-1!==i?i:r.length}var a=/--!?>/;a.lastIndex=n;var u,s=a.exec(e);return s?s.index+s[0].length:r.length}(w,r,t);return e=w.substr(t,o-t),D(r?n+e:e),o+1},B=function(e,t,n,r,o){var i,a,u,s,c,l;if(t=t.toLowerCase(),u=t in F?t:E(n||r||o||""),n=de(m.uris,u).getOr(u),U&&!g&&!1==(0===(s=t).indexOf("data-")||0===s.indexOf("aria-"))){if(!(i=h[t])&&v){for(a=v.length;a--&&!(i=v[a]).pattern.test(t););-1===a&&(i=null)}if(!i)return;if(i.validValues&&!(n in i.validValues))return}if(k[t]&&!W.allow_script_urls){var f=n.replace(/[\s\u0000-\u001F]+/g,"");try{f=decodeURIComponent(f)}catch(d){f=unescape(f)}if(_.test(f))return;if(l=f,!(c=W).allow_html_data_urls&&(/^data:image\//i.test(l)?!1===c.allow_svg_data_urls&&/^data:image\/svg\+xml/i.test(l):/^data:/i.test(l)))return}g&&(t in k||0===t.indexOf("on"))||(p.map[t]=n,p.push({name:t,value:n}))},P=new RegExp("<(?:(?:!--([\\w\\W]*?)--!?>)|(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]>)|(?:![Dd][Oo][Cc][Tt][Yy][Pp][Ee]([\\w\\W]*?)>)|(?:!(--)?)|(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|(?:\\/([A-Za-z][A-Za-z0-9\\-_\\:\\.]*)>)|(?:([A-Za-z][A-Za-z0-9\\-_\\:\\.]*)((?:\\s+[^\"'>]+(?:(?:\"[^\"]*\")|(?:'[^']*')|[^>]*))*|\\/|\\s+)>))","g"),L=/([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:[^\"])*)\")|(?:\'((?:[^\'])*)\')|([^>\s]+)))?/g,I=K.getShortEndedElements(),M=W.self_closing_elements||K.getSelfClosingElements(),F=K.getBoolAttrs(),U=W.validate,z=W.remove_internals,j=W.fix_self_closing,H=K.getSpecialElements(),V=w+">";t=P.exec(V);){var q=t[0];if(x<t.index&&A(E(w.substr(x,t.index-x))),n=t[7])":"===(n=n.toLowerCase()).charAt(0)&&(n=n.substr(1)),T(n);else if(n=t[8]){if(t.index+q.length>w.length){A(E(w.substr(t.index))),x=t.index+q.length;continue}":"===(n=n.toLowerCase()).charAt(0)&&(n=n.substr(1)),u=n in I,j&&M[n]&&0<S.length&&S[S.length-1].name===n&&T(n);var $=function(e,t){var n=e.exec(t);if(n){var r=n[1],o=n[2];return"string"==typeof r&&"data-mce-bogus"===r.toLowerCase()?o:null}return null}(L,t[9]);if(null!==$){if("all"===$){x=Dm(K,w,P.lastIndex),P.lastIndex=x;continue}c=!1}if(!U||(s=K.getElementRule(n))){if(c=!0,U&&(h=s.attributes,v=s.attributePatterns),(f=t[9])?((g=-1!==f.indexOf("data-mce-type"))&&z&&(c=!1),(p=[]).map={},f.replace(L,B)):(p=[]).map={},U&&!g){if(d=s.attributesRequired,y=s.attributesDefault,b=s.attributesForced,s.removeEmptyAttrs&&!p.length&&(c=!1),b)for(o=b.length;o--;)a=(l=b[o]).name,"{$uid}"===(C=l.value)&&(C="mce_"+N++),p.map[a]=C,p.push({name:a,value:C});if(y)for(o=y.length;o--;)(a=(l=y[o]).name)in p.map||("{$uid}"===(C=l.value)&&(C="mce_"+N++),p.map[a]=C,p.push({name:a,value:C}));if(d){for(o=d.length;o--&&!(d[o]in p.map););-1===o&&(c=!1)}if(l=p.map["data-mce-bogus"]){if("all"===l){x=Dm(K,w,P.lastIndex),P.lastIndex=x;continue}c=!1}}c&&J(n,p,u)}else c=!1;if(r=H[n]){r.lastIndex=x=t.index+q.length,x=(t=r.exec(w))?(c&&(i=w.substr(x,t.index-x)),t.index+t[0].length):(i=w.substr(x),w.length),c&&(0<i.length&&A(i,!0),Q(n)),P.lastIndex=x;continue}u||(f&&f.indexOf("/")===f.length-1?c&&Q(n):S.push({name:n,valid:c}))}else if(n=t[1])D(n);else if(n=t[2]){if(!(1==R||W.preserve_cdata||0<S.length&&K.isValidChild(S[S.length-1].name,"#cdata"))){x=O("",t.index+2),P.lastIndex=x;continue}Y(n)}else if(n=t[3])ee(n);else{if((n=t[4])||"<!"===q){x=O(n,t.index+q.length),P.lastIndex=x;continue}if(n=t[5]){if(1!=R){x=O("?",t.index+2),P.lastIndex=x;continue}Z(n,t[6])}}x=t.index+q.length}for(x<w.length&&A(E(w.substr(x))),o=S.length-1;0<=o;o--)(n=S[o]).valid&&Q(n.name)};return{parse:function(e,t){void 0===t&&(t="html"),n(function(e){for(var t,n=/data:[^;]+;base64,([a-z0-9\+\/=]+)/gi,r=[],o={},i=Zu("img"),a=0,u=0;t=n.exec(e);){var s=t[0],c=i+"_"+u++;o[c]=s,a<t.index&&r.push(e.substr(a,t.index-a)),r.push(c),a=t.index+s.length}return 0===a?{prefix:i,uris:o,html:e}:(a<e.length&&r.push(e.substr(a)),{prefix:i,uris:o,html:r.join("")})}(e),t)}}}(Om=Om||{}).findEndTag=Dm;var Bm,Pm,Lm=Om,Im=function(e,t){var n,r,o,i,a,u,s,c=t,l=/<(\w+) [^>]*data-mce-bogus="all"[^>]*>/g,f=e.schema;a=e.getTempAttrs(),u=c,s=new RegExp(["\\s?("+a.join("|")+')="[^"]+"'].join("|"),"gi"),c=u.replace(s,"");for(var d=f.getShortEndedElements();i=l.exec(c);)r=l.lastIndex,o=i[0].length,n=d[i[1]]?r:Lm.findEndTag(f,c,r),c=c.substring(0,r-o)+c.substring(n),l.lastIndex=r-o;return uo(c)},Mm=Im,Fm=function(e,t,n,r){var o,i,a,u,s;if(t.format=n,t.get=!0,t.getInner=!0,t.no_events||e.fire("BeforeGetContent",t),"raw"===t.format)o=xt.trim(Mm(e.serializer,r.innerHTML));else if("text"===t.format)o=uo(r.innerText||r.textContent);else{if("tree"===t.format)return e.serializer.serialize(r,t);a=(i=e).serializer.serialize(r,t),u=fc(i),s=new RegExp("^(<"+u+"[^>]*>(&nbsp;|&#160;|\\s|\xa0|<br \\/>|)<\\/"+u+">[\r\n]*|<br \\/>[\r\n]*)$"),o=a.replace(s,"")}return"text"===t.format||no(Nt.fromDom(r))?t.content=o:t.content=xt.trim(o),t.no_events||e.fire("GetContent",t),t.content},Um=xt.each,zm=function(o){this.compare=function(e,t){if(e.nodeName!==t.nodeName)return!1;var n=function(n){var r={};return Um(o.getAttribs(n),function(e){var t=e.nodeName.toLowerCase();0!==t.indexOf("_")&&"style"!==t&&0!==t.indexOf("data-")&&(r[t]=o.getAttrib(n,t))}),r},r=function(e,t){var n,r;for(r in e)if(e.hasOwnProperty(r)){if(void 0===(n=t[r]))return!1;if(e[r]!==n)return!1;delete t[r]}for(r in t)if(t.hasOwnProperty(r))return!1;return!0};return!!r(n(e),n(t))&&(!!r(o.parseStyle(o.getAttrib(e,"style")),o.parseStyle(o.getAttrib(t,"style")))&&(!$l(e)&&!$l(t)))}},jm=function(n,r,o){return U.from(o.container()).filter(On).exists(function(e){var t=n?0:-1;return r(e.data.charAt(o.offset()+t))})},Hm=E(jm,!0,Kl),Vm=E(jm,!1,Kl),qm=function(e){var t=e.container();return On(t)&&(0===t.data.length||ao(t.data)&&Kf.isBookmarkNode(t.parentNode))},$m=function(t,n){return function(e){return U.from(Zc(t?0:-1,e)).filter(n).isSome()}},Wm=function(e){return Mn(e)&&"block"===Yn(Nt.fromDom(e),"display")},Km=function(e){return Un(e)&&!(Nn(t=e)&&"all"===t.getAttribute("data-mce-bogus"));var t},Xm=$m(!0,Wm),Ym=$m(!1,Wm),Gm=$m(!0,jn),Jm=$m(!1,jn),Qm=$m(!0,Tn),Zm=$m(!1,Tn),ep=$m(!0,Km),tp=$m(!1,Km),np=function(e){var t=qu(e,"br"),n=j(function(e){for(var t=[],n=e.dom;n;)t.push(Nt.fromDom(n)),n=n.lastChild;return t}(e).slice(-1),Gr);t.length===n.length&&$(n,ln)},rp=function(e){cn(e),un(e,Nt.fromHtml('<br data-mce-bogus="1">'))},op=function(n){Yt(n).each(function(t){Ht(t).each(function(e){Xr(n)&&Gr(t)&&Xr(e)&&ln(t)})})},ip=function(e,t,n){return At(t,e)?function(e,t){for(var n=A(t)?t:p,r=e.dom,o=[];null!==r.parentNode&&r.parentNode!==undefined;){var i=r.parentNode,a=Nt.fromDom(i);if(o.push(a),!0===n(a))break;r=i}return o}(e,function(e){return n(e)||Rt(e,t)}).slice(0,-1):[]},ap=function(e,t){return ip(e,t,p)},up=function(e,t){return[e].concat(ap(e,t))},sp=function(e,t,n){return Rl(e,t,n,qm)},cp=function(e,t){return K(up(Nt.fromDom(t.container()),e),Xr)},lp=function(e,n,r){return sp(e,n.dom,r).forall(function(t){return cp(n,r).fold(function(){return!1===Qc(t,r,n.dom)},function(e){return!1===Qc(t,r,n.dom)&&At(e,Nt.fromDom(t.container()))})})},fp=function(t,n,r){return cp(n,r).fold(function(){return sp(t,n.dom,r).forall(function(e){return!1===Qc(e,r,n.dom)})},function(e){return sp(t,e.dom,r).isNone()})},dp=E(fp,!1),mp=E(fp,!0),pp=E(lp,!1),gp=E(lp,!0),hp=function(e){return ul(e).exists(Gr)},vp=function(e,t,n){var r=j(up(Nt.fromDom(n.container()),t),Xr),o=Z(r).getOr(t);return kl(e,o.dom,n).filter(hp)},yp=function(e,t){return ul(t).exists(Gr)||vp(!0,e,t).isSome()},bp=function(e,t){return n=t,U.from(n.getNode(!0)).map(Nt.fromDom).exists(Gr)||vp(!1,e,t).isSome();var n},Cp=E(vp,!1),wp=E(vp,!0),xp=function(e){return Is.isTextPosition(e)&&!e.isAtStart()&&!e.isAtEnd()},Sp=function(e,t){var n=j(up(Nt.fromDom(t.container()),e),Xr);return Z(n).getOr(e)},Np=function(e,t){return xp(t)?Vm(t):Vm(t)||Dl(Sp(e,t).dom,t).exists(Vm)},Ep=function(e,t){return xp(t)?Hm(t):Hm(t)||Al(Sp(e,t).dom,t).exists(Hm)},kp=function(e){return ul(e).bind(function(e){return Sr(e,Pt)}).exists(function(e){return t=Yn(e,"white-space"),I(["pre","pre-wrap"],t);var t})},_p=function(e,t){return r=t,Dl(e.dom,r).isNone()||(n=t,Al(e.dom,n).isNone())||dp(e,t)||mp(e,t)||bp(e,t)||yp(e,t);var n,r},Rp=function(e,t){return!kp(t)&&(dp(e,t)||pp(e,t)||bp(e,t)||Np(e,t))},Tp=function(e,t){return!kp(t)&&(mp(e,t)||gp(e,t)||yp(e,t)||Ep(e,t))},Ap=function(e,t){return Rp(e,t)||Tp(e,(r=(n=t).container(),o=n.offset(),On(r)&&o<r.data.length?Is(r,o+1):n));var n,r,o},Dp=function(e,t){return Wl(e.charAt(t))},Op=function(e){var t=e.container();return On(t)&&Fe(t.data,oo)},Bp=function(e){var n,t=e.data,r=(n=t.split(""),F(n,function(e,t){return Wl(e)&&0<t&&t<n.length-1&&Xl(n[t-1])&&Xl(n[t+1])?" ":e}).join(""));return r!==t&&(e.data=r,!0)},Pp=function(l,e){return U.some(e).filter(Op).bind(function(e){var t,n,r,o,i,a,u,s,c=e.container();return(i=l,u=(a=c).data,s=Is(a,0),!(!Dp(u,0)||Ap(i,s)||(a.data=" "+u.slice(1),0))||Bp(c)||(t=l,r=(n=c).data,o=Is(n,r.length-1),!(!Dp(r,r.length-1)||Ap(t,o)||(n.data=r.slice(0,-1)+" ",0))))?U.some(e):U.none()})},Lp=function(t){var e=Nt.fromDom(t.getBody());t.selection.isCollapsed()&&Pp(e,Is.fromRangeStart(t.selection.getRng())).each(function(e){t.selection.setRng(e.toRange())})},Ip=function(e,t,n){var r,o,i,a,u,s,c,l;0!==n&&(r=Nt.fromDom(e),o=xr(r,Xr).getOr(r),i=e.data.slice(t,t+n),a=t+n>=e.data.length&&Tp(o,Us(e,e.data.length)),u=0===t&&Rp(o,Us(e,0)),e.replaceData(t,n,(c=u,l=a,W(s=i,function(e,t){return Kl(t)||Wl(t)?e.previousCharIsSpace||""===e.str&&c||e.str.length===s.length-1&&l?{previousCharIsSpace:!1,str:e.str+oo}:{previousCharIsSpace:!0,str:e.str+" "}:{previousCharIsSpace:!1,str:e.str+t}},{previousCharIsSpace:!1,str:""}).str)))},Mp=function(e,t){var n=e.data.slice(t),r=n.length-He(n).length;return Ip(e,t,r)},Fp=function(e,t){var n=e.data.slice(0,t),r=n.length-Ve(n).length;return Ip(e,t-r,r)},Up=function(e,t,n,r){void 0===r&&(r=!0);var o=Ve(e.data).length,i=r?e:t,a=r?t:e;return r?i.appendData(a.data):i.insertData(0,a.data),ln(Nt.fromDom(a)),n&&Mp(i,o),i},zp=function(e,t){return r=e,o=(n=t).container(),i=n.offset(),!1===Us.isTextPosition(n)&&o===r.parentNode&&i>Us.before(r).offset()?Us(t.container(),t.offset()-1):t;var n,r,o,i},jp=function(e){return To(e.previousSibling)?U.some((t=e.previousSibling,On(t)?Us(t,t.data.length):Us.after(t))):e.previousSibling?Bl(e.previousSibling):U.none();var t},Hp=function(e){return To(e.nextSibling)?U.some((t=e.nextSibling,On(t)?Us(t,0):Us.before(t))):e.nextSibling?Ol(e.nextSibling):U.none();var t},Vp=function(r,o){return jp(o).orThunk(function(){return Hp(o)}).orThunk(function(){return e=r,t=o,n=Us.before(t.previousSibling?t.previousSibling:t.parentNode),Dl(e,n).fold(function(){return Al(e,Us.after(t))},U.some);var e,t,n})},qp=function(n,r){return Hp(r).orThunk(function(){return jp(r)}).orThunk(function(){return t=r,Al(e=n,Us.after(t)).fold(function(){return Dl(e,Us.before(t))},U.some);var e,t})},$p=function(e,t,n){return(e?qp:Vp)(t,n).map(E(zp,n))},Wp=function(t,n,e){e.fold(function(){t.focus()},function(e){t.selection.setRng(e.toRange(),n)})},Kp=function(e,t){return t&&me(e.schema.getBlockElements(),Dt(t))},Xp=function(e){if(Uo(e)){var t=Nt.fromHtml('<br data-mce-bogus="1">');return cn(e),un(e,t),U.some(Us.before(t.dom))}return U.none()},Yp=function(e,t,a){var n,r,o,i,u=Ht(e).filter(Lt),s=Vt(e).filter(Lt);return ln(e),r=s,o=t,i=function(e,t,n){var r=e.dom,o=t.dom,i=r.data.length;return Up(r,o,a),n.container()===o?Us(r,i):n},((n=u).isSome()&&r.isSome()&&o.isSome()?U.some(i(n.getOrDie(),r.getOrDie(),o.getOrDie())):U.none()).orThunk(function(){return a&&(u.each(function(e){return Fp(e.dom,e.dom.length)}),s.each(function(e){return Mp(e.dom,0)})),t})},Gp=function(t,n,e,r){void 0===r&&(r=!0);var o,i,a=$p(n,t.getBody(),e.dom),u=xr(e,E(Kp,t),(o=t.getBody(),function(e){return e.dom===o})),s=Yp(e,a,(i=e,me(t.schema.getTextInlineElements(),Dt(i))));t.dom.isEmpty(t.getBody())?(t.setContent(""),t.selection.setCursorLocation()):u.bind(Xp).fold(function(){r&&Wp(t,n,s)},function(e){r&&Wp(t,n,U.some(e))})},Jp=function(e,t){return{start:e,end:t}},Qp=gr([{removeTable:["element"]},{emptyCells:["cells"]},{deleteCellSelection:["rng","cell"]}]),Zp=function(e,t){return kr(Nt.fromDom(e),"td,th",t)},eg=function(e,t){return Nr(e,"table",t)},tg=function(e){return!Rt(e.start,e.end)},ng=function(e,t){return eg(e.start,t).bind(function(r){return eg(e.end,t).bind(function(e){return t=Rt(r,e),n=r,t?U.some(n):U.none();var t,n})})},rg=function(e){return qu(e,"td,th")},og=function(r,e){var t=Zp(e.startContainer,r),n=Zp(e.endContainer,r);return e.collapsed?U.none():as(t,n,Jp).fold(function(){return t.fold(function(){return n.bind(function(t){return eg(t,r).bind(function(e){return Z(rg(e)).map(function(e){return Jp(e,t)})})})},function(t){return eg(t,r).bind(function(e){return ee(rg(e)).map(function(e){return Jp(t,e)})})})},function(e){return ig(r,e)?U.none():(n=r,eg((t=e).start,n).bind(function(e){return ee(rg(e)).map(function(e){return Jp(t.start,e)})}));var t,n})},ig=function(e,t){return ng(t,e).isSome()},ag=function(e,t,n){return e.filter(function(e){return tg(e)&&ig(n,e)}).orThunk(function(){return og(n,t)}).bind(function(e){return ng(t=e,n).map(function(e){return{rng:t,table:e,cells:rg(e)}});var t})},ug=function(e,t){return X(e,function(e){return Rt(e,t)})},sg=function(e,r,o){return e.filter(function(e){return n=o,!tg(t=e)&&ng(t,n).exists(function(e){var t=e.dom.rows;return 1===t.length&&1===t[0].cells.length})&&Af(e.start,r);var t,n}).map(function(e){return e.start})},cg=function(n){return as(ug((r=n).cells,r.rng.start),ug(r.cells,r.rng.end),function(e,t){return r.cells.slice(e,t+1)}).map(function(e){var t=n.cells;return e.length===t.length?Qp.removeTable(n.table):Qp.emptyCells(e)});var r},lg=function(e,t){var n,r,o,i,a,u=(n=e,function(e){return Rt(n,e)}),s=(o=u,i=Zp((r=t).startContainer,o),a=Zp(r.endContainer,o),as(i,a,Jp));return sg(s,t,u).map(function(e){return Qp.deleteCellSelection(t,e)}).orThunk(function(){return ag(s,t,u).bind(cg)})},fg=function(e){var t;return(8===Ot(t=e)||"#comment"===Dt(t)?Ht:Yt)(e).bind(fg).orThunk(function(){return U.some(e)})},dg=function(e,t){return $(t,rp),e.selection.setCursorLocation(t[0].dom,0),!0},mg=function(e,t,n){t.deleteContents();var r,o,i=fg(n).getOr(n),a=Nt.fromDom(e.dom.getParent(i.dom,e.dom.isBlock));return Uo(a)&&(rp(a),e.selection.setCursorLocation(a.dom,0)),Rt(n,a)||(r=jt(a).is(n)?[]:jt(o=a).map(Wt).map(function(e){return j(e,function(e){return!Rt(o,e)})}).getOr([]),$(r.concat(Wt(n)),function(e){Rt(e,a)||At(e,a)||ln(e)})),!0},pg=function(e,t){return Gp(e,!1,t),!0},gg=function(n,e,r,t){return vg(e,t).fold(function(){return t=n,lg(e,r).map(function(e){return e.fold(E(pg,t),E(dg,t),E(mg,t))});var t},function(e){return yg(n,e)}).getOr(!1)},hg=function(e,t){return K(up(t,e),to)},vg=function(e,t){return K(up(t,e),function(e){return"caption"===Dt(e)})},yg=function(e,t){return rp(t),e.selection.setCursorLocation(t.dom,0),U.some(!0)},bg=function(u,s,c,l,f){return _l(c,u.getBody(),f).bind(function(e){return o=c,i=f,a=e,Ol((r=l).dom).bind(function(t){return Bl(r.dom).map(function(e){return o?i.isEqual(t)&&a.isEqual(e):i.isEqual(e)&&a.isEqual(t)})}).getOr(!0)?yg(u,l):(t=l,n=e,vg(s,Nt.fromDom(n.getNode())).map(function(e){return!1===Rt(e,t)}));var t,n,r,o,i,a}).or(U.some(!0))},Cg=function(o,i,a,e){var u=Us.fromRangeStart(o.selection.getRng());return hg(a,e).bind(function(e){return Uo(e)?yg(o,e):(t=a,n=e,r=u,_l(i,o.getBody(),r).bind(function(e){return hg(t,Nt.fromDom(e.getNode())).map(function(e){return!1===Rt(e,n)})}));var t,n,r}).getOr(!1)},wg=function(e,t){return(e?Qm:Zm)(t)},xg=function(a,u,r){var s=Nt.fromDom(a.getBody());return vg(s,r).fold(function(){return Cg(a,u,s,r)||(e=a,t=u,n=Us.fromRangeStart(e.selection.getRng()),wg(t,n)||kl(t,e.getBody(),n).exists(function(e){return wg(t,e)}));var e,t,n},function(e){return t=a,n=u,r=s,o=e,i=Us.fromRangeStart(t.selection.getRng()),(Uo(o)?yg(t,o):bg(t,r,n,o,i)).getOr(!1);var t,n,r,o,i})},Sg=function(e,t){var n,r,o,i,a,u=Nt.fromDom(e.selection.getStart(!0)),s=_f(e);return e.selection.isCollapsed()&&0===s.length?xg(e,t,u):(n=e,r=u,o=Nt.fromDom(n.getBody()),i=n.selection.getRng(),0!==(a=_f(n)).length?dg(n,a):gg(n,o,i,r))},Ng=function(a){var u=Us.fromRangeStart(a),s=Us.fromRangeEnd(a),c=a.commonAncestorContainer;return kl(!1,c,s).map(function(e){return!Qc(u,s,c)&&Qc(u,e,c)?(t=u.container(),n=u.offset(),r=e.container(),o=e.offset(),(i=document.createRange()).setStart(t,n),i.setEnd(r,o),i):a;var t,n,r,o,i}).getOr(a)},Eg=function(e){return e.collapsed?e:Ng(e)},kg=function(e,t){var n,r;return e.getBlockElements()[t.name]&&((r=t).firstChild&&r.firstChild===r.lastChild)&&("br"===(n=t.firstChild).name||n.value===oo)},_g=function(e,t){var n,r,o,i=t.firstChild,a=t.lastChild;return i&&"meta"===i.name&&(i=i.next),a&&"mce_marker"===a.attr("id")&&(a=a.prev),r=a,o=(n=e).getNonEmptyElements(),r&&(r.isEmpty(o)||kg(n,r))&&(a=a.prev),!(!i||i!==a)&&("ul"===i.name||"ol"===i.name)},Rg=function(e){return e&&e.firstChild&&e.firstChild===e.lastChild&&((t=e.firstChild).data===oo||In(t));var t},Tg=function(e){return 0<e.length&&(!(t=e[e.length-1]).firstChild||Rg(t))?e.slice(0,-1):e;var t},Ag=function(e,t){var n=e.getParent(t,e.isBlock);return n&&"LI"===n.nodeName?n:null},Dg=function(e,t){var n=Us.after(e),r=wl(t).prev(n);return r?r.toRange():null},Og=function(t,e,n){var r,o,i,a,u=t.parentNode;return xt.each(e,function(e){u.insertBefore(e,t)}),r=t,o=n,i=Us.before(r),(a=wl(o).next(i))?a.toRange():null},Bg=function(e,o,i,t){var n,r,a,u,s,c,l,f,d,m,p,g,h,v,y,b,C,w,x,S,N=(n=o,r=t,c=e.serialize(r),l=n.createFragment(c),u=(a=l).firstChild,s=a.lastChild,u&&"META"===u.nodeName&&u.parentNode.removeChild(u),s&&"mce_marker"===s.id&&s.parentNode.removeChild(s),a),E=Ag(o,i.startContainer),k=Tg((f=N.firstChild,xt.grep(f.childNodes,function(e){return"LI"===e.nodeName}))),_=o.getRoot(),R=function(e){var t=Us.fromRangeStart(i),n=wl(o.getRoot()),r=1===e?n.prev(t):n.next(t);return!r||Ag(o,r.getNode())!==E};return R(1)?Og(E,k,_):R(2)?(d=E,m=k,p=_,o.insertAfter(m.reverse(),d),Dg(m[0],p)):(h=k,v=_,y=g=E,C=(b=i).cloneRange(),w=b.cloneRange(),C.setStartBefore(y),w.setEndAfter(y),x=[C.cloneContents(),w.cloneContents()],(S=g.parentNode).insertBefore(x[0],g),xt.each(h,function(e){S.insertBefore(e,g)}),S.insertBefore(x[1],g),S.removeChild(g),Dg(h[h.length-1],v))},Pg=zn,Lg=function(e){var t=e.dom,n=Eg(e.selection.getRng());e.selection.setRng(n);var r,o,i,a=t.getParent(n.startContainer,Pg);r=t,o=n,null!==(i=a)&&i===r.getParent(o.endContainer,Pg)&&Af(Nt.fromDom(i),o)?mg(e,n,Nt.fromDom(a)):e.getDoc().execCommand("Delete",!1,null)},Ig=function(e,t,n){var r,o,i,a,u,s,c,l,f,d=e.selection,m=e.dom;/^ | $/.test(t)&&(s=m,c=d.getRng(),l=t,f=Nt.fromDom(s.getRoot()),l=Rp(f,Us.fromRangeStart(c))?l.replace(/^ /,"&nbsp;"):l.replace(/^&nbsp;/," "),t=l=Tp(f,Us.fromRangeEnd(c))?l.replace(/(&nbsp;| )(<br( \/)>)?$/,"&nbsp;"):l.replace(/&nbsp;(<br( \/)?>)?$/," "));var p=e.parser,g=n.merge,h=Tm({validate:e.getParam("validate")},e.schema),v='<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;</span>',y={content:t,format:"html",selection:!0,paste:n.paste};if((y=e.fire("BeforeSetContent",y)).isDefaultPrevented())e.fire("SetContent",{content:y.content,format:"html",selection:!0,paste:n.paste});else{-1===(t=y.content).indexOf("{$caret}")&&(t+="{$caret}"),t=t.replace(/\{\$caret\}/,v);var b,C,w=(a=d.getRng()).startContainer||(a.parentElement?a.parentElement():null),x=e.getBody();w===x&&d.isCollapsed()&&m.isBlock(x.firstChild)&&(b=e,(C=x.firstChild)&&!b.schema.getShortEndedElements()[C.nodeName])&&m.isEmpty(x.firstChild)&&((a=m.createRng()).setStart(x.firstChild,0),a.setEnd(x.firstChild,0),d.setRng(a)),d.isCollapsed()||Lg(e);var S,N,E,k,_,R,T,A,D,O,B,P,L,I,M={context:(r=d.getNode()).nodeName.toLowerCase(),data:n.data,insert:!0},F=p.parse(t,M);if(!0===n.paste&&_g(e.schema,F)&&Ag(m,r))return a=Bg(h,m,d.getRng(),F),d.setRng(a),void e.fire("SetContent",y);if(!function(e){for(var t=e;t=t.walk();)1===t.type&&t.attr("data-mce-fragment","1")}(F),"mce_marker"===(u=F.lastChild).attr("id"))for(u=(i=u).prev;u;u=u.walk(!0))if(3===u.type||!m.isBlock(u.name)){e.schema.isValidChild(u.parent.name,"span")&&u.parent.insert(i,u,"br"===u.name);break}if(e._selectionOverrides.showBlockCaretContainer(r),M.invalid){for(e.selection.setContent(v),r=d.getNode(),o=e.getBody(),9===r.nodeType?r=u=o:u=r;u!==o;)u=(r=u).parentNode;t=r===o?o.innerHTML:m.getOuterHTML(r),t=h.serialize(p.parse(t.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i,function(){return h.serialize(F)}))),r===o?m.setHTML(o,t):m.setOuterHTML(r,t)}else t=h.serialize(F),S=e,N=t,"all"===(E=r).getAttribute("data-mce-bogus")?E.parentNode.insertBefore(S.dom.createFragment(N),E):(k=E.firstChild,_=E.lastChild,!k||k===_&&"BR"===k.nodeName?S.dom.setHTML(E,N):S.selection.setContent(N));T=g,O=(R=e).schema.getTextInlineElements(),B=R.dom,T&&(A=R.getBody(),D=new zm(B),xt.each(B.select("*[data-mce-fragment]"),function(e){for(var t=e.parentNode;t&&t!==A;t=t.parentNode)O[e.nodeName.toLowerCase()]&&D.compare(t,e)&&B.remove(e,!0)})),function(n,e){var t,r,o=n.dom,i=n.selection;if(e){i.scrollIntoView(e);var a=function(e){for(var t=n.getBody();e&&e!==t;e=e.parentNode)if("false"===o.getContentEditable(e))return e;return null}(e);if(a)return o.remove(e),i.select(a);var u=o.createRng(),s=e.previousSibling;s&&3===s.nodeType?(u.setStart(s,s.nodeValue.length),vt.ie||(r=e.nextSibling)&&3===r.nodeType&&(s.appendData(r.data),r.parentNode.removeChild(r))):(u.setStartBefore(e),u.setEndBefore(e));var c=o.getParent(e,o.isBlock);o.remove(e),c&&o.isEmpty(c)&&(n.$(c).empty(),u.setStart(c,0),u.setEnd(c,0),Pg(c)||c.getAttribute("data-mce-fragment")||!(t=function(e){var t=Us.fromRangeStart(e);if(t=wl(n.getBody()).next(t))return t.toRange()}(u))?o.add(c,o.create("br",{"data-mce-bogus":"1"})):(u=t,o.remove(c))),i.setRng(u)}}(e,m.get("mce_marker")),P=e.getBody(),xt.each(P.getElementsByTagName("*"),function(e){e.removeAttribute("data-mce-fragment")}),L=m,I=d.getStart(),U.from(L.getParent(I,"td,th")).map(Nt.fromDom).each(op),e.fire("SetContent",y),e.addVisual()}},Mg=function(e,t){t(e),e.firstChild&&Mg(e.firstChild,t),e.next&&Mg(e.next,t)},Fg=function(e,t,n){var r=function(e,n,t){var r={},o={},i=[];for(var a in t.firstChild&&Mg(t.firstChild,function(t){$(e,function(e){e.name===t.name&&(r[e.name]?r[e.name].nodes.push(t):r[e.name]={filter:e,nodes:[t]})}),$(n,function(e){"string"==typeof t.attr(e.name)&&(o[e.name]?o[e.name].nodes.push(t):o[e.name]={filter:e,nodes:[t]})})}),r)r.hasOwnProperty(a)&&i.push(r[a]);for(var u in o)o.hasOwnProperty(u)&&i.push(o[u]);return i}(e,t,n);$(r,function(t){$(t.filter.callbacks,function(e){e(t.nodes,t.filter.name,{})})})},Ug=function(e){return e instanceof Em},zg=function(e,t){var r;e.dom.setHTML(e.getBody(),t),pm(r=e)&&Ol(r.getBody()).each(function(e){var t=e.getNode(),n=Tn(t)?Ol(t).getOr(e):e;r.selection.setRng(n.toRange())})},jg=function(u,s,c){return c.format=c.format?c.format:"html",c.set=!0,c.content=Ug(s)?"":s,Ug(s)||c.no_events||(u.fire("BeforeSetContent",c),s=c.content),U.from(u.getBody()).fold(N(s),function(e){return Ug(s)?function(e,t,n,r){Fg(e.parser.getNodeFilters(),e.parser.getAttributeFilters(),n);var o=Tm({validate:e.validate},e.schema).serialize(n);return r.content=no(Nt.fromDom(t))?o:xt.trim(o),zg(e,r.content),r.no_events||e.fire("SetContent",r),n}(u,e,s,c):(t=u,n=e,o=c,0===(r=s).length||/^\s+$/.test(r)?(a='<br data-mce-bogus="1">',"TABLE"===n.nodeName?r="<tr><td>"+a+"</td></tr>":/^(UL|OL)$/.test(n.nodeName)&&(r="<li>"+a+"</li>"),r=(i=fc(t))&&t.schema.isValidChild(n.nodeName.toLowerCase(),i.toLowerCase())?(r=a,t.dom.createHTML(i,dc(t),r)):r||'<br data-mce-bogus="1">',zg(t,r),t.fire("SetContent",o)):("raw"!==o.format&&(r=Tm({validate:t.validate},t.schema).serialize(t.parser.parse(r,{isRootContent:!0,insert:!0}))),o.content=no(Nt.fromDom(n))?r:xt.trim(r),zg(t,o.content),o.no_events||t.fire("SetContent",o)),o.content);var t,n,r,o,i,a})},Hg=nf,Vg=function(e,t,n){var r=e.formatter.get(n);if(r)for(var o=0;o<r.length;o++)if(!1===r[o].inherit&&e.dom.is(t,r[o].selector))return!0;return!1},qg=function(t,e,n,r){var o=t.dom.getRoot();return e!==o&&(e=t.dom.getParent(e,function(e){return!!Vg(t,e,n)||(e.parentNode===o||!!Kg(t,e,n,r,!0))}),Kg(t,e,n,r))},$g=function(e,t,n){return!!Hg(t,n.inline)||(!!Hg(t,n.block)||(n.selector?1===t.nodeType&&e.is(t,n.selector):void 0))},Wg=function(e,t,n,r,o,i){var a,u,s,c=n[r];if(n.onmatch)return n.onmatch(t,n,r);if(c)if("undefined"==typeof c.length){for(a in c)if(c.hasOwnProperty(a)){if(u="attributes"===r?e.getAttrib(t,a):of(e,t,a),o&&!u&&!n.exact)return;if((!o||n.exact)&&!Hg(u,rf(e,tf(c[a],i),a)))return}}else for(s=0;s<c.length;s++)if("attributes"===r?e.getAttrib(t,c[s]):of(e,t,c[s]))return n;return n},Kg=function(e,t,n,r,o){var i,a,u,s,c=e.formatter.get(n),l=e.dom;if(c&&t)for(a=0;a<c.length;a++)if(i=c[a],$g(e.dom,t,i)&&Wg(l,t,i,"attributes",o,r)&&Wg(l,t,i,"styles",o,r)){if(s=i.classes)for(u=0;u<s.length;u++)if(!e.dom.hasClass(t,s[u]))return;return i}},Xg=function(e,t,n,r){if(r)return qg(e,r,t,n);if(r=e.selection.getNode(),qg(e,r,t,n))return!0;var o=e.selection.getStart();return!(o===r||!qg(e,o,t,n))},Yg=function(r,o,i){var a=[],u={},e=r.selection.getStart();return r.dom.getParent(e,function(e){for(var t=0;t<o.length;t++){var n=o[t];!u[n]&&Kg(r,e,n,i)&&(u[n]=!0,a.push(n))}},r.dom.getRoot()),a},Gg=function(e,t){var n,r,o,i,a,u=e.formatter.get(t),s=e.dom;if(u)for(n=e.selection.getStart(),r=uf(s,n),i=u.length-1;0<=i;i--){if(!(a=u[i].selector)||u[i].defaultBlock)return!0;for(o=r.length-1;0<=o;o--)if(s.is(r[o],a))return!0}return!1},Jg=function(o,i,e){return W(e,function(e,t){var n,r=(n=t,M(o.formatter.get(n),function(t){var n=function(e){return 1<e.length&&"%"===e.charAt(0)};return M(["styles","attributes"],function(e){return de(t,e).exists(function(e){var t=S(e)?e:fe(e);return M(t,n)})})}));return o.formatter.matchNode(i,t,{},r)?e.concat([t]):e},[])},Qg=io,Zg="_mce_caret",eh=function(e){return 0<function(e){for(var t=[];e;){if(3===e.nodeType&&e.nodeValue!==Qg||1<e.childNodes.length)return[];1===e.nodeType&&t.push(e),e=e.firstChild}return t}(e).length},th=function(e){if(e){var t=new Hr(e,e);for(e=t.current();e;e=t.next())if(On(e))return e}return null},nh=function(e){var t=Nt.fromTag("span");return $n(t,{id:Zg,"data-mce-bogus":"1","data-mce-type":"format-caret"}),e&&un(t,Nt.fromText(Qg)),t},rh=function(e,t,n){void 0===n&&(n=!0);var r,o,i,a,u,s,c,l,f=e.dom,d=e.selection;eh(t)?Gp(e,!1,Nt.fromDom(t),n):(r=d.getRng(),o=f.getParent(t,f.isBlock),i=r.startContainer,a=r.startOffset,u=r.endContainer,s=r.endOffset,(l=th(t))&&l.nodeValue.charAt(0)===Qg&&l.deleteData(0,1),c=l,f.remove(t,!0),i===c&&0<a&&r.setStart(c,a-1),u===c&&0<s&&r.setEnd(c,s-1),o&&f.isEmpty(o)&&rp(Nt.fromDom(o)),d.setRng(r))},oh=function(e,t,n){void 0===n&&(n=!0);var r=e.dom,o=e.selection;if(t)rh(e,t,n);else if(!(t=Il(e.getBody(),o.getStart())))for(;t=r.get(Zg);)rh(e,t,!1)},ih=function(e,t){return e.appendChild(t),t},ah=function(e,t){var n=H(e,function(e,t){return ih(e,t.cloneNode(!1))},t);return ih(n,n.ownerDocument.createTextNode(Qg))},uh=function(e,t,n,r){var o,i,a,u,s,c,l,f,d,m,p,g,h,v=e.dom,y=e.selection,b=[],C=y.getRng(),w=C.startContainer,x=C.startOffset,S=w;for(3===w.nodeType&&(x!==w.nodeValue.length&&(o=!0),S=S.parentNode);S;){if(Kg(e,S,t,n,r)){i=S;break}S.nextSibling&&(o=!0),b.push(S),S=S.parentNode}i&&(o?(a=y.getBookmark(),C.collapse(!0),u=wf(e,C,e.formatter.get(t),!0),u=cd(u),e.formatter.remove(t,n,u,r),y.moveToBookmark(a)):(s=Il(e.getBody(),i),c=nh(!1).dom,m=c,p=null!==s?s:i,g=(d=e).dom,(h=g.getParent(p,E(Ql,d)))&&g.isEmpty(h)?p.parentNode.replaceChild(m,p):(np(Nt.fromDom(p)),g.isEmpty(p)?p.parentNode.replaceChild(m,p):g.insertAfter(m,p)),l=function(t,e,n,r,o,i){var a=t.formatter,u=t.dom,s=j(ne(a.get()),function(e){return e!==r&&!Fe(e,"removeformat")}),c=Jg(t,n,s);if(0<j(c,function(e){return!sf(t,e,r)}).length){var l=n.cloneNode(!1);return u.add(e,l),a.remove(r,o,l,i),u.remove(l),U.some(l)}return U.none()}(e,c,i,t,n,r),f=ah(b.concat(l.toArray()),c),rh(e,s,!1),y.setCursorLocation(f,1),v.isEmpty(i)&&v.remove(i)))},sh=function(i){i.on("mouseup keydown",function(e){var t,n,r,o;t=i,n=e.keyCode,r=t.selection,o=t.getBody(),oh(t,null,!1),8!==n&&46!==n||!r.isCollapsed()||r.getStart().innerHTML!==Qg||oh(t,Il(o,r.getStart())),37!==n&&39!==n||oh(t,Il(o,r.getStart()))})},ch=function(e,t){return e.schema.getTextInlineElements().hasOwnProperty(Dt(t))&&!Ll(t.dom)&&!Rn(t.dom)},lh={},fh=ve,dh=ge;Pm=function(e){var t,n=e.selection.getRng(),r=En(["pre"]);n.collapsed||(t=e.selection.getSelectedBlocks(),dh(fh(fh(t,r),function(e){return r(e.previousSibling)&&-1!==ye(t,e.previousSibling)}),function(e){var t,n;t=e.previousSibling,lu(n=e).remove(),lu(t).append("<br><br>").append(n.childNodes)}))},lh[Bm="pre"]||(lh[Bm]=[]),lh[Bm].push(Pm);var mh=xt.each,ph=function(e){return Nn(e)&&!$l(e)&&!Ll(e)&&!Rn(e)},gh=function(e,t){for(var n=e;n;n=n[t]){if(On(n)&&0!==n.nodeValue.length)return e;if(Nn(n)&&!$l(n))return n}return e},hh=function(e,t,n){var r,o,i=new zm(e);if(t&&n&&(t=gh(t,"previousSibling"),n=gh(n,"nextSibling"),i.compare(t,n))){for(r=t.nextSibling;r&&r!==n;)r=(o=r).nextSibling,t.appendChild(o);return e.remove(n),xt.each(xt.grep(n.childNodes),function(e){t.appendChild(e)}),t}return n},vh=function(e,t,n,r){var o;r&&!1!==t.merge_siblings&&(o=hh(e,Jl(r),r),hh(e,o,Jl(o,!0)))},yh=function(e,t,n){mh(e.childNodes,function(e){ph(e)&&(t(e)&&n(e),e.hasChildNodes()&&yh(e,t,n))})},bh=function(t,n){return function(e){return!(!e||!of(t,e,n))}},Ch=function(r,o,i){return function(e){var t,n;r.setStyle(e,o,i),""===e.getAttribute("style")&&e.removeAttribute("style"),t=r,"SPAN"===(n=e).nodeName&&0===t.getAttribs(n).length&&t.remove(n,!0)}},wh=gr([{keep:[]},{rename:["name"]},{removed:[]}]),xh=/^(src|href|style)$/,Sh=xt.each,Nh=nf,Eh=function(e,t,n){return e.isChildOf(t,n)&&t!==n&&!e.isBlock(n)},kh=function(e,t,n){var r,o=t[n?"startContainer":"endContainer"],i=t[n?"startOffset":"endOffset"];return Nn(o)&&(r=o.childNodes.length-1,!n&&i&&i--,o=o.childNodes[r<i?r:i]),On(o)&&n&&i>=o.nodeValue.length&&(o=new Hr(o,e.getBody()).next()||o),On(o)&&!n&&0===i&&(o=new Hr(o,e.getBody()).prev()||o),o},_h=function(e,t){var n=t?"firstChild":"lastChild";if(/^(TR|TH|TD)$/.test(e.nodeName)&&e[n]){var r=e[n];return"TR"===e.nodeName&&r[n]||r}return e},Rh=function(e,t,n,r){var o=e.create(n,r);return t.parentNode.insertBefore(o,t),o.appendChild(t),o},Th=function(e,t,n,r,o){var i=Nt.fromDom(t),a=Nt.fromDom(e.create(r,o)),u=(n?$t:qt)(i);return sn(a,u),n?(rn(i,a),an(a,i)):(on(i,a),un(a,i)),a.dom},Ah=function(e,t,n,r){return!(t=Jl(t,n,r))||"BR"===t.nodeName||e.isBlock(t)},Dh=function(e,r,o,t,i){var n,a,u,s,c,l=e.dom;if(u=l,!(Nh(s=t,(c=r).inline)||Nh(s,c.block)||c.selector&&(Nn(s)&&u.is(s,c.selector))||(a=t,r.links&&"A"===a.nodeName)))return wh.keep();var f,d,m,p,g,h,v,y=t;if(r.inline&&"all"===r.remove&&S(r.preserve_attributes)){var b=j(l.getAttribs(y),function(e){return I(r.preserve_attributes,e.name.toLowerCase())});if(l.removeAllAttribs(y),$(b,function(e){return l.setAttrib(y,e.name,e.value)}),0<b.length)return wh.rename("span")}if("all"!==r.remove){Sh(r.styles,function(e,t){e=rf(l,tf(e,o),t+""),D(t)&&(t=e,i=null),!r.remove_similar&&i&&!Nh(of(l,i,t),e)||l.setStyle(y,t,""),n=!0}),n&&""===l.getAttrib(y,"style")&&(y.removeAttribute("style"),y.removeAttribute("data-mce-style")),Sh(r.attributes,function(e,t){var n;if(e=tf(e,o),D(t)&&(t=e,i=null),r.remove_similar||!i||Nh(l.getAttrib(i,t),e)){if("class"===t&&(e=l.getAttrib(y,t))&&(n="",$(e.split(/\s+/),function(e){/mce\-\w+/.test(e)&&(n+=(n?" ":"")+e)}),n))return void l.setAttrib(y,t,n);"class"===t&&y.removeAttribute("className"),xh.test(t)&&y.removeAttribute("data-mce-"+t),y.removeAttribute(t)}}),Sh(r.classes,function(e){e=tf(e,o),i&&!l.hasClass(i,e)||l.removeClass(y,e)});for(var C=l.getAttribs(y),w=0;w<C.length;w++){var x=C[w].nodeName;if(0!==x.indexOf("_")&&0!==x.indexOf("data-"))return wh.keep()}}return"none"!==r.remove?(f=e,m=r,g=(d=y).parentNode,h=f.dom,v=fc(f),m.block&&(v?g===h.getRoot()&&(m.list_block&&Nh(d,m.list_block)||$(te(d.childNodes),function(e){Zl(f,v,e.nodeName.toLowerCase())?p?p.appendChild(e):(p=Rh(h,e,v),h.setAttribs(p,f.settings.forced_root_block_attrs)):p=0})):h.isBlock(d)&&!h.isBlock(g)&&(Ah(h,d,!1)||Ah(h,d.firstChild,!0,!0)||d.insertBefore(h.create("br"),d.firstChild),Ah(h,d,!0)||Ah(h,d.lastChild,!1,!0)||d.appendChild(h.create("br")))),m.selector&&m.inline&&!Nh(m.inline,d)||h.remove(d,!0),wh.removed()):wh.keep()},Oh=function(t,e,n,r,o){return Dh(t,e,n,r,o).fold(p,function(e){return t.dom.rename(r,e),!0},k)},Bh=function(e,t,n,r,o,i,a,u){var s,c,l,f=e.dom;if(n){for(var d=n.parentNode,m=r.parentNode;m&&m!==d;m=m.parentNode){s=f.clone(m,!1);for(var p=0;p<t.length&&null!==(s=function(t,e,n,r){return Dh(t,e,n,r,r).fold(N(r),function(e){return t.dom.createFragment().appendChild(r),t.dom.rename(r,e)},N(null))}(e,t[p],u,s));p++);s&&(c&&s.appendChild(c),l=l||s,c=s)}!i||a.mixed&&f.isBlock(n)||(r=f.split(n,r)),c&&(o.parentNode.insertBefore(c,o),l.appendChild(o),a.inline&&vh(f,a,0,c))}return r},Ph=function(s,c,l,e,f){var t,d=s.formatter.get(c),m=d[0],i=!0,a=s.dom,n=s.selection,u=function(e){var n,t,r,o,i,a,u=(t=e,r=c,o=l,i=f,$(uf((n=s).dom,t.parentNode).reverse(),function(e){var t;a||"_start"===e.id||"_end"===e.id||(t=Kg(n,e,r,o,i))&&!1!==t.split&&(a=e)}),a);return Bh(s,d,u,e,e,!0,m,l)},p=function(e){var t,n;Nn(e)&&a.getContentEditable(e)&&(t=i,i="true"===a.getContentEditable(e),n=!0);var r=te(e.childNodes);if(i&&!n)for(var o=0;o<d.length&&!Oh(s,d[o],l,e,e);o++);if(m.deep&&r.length){for(o=0;o<r.length;o++)p(r[o]);n&&(i=t)}},g=function(e){var t,n=a.get(e?"_start":"_end"),r=n[e?"firstChild":"lastChild"];return $l(t=r)&&Nn(t)&&("_start"===t.id||"_end"===t.id)&&(r=r[e?"firstChild":"lastChild"]),On(r)&&0===r.data.length&&(r=e?n.previousSibling||n.nextSibling:n.nextSibling||n.previousSibling),a.remove(n,!0),r},r=function(e){var t,n,r=wf(s,e,d,!0);if(m.split){if(r=cd(r),(t=kh(s,r,!0))!==(n=kh(s,r))){if(t=_h(t,!0),n=_h(n,!1),Eh(a,t,n)){var o=U.from(t.firstChild).getOr(t);return u(Th(a,o,!0,"span",{id:"_start","data-mce-type":"bookmark"})),void g(!0)}if(Eh(a,n,t)){o=U.from(n.lastChild).getOr(n);return u(Th(a,o,!1,"span",{id:"_end","data-mce-type":"bookmark"})),void g(!1)}t=Rh(a,t,"span",{id:"_start","data-mce-type":"bookmark"}),n=Rh(a,n,"span",{id:"_end","data-mce-type":"bookmark"});var i=a.createRng();i.setStartAfter(t),i.setEndBefore(n),Sf(a,i,function(e){$(e,function(e){$l(e)||$l(e.parentNode)||u(e)})}),u(t),u(n),t=g(!0),n=g()}else t=n=u(t);r.startContainer=t.parentNode?t.parentNode:t,r.startOffset=a.nodeIndex(t),r.endContainer=n.parentNode?n.parentNode:n,r.endOffset=a.nodeIndex(n)+1}Sf(a,r,function(e){$(e,function(t){p(t);$(["underline","line-through","overline"],function(e){Nn(t)&&s.dom.getStyle(t,"text-decoration")===e&&t.parentNode&&af(a,t.parentNode)===e&&Oh(s,{deep:!1,exact:!0,inline:"span",styles:{textDecoration:e}},null,t)})})})};if(e)Yl(e)?((t=a.createRng()).setStartBefore(e),t.setEndAfter(e),r(t)):r(e);else if("false"!==a.getContentEditable(n.getNode()))n.isCollapsed()&&m.inline&&!_f(s).length?uh(s,c,l,f):(Pf(n,!0,function(){Bf(s,r)}),m.inline&&Xg(s,c,l,n.getStart())&&Gl(a,n,n.getRng()),s.nodeChanged());else{e=n.getNode();for(var o=0;o<d.length&&(!d[o].ceFalseOverride||!Oh(s,d[o],l,e,e));o++);}},Lh=xt.each,Ih=function(i,e,a,u){Lh(e,function(t){var r,e,n,o;Lh(i.dom.select(t.inline,u),function(e){ph(e)&&Oh(i,t,a,e,t.exact?e:null)}),r=i.dom,n=u,(e=t).clear_child_styles&&(o=e.links?"*:not(a)":"*",mh(r.select(o,n),function(n){ph(n)&&mh(e.styles,function(e,t){r.setStyle(n,t,"")})}))})},Mh=xt.each,Fh=function(E,k,_,r){var e,t,n,R=E.formatter.get(k),T=R[0],o=!r&&E.selection.isCollapsed(),i=E.dom,a=E.selection,A=function(n,e){var t;e=e||T,n&&(e.onformat&&e.onformat(n,e,_,r),Mh(e.styles,function(e,t){i.setStyle(n,t,tf(e,_))}),!e.styles||(t=i.getAttrib(n,"style"))&&i.setAttrib(n,"data-mce-style",t),Mh(e.attributes,function(e,t){i.setAttrib(n,t,tf(e,_))}),Mh(e.classes,function(e){e=tf(e,_),i.hasClass(n,e)||i.addClass(n,e)}))},m=function(e,t){var n=!1;return!!T.selector&&(Mh(e,function(e){if(!("collapsed"in e&&e.collapsed!==o))return i.is(t,e.selector)&&!Ll(t)?(A(t,e),!(n=!0)):void 0}),n)},u=function(S,e,t,c){var N=[],l=!0,f=T.inline||T.block,d=S.create(f);A(d),Sf(S,e,function(e){var u,s=function(e){var t=!1,n=l,r=e.nodeName.toLowerCase(),o=e.parentNode.nodeName.toLowerCase();if(Nn(e)&&S.getContentEditable(e)&&(n=l,l="true"===S.getContentEditable(e),t=!0),nf(r,"br"))return u=0,void(T.block&&S.remove(e));if(T.wrapper&&Kg(E,e,k,_))u=0;else{if(l&&!t&&T.block&&!T.wrapper&&Ql(E,r)&&Zl(E,o,f)){var i=S.rename(e,f);return A(i),N.push(i),void(u=0)}if(T.selector){var a=m(R,e);if(!T.inline||a)return void(u=0)}!l||t||!Zl(E,f,r)||!Zl(E,o,f)||!c&&3===e.nodeType&&1===e.nodeValue.length&&65279===e.nodeValue.charCodeAt(0)||Ll(e)||T.inline&&S.isBlock(e)?(u=0,Mh(xt.grep(e.childNodes),s),t&&(l=n),u=0):(u||(u=S.clone(d,!1),e.parentNode.insertBefore(u,e),N.push(u)),u.appendChild(e))}};Mh(e,s)}),!0===T.links&&Mh(N,function(e){var t=function(e){"A"===e.nodeName&&A(e,T),Mh(xt.grep(e.childNodes),t)};t(e)}),Mh(N,function(e){var n,t,r,o,i,a,u,s,c,l,f,d,m,p,g,h,v,y,b,C,w=function(e){var n=!1;return Mh(e.childNodes,function(e){if((t=e)&&1===t.nodeType&&!$l(t)&&!Ll(t)&&!Rn(t))return n=e,!1;var t}),n},x=(n=0,Mh(e.childNodes,function(e){var t;(t=e)&&On(t)&&0===t.length||$l(e)||n++}),n);!(1<N.length)&&S.isBlock(e)||0!==x?(T.inline||T.wrapper)&&(T.exact||1!==x||((C=w(y=e))&&!$l(C)&&$g(S,C,T)&&(b=S.clone(C,!1),A(b),S.replace(b,y,!0),S.remove(C,!0)),e=b||y),Ih(E,R,_,e),p=T,g=k,h=_,Kg(m=E,(v=e).parentNode,g,h)&&Oh(m,p,h,v)||p.merge_with_parents&&m.dom.getParent(v.parentNode,function(e){if(Kg(m,e,g,h))return Oh(m,p,h,v),!0}),c=S,f=_,d=e,(l=T).styles&&l.styles.backgroundColor&&yh(d,bh(c,"fontSize"),Ch(c,"backgroundColor",tf(l.styles.backgroundColor,f))),i=S,u=e,s=function(e){var t;1===e.nodeType&&e.parentNode&&1===e.parentNode.nodeType&&(t=af(i,e.parentNode),i.getStyle(e,"color")&&t?i.setStyle(e,"text-decoration",t):i.getStyle(e,"text-decoration")===t&&i.setStyle(e,"text-decoration",null))},(a=T).styles&&(a.styles.color||a.styles.textDecoration)&&(xt.walk(u,s,"childNodes"),s(u)),t=S,o=e,"sub"!==(r=T).inline&&"sup"!==r.inline||(yh(o,bh(t,"fontSize"),Ch(t,"fontSize","")),t.remove(t.select("sup"===r.inline?"sub":"sup",o),!0)),vh(S,T,0,e)):S.remove(e,!0)})};if("false"!==i.getContentEditable(a.getNode())){T&&(r?Yl(r)?m(R,r)||((e=i.createRng()).setStartBefore(r),e.setEndAfter(r),u(i,wf(E,e,R),0,!0)):u(i,r,0,!0):o&&T.inline&&!_f(E).length?function(e,t,n){var r,o=e.selection,i=o.getRng(),a=i.startOffset,u=i.startContainer.nodeValue,s=Il(e.getBody(),o.getStart());s&&(r=th(s));var c,l,f,d,m=/[^\s\u00a0\u00ad\u200b\ufeff]/;u&&0<a&&a<u.length&&m.test(u.charAt(a))&&m.test(u.charAt(a-1))?(c=o.getBookmark(),i.collapse(!0),l=wf(e,i,e.formatter.get(t)),l=cd(l),e.formatter.apply(t,n,l),o.moveToBookmark(c)):(s&&r.nodeValue===Qg||(f=e.getDoc(),d=nh(!0).dom,r=(s=f.importNode(d,!0)).firstChild,i.insertNode(s),a=1),e.formatter.apply(t,n,s),o.setCursorLocation(r,a))}(E,k,_):(t=a.getNode(),E.settings.forced_root_block||!R[0].defaultBlock||i.getParent(t,i.isBlock)||Fh(E,R[0].defaultBlock),a.setRng(Eg(a.getRng())),Pf(a,!0,function(e){Bf(E,function(e,t){var n=t?e:wf(E,e,R);u(i,n)})}),Gl(i,a,a.getRng()),E.nodeChanged()),n=E,dh(lh[k],function(e){e(n)}))}else{r=a.getNode();for(var s=0,c=R.length;s<c;s++)if(R[s].ceFalseOverride&&i.is(r,R[s].selector))return void A(r,R[s])}},Uh=function(e,t){var n=(t||document).createDocumentFragment();return $(e,function(e){n.appendChild(e.dom)}),Nt.fromDom(n)},zh=function(e,t,n){return{element:e,width:t,rows:n}},jh=function(e,t){return{element:e,cells:t}},Hh=function(e,t){var n=parseInt(Wn(e,t),10);return isNaN(n)?1:n},Vh=function(e){return W(e,function(e,t){return t.cells.length>e?t.cells.length:e},0)},qh=function(e,t){for(var n=e.rows,r=0;r<n.length;r++)for(var o=n[r].cells,i=0;i<o.length;i++)if(Rt(o[i],t))return U.some({x:i,y:r});return U.none()},$h=function(e,t,n,r,o){for(var i=[],a=e.rows,u=n;u<=o;u++){var s=a[u].cells,c=t<r?s.slice(t,r+1):s.slice(r,t+1);i.push(jh(a[u].element,c))}return i},Wh=function(e){var o=zh(ns(e),0,[]);return $(qu(e,"tr"),function(n,r){$(qu(n,"td,th"),function(e,t){!function(e,t,n,r,o){for(var i=Hh(o,"rowspan"),a=Hh(o,"colspan"),u=e.rows,s=n;s<n+i;s++){u[s]||(u[s]=jh(rs(r),[]));for(var c=t;c<t+a;c++){u[s].cells[c]=s===n&&c===t?o:ns(o)}}}(o,function(e,t,n){for(;r=t,o=n,((i=e.rows)[o]?i[o].cells:[])[r];)t++;var r,o,i;return t}(o,t,r),r,n,e)})}),zh(o.element,Vh(o.rows),o.rows)},Kh=function(e){return n=F((t=e).rows,function(e){var t=F(e.cells,function(e){var t=rs(e);return Kn(t,"colspan"),Kn(t,"rowspan"),t}),n=ns(e.element);return sn(n,t),n}),r=ns(t.element),o=Nt.fromTag("tbody"),sn(o,n),un(r,o),r;var t,n,r,o},Xh=function(l,e,t){return qh(l,e).bind(function(c){return qh(l,t).map(function(e){return t=l,r=e,o=(n=c).x,i=n.y,a=r.x,u=r.y,s=i<u?$h(t,o,i,a,u):$h(t,o,u,a,i),zh(t.element,Vh(s),s);var t,n,r,o,i,a,u,s})})},Yh=function(t,n){return K(t,function(e){return"li"===Dt(e)&&Af(e,n)}).fold(N([]),function(e){return K(t,function(e){return"ul"===Dt(e)||"ol"===Dt(e)}).map(function(e){var t=Nt.fromTag(Dt(e)),n=le(Qn(e),function(e,t){return Ue(t,"list-style")});return Xn(t,n),[Nt.fromTag("li"),t]}).getOr([])})},Gh=function(e,t){var n,r=Nt.fromDom(t.commonAncestorContainer),o=up(r,e),i=j(o,function(e){return Yr(e)||Kr(e)}),a=Yh(o,t),u=i.concat(a.length?a:Zr(n=r)?jt(n).filter(Qr).fold(N([]),function(e){return[n,e]}):Qr(n)?[n]:[]);return F(u,ns)},Jh=function(){return Uh([])},Qh=function(e,t){return n=Nt.fromDom(t.cloneContents()),r=Gh(e,t),o=W(r,function(e,t){return un(t,e),t},n),0<r.length?Uh([o]):o;var n,r,o},Zh=function(e,o){return t=e,n=o[0],Nr(n,"table",E(Rt,t)).bind(function(e){var t=o[0],n=o[o.length-1],r=Wh(e);return Xh(r,t,n).map(function(e){return Uh([Kh(e)])})}).getOrThunk(Jh);var t,n},ev=function(e,t){var n,r,o=kf(t,e);return 0<o.length?Zh(e,o):(n=e,0<(r=t).length&&r[0].collapsed?Jh():Qh(n,r[0]))},tv=function(e,t){return 0<=t&&t<e.length&&Kl(e.charAt(t))},nv=function(e){var t=uo(e.innerText);return vt.browser.isIE()?t.replace(/^[ \f\n\r\t\v]+/,""):t},rv=function(e,t,n){if(void 0===n&&(n={}),n.get=!0,n.format=t,n.selection=!0,(n=e.fire("BeforeGetContent",n)).isDefaultPrevented())return e.fire("GetContent",n),n.content;if("text"===n.format)return l=e,U.from(l.selection.getRng()).map(function(e){var t=l.dom.add(l.getBody(),"div",{"data-mce-bogus":"all",style:"overflow: hidden; opacity: 0;"},e.cloneContents()),n=nv(t),r=uo(t.textContent);if(l.dom.remove(t),tv(r,0)||tv(r,r.length-1)){var o=l.dom.getParent(e.commonAncestorContainer,l.dom.isBlock),i=nv(o),a=i.indexOf(n);return-1===a?n:(tv(i,a-1)?" ":"")+n+(tv(i,a+n.length)?" ":"")}return n}).getOr("");n.getInner=!0;var r,o,i,a,u,s,c,l,f=(o=n,i=(r=e).selection.getRng(),a=r.dom.create("body"),u=r.selection.getSel(),s=wm(r,Nf(u)),(c=o.contextual?ev(Nt.fromDom(r.getBody()),s).dom:i.cloneContents())&&a.appendChild(c),r.selection.serializer.serialize(a,o));return"tree"===n.format?f:(n.content=e.selection.isCollapsed()?"":f,e.fire("GetContent",n),n.content)},ov=function(e){return Nn(e)?e.outerHTML:On(e)?ri.encodeRaw(e.data,!1):Bn(e)?"\x3c!--"+e.data+"--\x3e":""},iv=function(e,t,n){var r,o=function(e){var t,n=document.createElement("div"),r=document.createDocumentFragment();for(e&&(n.innerHTML=e);t=n.firstChild;)r.appendChild(t);return r}(t);e.hasChildNodes()&&n<e.childNodes.length?(r=e.childNodes[n]).parentNode.insertBefore(o,r):e.appendChild(o)},av=function(e,o){var i=0;$(e,function(e){var t,n,r;0===e[0]?i++:1===e[0]?(iv(o,e[1],i),i++):2===e[0]&&(n=i,(t=o).hasChildNodes()&&n<t.childNodes.length&&(r=t.childNodes[n]).parentNode.removeChild(r))})},uv=function(e,t){var p,g,n,h,v,c,y,l,r,o=F(te(t.childNodes),ov);return av((g=e,n=(p=o).length+g.length+2,h=new Array(n),v=new Array(n),c=function(e,t,n,r,o){var i=l(e,t,n,r);if(null===i||i.start===t&&i.diag===t-r||i.end===e&&i.diag===e-n)for(var a=e,u=n;a<t||u<r;)a<t&&u<r&&p[a]===g[u]?(o.push([0,p[a]]),++a,++u):r-n<t-e?(o.push([2,p[a]]),++a):(o.push([1,g[u]]),++u);else{c(e,i.start,n,i.start-i.diag,o);for(var s=i.start;s<i.end;++s)o.push([0,p[s]]);c(i.end,t,i.end-i.diag,r,o)}},y=function(e,t,n,r){for(var o=e;o-t<r&&o<n&&p[o]===g[o-t];)++o;return{start:e,end:o,diag:t}},l=function(e,t,n,r){var o=t-e,i=r-n;if(0==o||0==i)return null;var a,u,s,c,l,f=o-i,d=i+o,m=(d%2==0?d:1+d)/2;for(h[1+m]=e,v[1+m]=t+1,a=0;a<=m;++a){for(u=-a;u<=a;u+=2){for(s=u+m,u===-a||u!==a&&h[s-1]<h[s+1]?h[s]=h[s+1]:h[s]=h[s-1]+1,l=(c=h[s])-e+n-u;c<t&&l<r&&p[c]===g[l];)h[s]=++c,++l;if(f%2!=0&&f-a<=u&&u<=f+a&&v[s-f]<=h[s])return y(v[s-f],u+e-n,t,r)}for(u=f-a;u<=f+a;u+=2){for(s=u+m-f,u===f-a||u!==f+a&&v[s+1]<=v[s-1]?v[s]=v[s+1]-1:v[s]=v[s-1],l=(c=v[s]-1)-e+n-u;e<=c&&n<=l&&p[c]===g[l];)v[s]=c--,l--;if(f%2==0&&-a<=u&&u<=a&&v[s]<=h[s+f])return y(v[s],u+e-n,t,r)}}},r=[],c(0,p.length,0,g.length,r),r),t),t},sv=ku(U.none()),cv=function(n){var e,t=(e=n.getBody(),j(F(te(e.childNodes),ov),function(e){return 0<e.length})),r=Y(t,function(e){var t=Im(n.serializer,e);return 0<t.length?[t]:[]}),o=r.join("");return-1!==o.indexOf("</iframe>")?{type:"fragmented",fragments:r,content:"",bookmark:null,beforeBookmark:null}:{type:"complete",fragments:null,content:o,bookmark:null,beforeBookmark:null}},lv=function(e,t,n){"fragmented"===t.type?uv(t.fragments,e.getBody()):e.setContent(t.content,{format:"raw"}),e.selection.moveToBookmark(n?t.beforeBookmark:t.bookmark)},fv=function(e){return"fragmented"===e.type?e.fragments.join(""):e.content},dv=function(e){var t=Nt.fromTag("body",sv.get().getOrThunk(function(){var e=document.implementation.createHTMLDocument("undo");return sv.set(U.some(e)),e}));return es(t,fv(e)),$(qu(t,"*[data-mce-bogus]"),fn),t.dom.innerHTML},mv=function(e,t){return!(!e||!t)&&(r=t,fv(e)===fv(r)||(n=t,dv(e)===dv(n)));var n,r},pv=function(e){return 0===e.get()},gv=function(e,t,n){pv(n)&&(e.typing=t)},hv=function(e,t){e.typing&&(gv(e,!1,t),e.add())},vv=function(e){return e instanceof Em},yv=function(e,t){Fg(e.serializer.getNodeFilters(),e.serializer.getAttributeFilters(),t)},bv=function(){return{type:"complete",fragments:[],content:"",bookmark:null,beforeBookmark:null}},Cv=function(f){return{undoManager:{beforeChange:function(e,t){return n=f,r=t,void(pv(e)&&r.set(U.some(uc(n.selection))));var n,r},addUndoLevel:function(e,t,n,r,o,i){return function(e,t,n,r,o,i,a){var u=cv(e);if(i=i||{},i=xt.extend(i,u),!1===pv(r)||e.removed)return null;var s=t.data[n.get()];if(e.fire("BeforeAddUndo",{level:i,lastLevel:s,originalEvent:a}).isDefaultPrevented())return null;if(s&&mv(s,i))return null;t.data[n.get()]&&o.get().each(function(e){t.data[n.get()].beforeBookmark=e});var c=e.getParam("custom_undo_redo_levels",0,"number");if(c&&t.data.length>c){for(var l=0;l<t.data.length-1;l++)t.data[l]=t.data[l+1];t.data.length--,n.set(t.data.length)}i.bookmark=uc(e.selection),n.get()<t.data.length-1&&(t.data.length=n.get()+1),t.data.push(i),n.set(t.data.length-1);var f={level:i,lastLevel:s,originalEvent:a};return 0<n.get()?(e.setDirty(!0),e.fire("AddUndo",f),e.fire("change",f)):e.fire("AddUndo",f),i}(f,e,t,n,r,o,i)},undo:function(e,t,n){return r=f,i=t,a=n,(o=e).typing&&(o.add(),o.typing=!1,gv(o,!1,i)),0<a.get()&&(a.set(a.get()-1),u=o.data[a.get()],lv(r,u,!0),r.setDirty(!0),r.fire("Undo",{level:u})),u;var r,o,i,a,u},redo:function(e,t){return n=f,o=t,(r=e).get()<o.length-1&&(r.set(r.get()+1),i=o[r.get()],lv(n,i,!1),n.setDirty(!0),n.fire("Redo",{level:i})),i;var n,r,o,i},clear:function(e,t){return n=f,o=t,(r=e).data=[],o.set(0),r.typing=!1,void n.fire("ClearUndos");var n,r,o},reset:function(e){return(t=e).clear(),void t.add();var t},hasUndo:function(e,t){return n=f,r=e,0<t.get()||r.typing&&r.data[0]&&!mv(cv(n),r.data[0]);var n,r},hasRedo:function(e,t){return n=e,t.get()<n.data.length-1&&!n.typing;var n},transact:function(e,t,n){return o=n,hv(r=e,t),r.beforeChange(),r.ignore(o),r.add();var r,o},ignore:function(e,t){try{e.set(e.get()+1),t()}finally{e.set(e.get()-1)}},extra:function(e,t,n,r){return o=f,a=t,u=n,s=r,void((i=e).transact(u)&&(c=i.data[a.get()].bookmark,l=i.data[a.get()-1],lv(o,l,!0),i.transact(s)&&(i.data[a.get()-1].beforeBookmark=c)));var o,i,a,u,s,c,l}},formatter:{apply:function(e,t,n){return Fh(f,e,t,n)},remove:function(e,t,n,r){return Ph(f,e,t,n,r)},toggle:function(e,t,n){return o=e,i=t,a=n,u=(r=f).formatter.get(o),void(!Xg(r,o,i,a)||"toggle"in u[0]&&!u[0].toggle?Fh:Ph)(r,o,i,a);var r,o,i,a,u}},editor:{getContent:function(e,t){return n=f,r=e,o=t,U.from(n.getBody()).fold(N("tree"===r.format?new Em("body",11):""),function(e){return Fm(n,r,o,e)});var n,r,o},setContent:function(e,t){return jg(f,e,t)},insertContent:function(e,t){return Ig(f,e,t)}},selection:{getContent:function(e,t){return rv(f,e,t)}},raw:{getModel:function(){return U.none()}}}},wv=function(i,a){var o=function(e){return _(e)?e:{}},e=m("Unimplemented feature for rtc");return{undoManager:{beforeChange:V,addUndoLevel:e,undo:function(){return a.undo(),bv()},redo:function(){return a.redo(),bv()},clear:e,reset:e,hasUndo:function(){return a.hasUndo()},hasRedo:function(){return a.hasRedo()},transact:function(e,t,n){return a.transact(n),bv()},ignore:e,extra:e},formatter:{apply:function(e,t,n){return a.applyFormat(e,o(t))},remove:function(e,t,n,r){return a.removeFormat(e,o(t))},toggle:function(e,t,n){return a.toggleFormat(e,o(t))}},editor:{getContent:function(e,t){if("html"!==t&&"tree"!==t)return Cv(i).editor.getContent(e,t);var n=a.getContent(),r=Tm({inner:!0});return yv(i,n),"tree"===t?n:r.serialize(n)},setContent:function(e,t){var n=vv(e)?e:i.parser.parse(e,{isRootContent:!0,insert:!0});return a.setContent(n),e},insertContent:function(e,t){var n,r=(n=i,U.from(n.selection.getStart(!0)).map(function(e){return e.nodeName.toLowerCase()}).fold(function(){return{}},function(e){return{context:e}})),o=vv(e)?e:i.parser.parse(e,xe(xe({},r),{insert:!0}));a.insertContent(o)}},selection:{getContent:function(e,t){if("html"!==e&&"tree"!==e)return Cv(i).selection.getContent(e,t);var n=a.getSelectedContent(),r=Tm({});return yv(i,n),"tree"===e?n:r.serialize(n)}},raw:{getModel:function(){return U.some(a.getRawModel())}}}},xv=function(e){return me(e.plugins,"rtc")},Sv=function(e){return e.rtcInstance?e.rtcInstance:Cv(e)},Nv=function(e){var t=e.rtcInstance;if(t)return t;throw new Error("Failed to get RTC instance not yet initialized.")},Ev=function(e,t){void 0===t&&(t={});var n,r,o=t.format?t.format:"html";return n=o,r=t,Nv(e).selection.getContent(n,r)},kv=function(e){return 0===e.dom.length?(ln(e),U.none()):U.some(e)},_v=function(e,t,s,c){e.bind(function(u){return(c?Fp:Mp)(u.dom,c?u.dom.length:0),t.filter(Lt).map(function(e){return t=e,n=s,r=c,o=u.dom,i=t.dom,a=r?o.length:i.length,void(r?(Up(o,i,!1,!r),n.setStart(i,a)):(Up(i,o,!1,!r),n.setEnd(i,a)));var t,n,r,o,i,a})}).orThunk(function(){var e;return(e=c,t.filter(function(e){return Kf.isBookmarkNode(e.dom)}).bind(e?Vt:Ht).or(t).filter(Lt)).map(function(e){return r=c,void jt(n=e).each(function(e){var t=n.dom;r&&Rp(e,Us(t,0))?Mp(t,0):!r&&Tp(e,Us(t,t.length))&&Fp(t,t.length)});var n,r})})},Rv=function(e,t,n){void 0===n&&(n={});var r,o,i=(r=t,xe(xe({format:"html"},n),{set:!0,selection:!0,content:r}));i.no_events||!(i=e.fire("BeforeSetContent",i)).isDefaultPrevented()?(n.content=function(e,t){if("raw"===t.format)return t.content;var n=e.selection.getRng(),r=e.dom.getParent(n.commonAncestorContainer,e.dom.isBlock),o=r?{context:r.nodeName.toLowerCase()}:{},i=e.parser.parse(t.content,xe(xe({isRootContent:!0,forced_root_block:!1},o),t));return Tm({validate:e.validate},e.schema).serialize(i)}(e,i),function(e,t){var n=U.from(t.firstChild).map(Nt.fromDom),r=U.from(t.lastChild).map(Nt.fromDom);e.deleteContents(),e.insertNode(t);var o=n.bind(Ht).filter(Lt).bind(kv),i=r.bind(Vt).filter(Lt).bind(kv);_v(o,n,e,!0),_v(i,r,e,!1),e.collapse(!1)}(o=e.selection.getRng(),o.createContextualFragment(n.content)),e.selection.setRng(o),Md(e,o),i.no_events||e.fire("SetContent",i)):e.fire("SetContent",i)},Tv=function(e,t,n){var r;e&&e.hasOwnProperty(t)&&(0===(r=j(e[t],function(e){return e!==n})).length?delete e[t]:e[t]=r)};var Av=function(e){return!!e.select},Dv=function(e){return!(!e||!e.ownerDocument)&&At(Nt.fromDom(e.ownerDocument),Nt.fromDom(e))},Ov=function(u,s,e,c){var l,f,i,n,a,d,r=function(e,t){return a||(a={},d={},n.on("NodeChange",function(e){var n=e.element,r=i.getParents(n,null,i.getRoot()),o={};xt.each(a,function(e,n){xt.each(r,function(t){if(i.is(t,n))return d[n]||(xt.each(e,function(e){e(!0,{node:t,selector:n,parents:r})}),d[n]=e),o[n]=e,!1})}),xt.each(d,function(e,t){o[t]||(delete d[t],xt.each(e,function(e){e(!1,{node:n,selector:t,parents:r})}))})})),a[e]||(a[e]=[]),a[e].push(t),{unbind:function(){Tv(a,e,t),Tv(d,e,t)}}},t=function(e,t){return Rv(c,e,t)},o=function(e){var t=p();t.collapse(!!e),g(t)},m=function(){return s.getSelection?s.getSelection():s.document.selection},p=function(){var e,t,n,r=function(e,t,n){try{return t.compareBoundaryPoints(e,n)}catch(r){return-1}};if(!s)return null;var o=s.document;if(null==o)return null;if(c.bookmark!==undefined&&!1===pm(c)){var i=tm(c);if(i.isSome())return i.map(function(e){return wm(c,[e])[0]}).getOr(o.createRange())}try{(e=m())&&!Sn(e.anchorNode)&&(t=0<e.rangeCount?e.getRangeAt(0):e.createRange?e.createRange():o.createRange(),t=wm(c,[t])[0])}catch(a){}return(t=t||(o.createRange?o.createRange():o.body.createTextRange())).setStart&&9===t.startContainer.nodeType&&t.collapsed&&(n=u.getRoot(),t.setStart(n,0),t.setEnd(n,0)),l&&f&&(0===r(t.START_TO_START,t,l)&&0===r(t.END_TO_END,t,l)?t=f:f=l=null),t},g=function(e,t){var n;if((r=e)&&(Av(r)||Dv(r.startContainer)&&Dv(r.endContainer))){var r,o=Av(e)?e:null;if(o){f=null;try{o.select()}catch(a){}}else{var i=m();if(e=c.fire("SetSelectionRange",{range:e,forward:t}).range,i){f=e;try{i.removeAllRanges(),i.addRange(e)}catch(a){}!1===t&&i.extend&&(i.collapse(e.endContainer,e.endOffset),i.extend(e.startContainer,e.startOffset)),l=0<i.rangeCount?i.getRangeAt(0):null}e.collapsed||e.startContainer!==e.endContainer||!i.setBaseAndExtent||vt.ie||e.endOffset-e.startOffset<2&&e.startContainer.hasChildNodes()&&(n=e.startContainer.childNodes[e.startOffset])&&"IMG"===n.tagName&&(i.setBaseAndExtent(e.startContainer,e.startOffset,e.endContainer,e.endOffset),i.anchorNode===e.startContainer&&i.focusNode===e.endContainer||i.setBaseAndExtent(n,0,n,1)),c.fire("AfterSetSelectionRange",{range:e,forward:t})}}},h=function(){var e=m(),t=null==e?void 0:e.anchorNode,n=null==e?void 0:e.focusNode;if(!e||!t||!n||Sn(t)||Sn(n))return!0;var r=u.createRng();r.setStart(t,e.anchorOffset),r.collapse(!0);var o=u.createRng();return o.setStart(n,e.focusOffset),o.collapse(!0),r.compareBoundaryPoints(r.START_TO_START,o)<=0},v={bookmarkManager:null,controlSelection:null,dom:i=u,win:s,serializer:e,editor:n=c,collapse:o,setCursorLocation:function(e,t){var n=u.createRng();e?(n.setStart(e,t),n.setEnd(e,t),g(n),o(!1)):(Df(u,n,c.getBody(),!0),g(n))},getContent:function(e){return Ev(c,e)},setContent:t,getBookmark:function(e,t){return y.getBookmark(e,t)},moveToBookmark:function(e){return y.moveToBookmark(e)},select:function(e,t){var r,n,o;return r=u,n=e,o=t,U.from(n).map(function(e){var t=r.nodeIndex(e),n=r.createRng();return n.setStart(e.parentNode,t),n.setEnd(e.parentNode,t+1),o&&(Df(r,n,e,!0),Df(r,n,e,!1)),n}).each(g),e},isCollapsed:function(){var e=p(),t=m();return!(!e||e.item)&&(e.compareEndPoints?0===e.compareEndPoints("StartToEnd",e):!t||e.collapsed)},isForward:h,setNode:function(e){return t(u.getOuterHTML(e)),e},getNode:function(){return function(e,t){var n,r;if(!t)return e;n=t.startContainer,r=t.endContainer;var o=t.startOffset,i=t.endOffset,a=t.commonAncestorContainer;return!t.collapsed&&(n===r&&i-o<2&&n.hasChildNodes()&&(a=n.childNodes[o]),3===n.nodeType&&3===r.nodeType&&(n=n.length===o?Cm(n.nextSibling,!0):n.parentNode,r=0===i?Cm(r.previousSibling,!1):r.parentNode,n&&n===r))?n:a&&3===a.nodeType?a.parentNode:a}(c.getBody(),p())},getSel:m,setRng:g,getRng:p,getStart:function(e){return ym(c.getBody(),p(),e)},getEnd:function(e){return bm(c.getBody(),p(),e)},getSelectedBlocks:function(e,t){return function(e,t,n,r){var o,i=[],a=e.getRoot();if(n=e.getParent(n||ym(a,t,t.collapsed),e.isBlock),r=e.getParent(r||bm(a,t,t.collapsed),e.isBlock),n&&n!==a&&i.push(n),n&&r&&n!==r)for(var u=new Hr(o=n,a);(o=u.next())&&o!==r;)e.isBlock(o)&&i.push(o);return r&&n!==r&&r!==a&&i.push(r),i}(u,p(),e,t)},normalize:function(){var e=p(),t=m();if(1<Nf(t).length||!Of(c))return e;var n=ud(u,e);return n.each(function(e){g(e,h())}),n.getOr(e)},selectorChanged:function(e,t){return r(e,t),v},selectorChangedWithUnbind:r,getScrollContainer:function(){for(var e,t=u.getRoot();t&&"BODY"!==t.nodeName;){if(t.scrollHeight>t.clientHeight){e=t;break}t=t.parentNode}return e},scrollIntoView:function(e,t){return r=e,o=t,void((n=c).inline?Pd:Id)(n,r,o);var n,r,o},placeCaretAt:function(e,t){return g(ed(e,t,c.getDoc()))},getBoundingClientRect:function(){var e=p();return e.collapsed?Us.fromRangeStart(e).getClientRects()[0]:e.getBoundingClientRect()},destroy:function(){s=l=f=null,b.destroy()}},y=Kf(v),b=Qf(v,c);return v.bookmarkManager=y,v.controlSelection=b,v},Bv=function(e,a,u){e.addNodeFilter("font",function(e){$(e,function(e){var t,n=a.parse(e.attr("style")),r=e.attr("color"),o=e.attr("face"),i=e.attr("size");r&&(n.color=r),o&&(n["font-family"]=o),i&&(n["font-size"]=u[parseInt(e.attr("size"),10)-1]),e.name="span",e.attr("style",a.serialize(n)),t=e,$(["color","face","size"],function(e){t.attr(e,null)})})})},Pv=function(e,t){var n,r=hi();t.convert_fonts_to_spans&&Bv(e,r,xt.explode(t.font_size_legacy_values)),n=r,e.addNodeFilter("strike",function(e){$(e,function(e){var t=n.parse(e.attr("style"));t["text-decoration"]="line-through",e.name="span",e.attr("style",n.serialize(t))})})},Lv=function(e){var t,n=decodeURIComponent(e).split(","),r=/data:([^;]+)/.exec(n[0]);return r&&(t=r[1]),{type:t,data:n[1]}},Iv=function(e,t){var n;try{n=atob(t)}catch(pk){return U.none()}for(var r=new Uint8Array(n.length),o=0;o<r.length;o++)r[o]=n.charCodeAt(o);return U.some(new Blob([r],{type:e}))},Mv=function(e){return 0===e.indexOf("blob:")?(i=e,new _r(function(e,t){var n=function(){t("Cannot convert "+i+" to Blob. Resource might not exist or is inaccessible.")};try{var r=new XMLHttpRequest;r.open("GET",i,!0),r.responseType="blob",r.onload=function(){200===this.status?e(this.response):n()},r.onerror=n,r.send()}catch(o){n()}})):0===e.indexOf("data:")?(o=e,new _r(function(e){var t=Lv(o),n=t.type,r=t.data;Iv(n,r).fold(function(){return e(new Blob([]))},e)})):null;var i,o},Fv=0,Uv=function(e){return(e||"blobid")+Fv++},zv=function(r,o,i,t){var e,n,a,u,s;0!==o.src.indexOf("blob:")?(n=(e=Lv(o.src)).data,a=e.type,u=n,(s=r.getByData(u,a))?i({image:o,blobInfo:s}):Mv(o.src).then(function(e){s=r.create(Uv(),e,u),r.add(s),i({image:o,blobInfo:s})},function(e){t(e)})):(s=r.getByUri(o.src))?i({image:o,blobInfo:s}):Mv(o.src).then(function(t){var n;n=t,new _r(function(e){var t=new FileReader;t.onloadend=function(){e(t.result)},t.readAsDataURL(n)}).then(function(e){u=Lv(e).data,s=r.create(Uv(),t,u),r.add(s),i({image:o,blobInfo:s})})},function(e){t(e)})};function jv(i,a){var u={};return{findAll:function(e,n){n=n||k;var t,r=j((t=e)?te(t.getElementsByTagName("img")):[],function(e){var t=e.src;return!!vt.fileApi&&(!e.hasAttribute("data-mce-bogus")&&(!e.hasAttribute("data-mce-placeholder")&&(!(!t||t===vt.transparentSrc)&&(0===t.indexOf("blob:")?!i.isUploaded(t)&&n(e):0===t.indexOf("data:")&&n(e)))))}),o=F(r,function(n){if(u[n.src]!==undefined)return new _r(function(t){u[n.src].then(function(e){return"string"==typeof e?e:void t({image:n,blobInfo:e.blobInfo})})});var e=new _r(function(e,t){zv(a,n,e,t)}).then(function(e){return delete u[e.image.src],e})["catch"](function(e){return delete u[n.src],e});return u[n.src]=e});return _r.all(o)}}}var Hv,Vv,qv=function(e,t,n,r){(e.padd_empty_with_br||t.insert)&&n[r.name]?r.empty().append(new Em("br",1)).shortEnded=!0:r.empty().append(new Em("#text",3)).value=oo},$v=function(e,t){return e&&e.firstChild&&e.firstChild===e.lastChild&&e.firstChild.name===t},Wv=function(r,e,t,n){return n.isEmpty(e,t,function(e){return t=e,(n=r.getElementRule(t.name))&&n.paddEmpty;var t,n})},Kv=function(e,o){var i=o.blob_cache,t=function(t){var e,n,r=t.attr("src");(e=t).attr("src")===vt.transparentSrc||e.attr("data-mce-placeholder")||t.attr("data-mce-bogus")||((n=/data:([^;]+);base64,([a-z0-9\+\/=]+)/i.exec(r))?U.some({type:n[1],data:decodeURIComponent(n[2])}):U.none()).filter(function(){return function(e,t){if(t.images_dataimg_filter){var n=new Image;return n.src=e.attr("src"),oe(e.attributes.map,function(e,t){n.setAttribute(t,e)}),t.images_dataimg_filter(n)}return!0}(t,o)}).bind(function(e){var t=e.type,n=e.data;return U.from(i.getByData(n,t)).orThunk(function(){return Iv(t,n).map(function(e){var t=i.create(Uv(),e,n);return i.add(t),t})})}).each(function(e){t.attr("src",e.blobUri())})};i&&e.addAttributeFilter("src",function(e){return $(e,t)})},Xv=function(e,g){var h=e.schema;g.remove_trailing_brs&&e.addNodeFilter("br",function(e,t,n){var r,o,i,a,u,s,c,l,f=e.length,d=xt.extend({},h.getBlockElements()),m=h.getNonEmptyElements(),p=h.getWhiteSpaceElements();for(d.body=1,r=0;r<f;r++)if(i=(o=e[r]).parent,d[o.parent.name]&&o===i.lastChild){for(u=o.prev;u;){if("span"!==(s=u.name)||"bookmark"!==u.attr("data-mce-type")){"br"===s&&(o=null);break}u=u.prev}o&&(o.remove(),Wv(h,m,p,i)&&(c=h.getElementRule(i.name))&&(c.removeEmpty?i.remove():c.paddEmpty&&qv(g,n,d,i)))}else{for(a=o;i&&i.firstChild===a&&i.lastChild===a&&!d[(a=i).name];)i=i.parent;a===i&&!0!==g.padd_empty_with_br&&((l=new Em("#text",3)).value=oo,o.replace(l))}}),e.addAttributeFilter("href",function(e){var t,n,r=e.length;if(!g.allow_unsafe_link_target)for(;r--;){var o=e[r];"a"===o.name&&"_blank"===o.attr("target")&&o.attr("rel",(t=o.attr("rel"),n=t?xt.trim(t):"",/\b(noopener)\b/g.test(n)?n:n.split(" ").filter(function(e){return 0<e.length}).concat(["noopener"]).sort().join(" ")))}}),g.allow_html_in_named_anchor||e.addAttributeFilter("id,name",function(e){for(var t,n,r,o,i=e.length;i--;)if("a"===(o=e[i]).name&&o.firstChild&&!o.attr("href"))for(r=o.parent,t=o.lastChild;n=t.prev,r.insert(t,o),t=n;);}),g.fix_list_elements&&e.addNodeFilter("ul,ol",function(e){for(var t,n,r,o=e.length;o--;){"ul"!==(r=(n=e[o]).parent).name&&"ol"!==r.name||(n.prev&&"li"===n.prev.name?n.prev.append(n):((t=new Em("li",1)).attr("style","list-style-type: none"),n.wrap(t)))}}),g.validate&&h.getValidClasses()&&e.addAttributeFilter("class",function(e){for(var t,n,r,o,i,a,u,s=e.length,c=h.getValidClasses();s--;){for(n=(t=e[s]).attr("class").split(" "),i="",r=0;r<n.length;r++)o=n[r],u=!1,(a=c["*"])&&a[o]&&(u=!0),a=c[t.name],!u&&a&&a[o]&&(u=!0),u&&(i&&(i+=" "),i+=o);i.length||(i=null),t.attr("class",i)}}),Kv(e,g)},Yv=xt.makeMap,Gv=xt.each,Jv=xt.explode,Qv=xt.extend,Zv=function(R,T){void 0===T&&(T=pi());var A={},D=[],O={},B={};(R=R||{}).validate=!("validate"in R)||R.validate,R.root_name=R.root_name||"body";var e,t,P=function(e){var t,n,r=e.name;r in A&&((n=O[r])?n.push(e):O[r]=[e]),t=D.length;for(;t--;)(r=D[t].name)in e.attributes.map&&((n=B[r])?n.push(e):B[r]=[e]);return e},n={schema:T,addAttributeFilter:function(e,n){Gv(Jv(e),function(e){for(var t=0;t<D.length;t++)if(D[t].name===e)return void D[t].callbacks.push(n);D.push({name:e,callbacks:[n]})})},getAttributeFilters:function(){return[].concat(D)},addNodeFilter:function(e,n){Gv(Jv(e),function(e){var t=A[e];t||(A[e]=t=[]),t.push(n)})},getNodeFilters:function(){var e=[];for(var t in A)A.hasOwnProperty(t)&&e.push({name:t,callbacks:A[t]});return e},filterNode:P,parse:function(e,u){var t,n,r,o,i,s,a,c,l=[];u=u||{},O={},B={};var f,d=Qv(Yv("script,style,head,html,body,title,meta,param"),T.getBlockElements()),m=T.getNonEmptyElements(),p=T.children,g=R.validate,h="forced_root_block"in u?u.forced_root_block:R.forced_root_block,v=!1===(f=h)?"":!0===f?"p":f,y=T.getWhiteSpaceElements(),b=/^[ \t\r\n]+/,C=/[ \t\r\n]+$/,w=/[ \t\r\n]+/g,x=/^[ \t\r\n]+$/,S=y.hasOwnProperty(u.context)||y.hasOwnProperty(R.root_name),N=function(e,t){var n,r=new Em(e,t);return e in A&&((n=O[e])?n.push(r):O[e]=[r]),r},E=function(e){for(var t,n,r,o=T.getBlockElements(),i=e.prev;i&&3===i.type;){if(0<(n=i.value.replace(C,"")).length)return void(i.value=n);if(t=i.next){if(3===t.type&&t.value.length){i=i.prev;continue}if(!o[t.name]&&"script"!==t.name&&"style"!==t.name){i=i.prev;continue}}r=i.prev,i.remove(),i=r}},k=Lm({validate:g,allow_html_data_urls:R.allow_html_data_urls,allow_script_urls:R.allow_script_urls,allow_conditional_comments:R.allow_conditional_comments,preserve_cdata:R.preserve_cdata,self_closing_elements:function(e){var t,n={};for(t in e)"li"!==t&&"p"!==t&&(n[t]=e[t]);return n}(T.getSelfClosingElements()),cdata:function(e){c.append(N("#cdata",4)).value=e},text:function(e,t){var n,r,o;S||(e=e.replace(w," "),r=c.lastChild,o=d,r&&(o[r.name]||"br"===r.name)&&(e=e.replace(b,""))),0!==e.length&&((n=N("#text",3)).raw=!!t,c.append(n).value=e)},comment:function(e){c.append(N("#comment",8)).value=e},pi:function(e,t){c.append(N(e,7)).value=t,E(c)},doctype:function(e){c.append(N("#doctype",10)).value=e,E(c)},start:function(e,t,n){var r,o,i,a,u=g?T.getElementRule(e):{};if(u){for((r=N(u.outputName||e,1)).attributes=t,r.shortEnded=n,c.append(r),(a=p[c.name])&&p[r.name]&&!a[r.name]&&l.push(r),o=D.length;o--;)(i=D[o].name)in t.map&&((s=B[i])?s.push(r):B[i]=[r]);d[e]&&E(r),n||(c=r),!S&&y[e]&&(S=!0)}},end:function(e){var t,n,r,o,i,a=g?T.getElementRule(e):{};if(a){if(d[e]&&!S){if((t=c.firstChild)&&3===t.type)if(0<(n=t.value.replace(b,"")).length)t.value=n,t=t.next;else for(r=t.next,t.remove(),t=r;t&&3===t.type;)n=t.value,r=t.next,0!==n.length&&!x.test(n)||(t.remove(),t=r),t=r;if((t=c.lastChild)&&3===t.type)if(0<(n=t.value.replace(C,"")).length)t.value=n,t=t.prev;else for(r=t.prev,t.remove(),t=r;t&&3===t.type;)n=t.value,r=t.prev,0!==n.length&&!x.test(n)||(t.remove(),t=r),t=r}if(S&&y[e]&&(S=!1),a.removeEmpty&&Wv(T,m,y,c))return o=c.parent,d[c.name]?c.empty().remove():c.unwrap(),void(c=o);a.paddEmpty&&($v(i=c,"#text")&&i.firstChild.value===oo||Wv(T,m,y,c))&&qv(R,u,d,c),c=c.parent}}},T),_=c=new Em(u.context||R.root_name,11);if(k.parse(e,u.format),g&&l.length&&(u.context?u.invalid=!0:function(e){for(var t,n,r,o,i,a,u,s,c,l,f=Yv("tr,td,th,tbody,thead,tfoot,table"),d=T.getNonEmptyElements(),m=T.getWhiteSpaceElements(),p=T.getTextBlockElements(),g=T.getSpecialElements(),h=0;h<e.length;h++)if((t=e[h]).parent&&!t.fixed)if(p[t.name]&&"li"===t.parent.name){for(c=t.next;c&&p[c.name];)c.name="li",c.fixed=!0,t.parent.insert(c,t.parent),c=c.next;t.unwrap(t)}else{for(r=[t],n=t.parent;n&&!T.isValidChild(n.name,t.name)&&!f[n.name];n=n.parent)r.push(n);if(n&&1<r.length){for(r.reverse(),o=i=P(r[0].clone()),s=0;s<r.length-1;s++){for(T.isValidChild(i.name,r[s].name)?(a=P(r[s].clone()),i.append(a)):a=i,u=r[s].firstChild;u&&u!==r[s+1];)l=u.next,a.append(u),u=l;i=a}Wv(T,d,m,o)?n.insert(t,r[0],!0):(n.insert(o,r[0],!0),n.insert(t,o)),n=r[0],(Wv(T,d,m,n)||$v(n,"br"))&&n.empty().remove()}else if(t.parent){if("li"===t.name){if((c=t.prev)&&("ul"===c.name||"ol"===c.name)){c.append(t);continue}if((c=t.next)&&("ul"===c.name||"ol"===c.name)){c.insert(t,c.firstChild,!0);continue}t.wrap(P(new Em("ul",1)));continue}T.isValidChild(t.parent.name,"div")&&T.isValidChild("div",t.name)?t.wrap(P(new Em("div",1))):g[t.name]?t.empty().remove():t.unwrap()}}}(l)),v&&("body"===_.name||u.isRootContent)&&function(){var e,t,n=_.firstChild,r=function(e){e&&((n=e.firstChild)&&3===n.type&&(n.value=n.value.replace(b,"")),(n=e.lastChild)&&3===n.type&&(n.value=n.value.replace(C,"")))};if(T.isValidChild(_.name,v.toLowerCase())){for(;n;)e=n.next,3===n.type||1===n.type&&"p"!==n.name&&!d[n.name]&&!n.attr("data-mce-type")?(t||((t=N(v,1)).attr(R.forced_root_block_attrs),_.insert(t,n)),t.append(n)):(r(t),t=null),n=e;r(t)}}(),!u.invalid){for(a in O)if(O.hasOwnProperty(a)){for(s=A[a],o=(t=O[a]).length;o--;)t[o].parent||t.splice(o,1);for(n=0,r=s.length;n<r;n++)s[n](t,a,u)}for(n=0,r=D.length;n<r;n++)if((s=D[n]).name in B){for(o=(t=B[s.name]).length;o--;)t[o].parent||t.splice(o,1);for(o=0,i=s.callbacks.length;o<i;o++)s.callbacks[o](t,s.name,u)}}return _}};return Xv(n,R),e=n,(t=R).inline_styles&&Pv(e,t),n},ey=function(e,t,n){return o=n,(r=e)&&r.hasEventListeners("PreProcess")&&!o.no_events?function(e,t,n){var r,o,i=e.dom;t=t.cloneNode(!0);var a,u,s=document.implementation;return s.createHTMLDocument&&(r=s.createHTMLDocument(""),xt.each("BODY"===t.nodeName?t.childNodes:[t],function(e){r.body.appendChild(r.importNode(e,!0))}),t="BODY"!==t.nodeName?r.body.firstChild:r.body,o=i.doc,i.doc=r),a=e,u=xe(xe({},n),{node:t}),a.fire("PreProcess",u),o&&(i.doc=o),t}(e,t,n):t;var r,o},ty=function(e,t,n){-1===xt.inArray(t,n)&&(e.addAttributeFilter(n,function(e,t){for(var n=e.length;n--;)e[n].attr(t,null)}),t.push(n))},ny=function(e,t,n,r,o){var i,a,u,s,c,l,f=(i=r,Tm(t,n).serialize(i));return a=e,s=f,(u=o).no_events||!a?s:(c=a,l=xe(xe({},u),{content:s}),c.fire("PostProcess",l).content)},ry=function(y,b){var e=["data-mce-selected"],C=b&&b.dom?b.dom:bu.DOM,w=b&&b.schema?b.schema:pi(y);y.entity_encoding=y.entity_encoding||"named",y.remove_trailing_brs=!("remove_trailing_brs"in y)||y.remove_trailing_brs;var t,s,c,x=Zv(y,w);s=y,c=C,(t=x).addAttributeFilter("data-mce-tabindex",function(e,t){for(var n,r=e.length;r--;)(n=e[r]).attr("tabindex",n.attr("data-mce-tabindex")),n.attr(t,null)}),t.addAttributeFilter("src,href,style",function(e,t){for(var n,r,o=e.length,i="data-mce-"+t,a=s.url_converter,u=s.url_converter_scope;o--;)(r=(n=e[o]).attr(i))!==undefined?(n.attr(t,0<r.length?r:null),n.attr(i,null)):(r=n.attr(t),"style"===t?r=c.serializeStyle(c.parseStyle(r),n.name):a&&(r=a.call(u,r,t,n.name)),n.attr(t,0<r.length?r:null))}),t.addAttributeFilter("class",function(e){for(var t,n,r=e.length;r--;)(n=(t=e[r]).attr("class"))&&(n=t.attr("class").replace(/(?:^|\s)mce-item-\w+(?!\S)/g,""),t.attr("class",0<n.length?n:null))}),t.addAttributeFilter("data-mce-type",function(e,t,n){for(var r,o=e.length;o--;){"bookmark"!==(r=e[o]).attr("data-mce-type")||n.cleanup||(U.from(r.firstChild).exists(function(e){return!ao(e.value)})?r.unwrap():r.remove())}}),t.addNodeFilter("noscript",function(e){for(var t,n=e.length;n--;)(t=e[n].firstChild)&&(t.value=ri.decode(t.value))}),t.addNodeFilter("script,style",function(e,t){for(var n,r,o,i=e.length,a=function(e){return e.replace(/(<!--\[CDATA\[|\]\]-->)/g,"\n").replace(/^[\r\n]*|[\r\n]*$/g,"").replace(/^\s*((<!--)?(\s*\/\/)?\s*<!\[CDATA\[|(<!--\s*)?\/\*\s*<!\[CDATA\[\s*\*\/|(\/\/)?\s*<!--|\/\*\s*<!--\s*\*\/)\s*[\r\n]*/gi,"").replace(/\s*(\/\*\s*\]\]>\s*\*\/(-->)?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g,"")};i--;)r=(n=e[i]).firstChild?n.firstChild.value:"","script"===t?((o=n.attr("type"))&&n.attr("type","mce-no/type"===o?null:o.replace(/^mce\-/,"")),"xhtml"===s.element_format&&0<r.length&&(n.firstChild.value="// <![CDATA[\n"+a(r)+"\n// ]]>")):"xhtml"===s.element_format&&0<r.length&&(n.firstChild.value="\x3c!--\n"+a(r)+"\n--\x3e")}),t.addNodeFilter("#comment",function(e){for(var t,n=e.length;n--;)t=e[n],s.preserve_cdata&&0===t.value.indexOf("[CDATA[")?(t.name="#cdata",t.type=4,t.value=c.decode(t.value.replace(/^\[CDATA\[|\]\]$/g,""))):0===t.value.indexOf("mce:protected ")&&(t.name="#text",t.type=3,t.raw=!0,t.value=unescape(t.value).substr(14))}),t.addNodeFilter("xml:namespace,input",function(e,t){for(var n,r=e.length;r--;)7===(n=e[r]).type?n.remove():1===n.type&&("input"!==t||n.attr("type")||n.attr("type","text"))}),t.addAttributeFilter("data-mce-type",function(e){$(e,function(e){"format-caret"===e.attr("data-mce-type")&&(e.isEmpty(t.schema.getNonEmptyElements())?e.remove():e.unwrap())})}),t.addAttributeFilter("data-mce-src,data-mce-href,data-mce-style,data-mce-selected,data-mce-expando,data-mce-type,data-mce-resize,data-mce-placeholder",function(e,t){for(var n=e.length;n--;)e[n].attr(t,null)});return{schema:w,addNodeFilter:x.addNodeFilter,addAttributeFilter:x.addAttributeFilter,serialize:function(e,t){void 0===t&&(t={});var n,r,o,i,a,u,s,c,l,f,d,m,p=xe({format:"html"},t),g=ey(b,e,p),h=(n=C,r=g,i=uo((o=p).getInner?r.innerHTML:n.getOuterHTML(r)),o.selection||no(Nt.fromDom(r))?i:xt.trim(i)),v=(a=x,u=h,d=(s=p).selection?xe({forced_root_block:!1},s):s,m=a.parse(u,d),l=function(e){return e&&"br"===e.name},f=m.lastChild,!l(f)||l(c=f.prev)&&(f.remove(),c.remove()),m);return"tree"===p.format?v:ny(b,y,w,v,p)},addRules:function(e){w.addValidElements(e)},setRules:function(e){w.setValidElements(e)},addTempAttr:E(ty,x,e),getTempAttrs:function(){return e},getNodeFilters:x.getNodeFilters,getAttributeFilters:x.getAttributeFilters}},oy=function(e,t){var n=ry(e,t);return{schema:n.schema,addNodeFilter:n.addNodeFilter,addAttributeFilter:n.addAttributeFilter,serialize:n.serialize,addRules:n.addRules,setRules:n.setRules,addTempAttr:n.addTempAttr,getTempAttrs:n.getTempAttrs,getNodeFilters:n.getNodeFilters,getAttributeFilters:n.getAttributeFilters}},iy=function(e,t){void 0===t&&(t={});var n,r,o=t.format?t.format:"html";return n=t,r=o,Sv(e).editor.getContent(n,r)},ay=function(e,t,n){return void 0===n&&(n={}),r=t,o=n,Sv(e).editor.setContent(r,o);var r,o},uy=bu.DOM,sy=function(e){return U.from(e).each(function(e){return e.destroy()})},cy=function(e){var t,n,r,o,i;e.removed||(t=e._selectionOverrides,n=e.editorUpload,r=e.getBody(),o=e.getElement(),r&&e.save({is_removing:!0}),e.removed=!0,e.unbindAllNativeEvents(),e.hasHiddenInput&&o&&uy.remove(o.nextSibling),e.fire("remove"),e.editorManager.remove(e),!e.inline&&r&&(i=e,uy.setStyle(i.id,"display",i.orgDisplay)),e.fire("detach"),uy.remove(e.getContainer()),sy(t),sy(n),e.destroy())},ly=function(e,t){var n,r,o,i=e.selection,a=e.dom;e.destroyed||(t||e.removed?(t||(e.editorManager.off("beforeunload",e._beforeUnload),e.theme&&e.theme.destroy&&e.theme.destroy(),sy(i),sy(a)),(r=(n=e).formElement)&&(r._mceOldSubmit&&(r.submit=r._mceOldSubmit,r._mceOldSubmit=null),uy.unbind(r,"submit reset",n.formEventDelegate)),(o=e).contentAreaContainer=o.formElement=o.container=o.editorContainer=null,o.bodyElement=o.contentDocument=o.contentWindow=null,o.iframeElement=o.targetElm=null,o.selection&&(o.selection=o.selection.win=o.selection.dom=o.selection.dom.doc=null),e.destroyed=!0):e.remove())},fy=Object.prototype.hasOwnProperty,dy=(Hv=function(e,t){return _(e)&&_(t)?dy(e,t):t},function(){for(var e=new Array(arguments.length),t=0;t<e.length;t++)e[t]=arguments[t];if(0===e.length)throw new Error("Can't merge zero objects");for(var n={},r=0;r<e.length;r++){var o=e[r];for(var i in o)fy.call(o,i)&&(n[i]=Hv(n[i],o[i]))}return n}),my=st().deviceType,py=my.isTouch(),gy=my.isPhone(),hy=my.isTablet(),vy=["lists","autolink","autosave"],yy={table_grid:!1,object_resizing:!1,resize:!1},by=function(e){var t=S(e)?e.join(" "):e,n=F(q(t)?t.split(" "):[],je);return j(n,function(e){return 0<e.length})},Cy=function(n,e){var t,r,o=ce(e,function(e,t){return I(n,t)});return t=o.t,r=o.f,{sections:N(t),settings:N(r)}},wy=function(e,t){return e.sections().hasOwnProperty(t)},xy=function(e,t){return de(e,"toolbar_mode").orThunk(function(){return de(e,"toolbar_drawer").map(function(e){return!1===e?"wrap":e})}).getOr(t)},Sy=function(e,t,n,r){var o,i,a,u,s,c,l,f=by(n.forced_plugins),d=by(r.plugins),m=wy(o=t,i="mobile")?o.sections()[i]:{},p=m.plugins?by(m.plugins):d,g=e&&(s=u="mobile",c=(a=t).sections(),wy(a,u)&&c[u].theme===s)?j(p,E(I,vy)):e&&wy(t,"mobile")?p:d,h=(l=g,[].concat(by(f)).concat(by(l)));return xt.extend(r,{plugins:h.join(" ")})},Ny=function(e,t,n,r,o){var i,a,u,s,c,l,f,d=e?{mobile:(i=o.mobile||{},a=t,u={resize:!1,toolbar_mode:xy(i,"scrolling"),toolbar_sticky:!1},xe(xe(xe({},yy),u),a?{menubar:!1}:{}))}:{},m=Cy(["mobile"],dy(d,o)),p=xt.extend(n,r,m.settings(),(f=m,e&&wy(f,"mobile")?function(e,t,n){void 0===n&&(n={});var r=e.sections(),o=r.hasOwnProperty(t)?r[t]:{};return xt.extend({},n,o)}(m,"mobile"):{}),{validate:!0,external_plugins:(s=r,c=m.settings(),l=c.external_plugins?c.external_plugins:{},s&&s.external_plugins?xt.extend({},s.external_plugins,l):l)});return Sy(e,m,r,p)},Ey=function(e,t,n,r,o){var i,a,u,s,c=(i=n,a=py,u=e,s={id:t,theme:"silver",toolbar_mode:xy(o,"floating"),plugins:"",document_base_url:i,add_form_submit_trigger:!0,submit_patch:!0,add_unload_trigger:!0,convert_urls:!0,relative_urls:!0,remove_script_host:!0,object_resizing:!0,doctype:"<!DOCTYPE html>",visual:!0,font_size_legacy_values:"xx-small,small,medium,large,x-large,xx-large,300%",forced_root_block:"p",hidden_input:!0,inline_styles:!0,convert_fonts_to_spans:!0,indent:!0,indent_before:"p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,th,ul,ol,li,dl,dt,dd,area,table,thead,tfoot,tbody,tr,section,summary,article,hgroup,aside,figure,figcaption,option,optgroup,datalist",indent_after:"p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,th,ul,ol,li,dl,dt,dd,area,table,thead,tfoot,tbody,tr,section,summary,article,hgroup,aside,figure,figcaption,option,optgroup,datalist",entity_encoding:"named",url_converter:u.convertURL,url_converter_scope:u},xe(xe({},s),a?yy:{}));return Ny(gy||hy,gy,c,r,o)},ky=function(e,t,n){return U.from(t.settings[n]).filter(e)},_y=function(e,t,n,r){var o,i,a,u=t in e.settings?e.settings[t]:n;return"hash"===r?(a={},"string"==typeof(i=u)?$(0<i.indexOf("=")?i.split(/[;,](?![^=;,]*(?:[;,]|$))/):i.split(","),function(e){var t=e.split("=");1<t.length?a[xt.trim(t[0])]=xt.trim(t[1]):a[xt.trim(t[0])]=xt.trim(t[0])}):a=i,a):"string"===r?ky(q,e,t).getOr(n):"number"===r?ky(D,e,t).getOr(n):"boolean"===r?ky(x,e,t).getOr(n):"object"===r?ky(_,e,t).getOr(n):"array"===r?ky(S,e,t).getOr(n):"string[]"===r?ky((o=q,function(e){return S(e)&&G(e,o)}),e,t).getOr(n):"function"===r?ky(A,e,t).getOr(n):u},Ry=(Vv={},{add:function(e,t){Vv[e]=t},get:function(e){return Vv[e]?Vv[e]:{icons:{}}},has:function(e){return me(Vv,e)}}),Ty=function(e,t){return t.dom[e]},Ay=function(e,t){return parseInt(Yn(t,e),10)},Dy=E(Ty,"clientWidth"),Oy=E(Ty,"clientHeight"),By=E(Ay,"margin-top"),Py=E(Ay,"margin-left"),Ly=function(e,t,n){var r,o,i,a,u,s,c,l,f,d,m,p=Nt.fromDom(e.getBody()),g=e.inline?p:(r=p,Nt.fromDom(Ut(r).dom.documentElement)),h=(o=e.inline,a=t,u=n,s=(i=g).dom.getBoundingClientRect(),{x:a-(o?s.left+i.dom.clientLeft+Py(i):0),y:u-(o?s.top+i.dom.clientTop+By(i):0)});return l=h.x,f=h.y,d=Dy(c=g),m=Oy(c),0<=l&&0<=f&&l<=d&&f<=m},Iy=function(e){var t,n=e.inline?e.getBody():e.getContentAreaContainer();return t=n,U.from(t).map(Nt.fromDom).map(dn).getOr(!1)};function My(n){var t,o=[],i=function(){var e,t=n.theme;return t&&t.getNotificationManagerImpl?t.getNotificationManagerImpl():{open:e=function(){throw new Error("Theme did not provide a NotificationManager implementation.")},close:e,reposition:e,getArgs:e}},a=function(){return U.from(o[0])},u=function(){0<o.length&&i().reposition(o)},s=function(t){X(o,function(e){return e===t}).each(function(e){o.splice(e,1)})},r=function(r){if(!n.removed&&Iy(n))return K(o,function(e){return t=i().getArgs(e),n=r,!(t.type!==n.type||t.text!==n.text||t.progressBar||t.timeout||n.progressBar||n.timeout);var t,n}).getOrThunk(function(){n.editorManager.setActive(n);var e,t=i().open(r,function(){s(t),u(),a().fold(function(){return n.focus()},function(e){return Nt.fromDom(e.getEl()).dom.focus()})});return e=t,o.push(e),u(),t})};return(t=n).on("SkinLoaded",function(){var e=t.getParam("service_message");e&&r({text:e,type:"warning",timeout:0})}),t.on("ResizeEditor ResizeWindow NodeChange",function(){Fr.requestAnimationFrame(u)}),t.on("remove",function(){$(o.slice(),function(e){i().close(e)})}),{open:r,close:function(){a().each(function(e){i().close(e),s(e),u()})},getNotifications:function(){return o}}}var Fy=Bu.PluginManager,Uy=Bu.ThemeManager;var zy=function(n){var r=[],o=function(){var e,t=n.theme;return t&&t.getWindowManagerImpl?t.getWindowManagerImpl():{open:e=function(){throw new Error("Theme did not provide a WindowManager implementation.")},openUrl:e,alert:e,confirm:e,close:e,getParams:e,setParams:e}},i=function(e,t){return function(){return t?t.apply(e,arguments):undefined}},a=function(e){var t;r.push(e),t=e,n.fire("OpenWindow",{dialog:t})},u=function(t){var e;e=t,n.fire("CloseWindow",{dialog:e}),0===(r=j(r,function(e){return e!==t})).length&&n.focus()},s=function(e){n.editorManager.setActive(n),em(n);var t=e();return a(t),t};return n.on("remove",function(){$(r,function(e){o().close(e)})}),{open:function(e,t){return s(function(){return o().open(e,t,u)})},openUrl:function(e){return s(function(){return o().openUrl(e,u)})},alert:function(e,t,n){o().alert(e,i(n||this,t))},confirm:function(e,t,n){o().confirm(e,i(n||this,t))},close:function(){U.from(r[r.length-1]).each(function(e){o().close(e),u(e)})}}},jy=function(e,t){e.notificationManager.open({type:"error",text:t})},Hy=function(e,t){e._skinLoaded?jy(e,t):e.on("SkinLoaded",function(){jy(e,t)})},Vy=function(e,t,n){var r,o;r=t,o={message:n},e.fire(r,o),console.error(n)},qy=function(e,t,n){return n?"Failed to load "+e+": "+n+" from url "+t:"Failed to load "+e+" url: "+t},$y=function(e,t,n){Vy(e,"PluginLoadError",qy("plugin",t,n))},Wy=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r=window.console;r&&(r.error?r.error.apply(r,Se([e],t)):r.log.apply(r,Se([e],t)))},Ky=function(t){var e,n,r=(n=(e=t).getParam("content_css"),q(n)?F(n.split(","),je):S(n)?n:!1===n||e.inline?[]:["default"]),o=t.editorManager.baseURL+"/skins/content",i="content"+t.editorManager.suffix+".css",a=!0===t.inline;return F(r,function(e){return/^[a-z0-9\-]+$/i.test(e)&&!a?o+"/"+e+"/"+i:t.documentBaseURI.toAbsolute(e)})};function Xy(u,s){var o={},n=function(e,r,o,t){var i=new XMLHttpRequest;i.open("POST",s.url),i.withCredentials=s.credentials,i.upload.onprogress=function(e){t(e.loaded/e.total*100)},i.onerror=function(){o("Image upload failed due to a XHR Transport error. Code: "+i.status)},i.onload=function(){var e,t,n;i.status<200||300<=i.status?o("HTTP Error: "+i.status):(e=JSON.parse(i.responseText))&&"string"==typeof e.location?r((t=s.basePath,n=e.location,t?t.replace(/\/$/,"")+"/"+n.replace(/^\//,""):n)):o("Invalid JSON: "+i.responseText)};var n=new FormData;n.append("file",e.blob(),e.filename()),i.send(n)},c=function(e,t){return{url:t,blobInfo:e,status:!0}},l=function(e,t,n){return{url:"",blobInfo:e,status:!1,error:{message:t,options:n}}},f=function(e,t){xt.each(o[e],function(e){e(t)}),delete o[e]},r=function(e,r){return e=xt.grep(e,function(e){return!u.isUploaded(e.blobUri())}),_r.all(xt.map(e,function(e){return u.isPending(e.blobUri())?(t=e.blobUri(),new _r(function(e){o[t]=o[t]||[],o[t].push(e)})):(i=e,n=s.handler,a=r,u.markPending(i.blobUri()),new _r(function(r){var t;try{var o=function(){t&&t.close()};n(i,function(e){o(),u.markUploaded(i.blobUri(),e),f(i.blobUri(),c(i,e)),r(c(i,e))},function(e,t){var n=t||{};o(),u.removeFailed(i.blobUri()),f(i.blobUri(),l(i,e,n)),r(l(i,e,n))},function(e){e<0||100<e||(t=t||a()).progressBar.value(e)})}catch(e){r(l(i,e.message,{}))}}));var i,n,a,t}))};return!1===A(s.handler)&&(s.handler=n),{upload:function(e,t){return s.url||s.handler!==n?r(e,t):new _r(function(e){e([])})}}}var Yy=0,Gy=function(e){return e+Yy+++(t=function(){return Math.round(4294967295*Math.random()).toString(36)},"s"+(new Date).getTime().toString(36)+t()+t()+t());var t},Jy=function(s){var n,o,e,t,r,i,a,u,c,l=(n=[],o=function(e){if(!e.blob||!e.base64)throw new Error("blob and base64 representations of the image are required for BlobInfo to be created");var t=e.id||Gy("blobid"),n=e.name||t;return{id:N(t),name:N(n),filename:N(n+"."+({"image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/png":"png"}[e.blob.type.toLowerCase()]||"dat")),blob:N(e.blob),base64:N(e.base64),blobUri:N(e.blobUri||URL.createObjectURL(e.blob)),uri:N(e.uri)}},{create:function(e,t,n,r){if(q(e))return o({id:e,name:r,blob:t,base64:n});if(_(e))return o(e);throw new Error("Unknown input type")},add:function(e){t(e.id())||n.push(e)},get:t=function(t){return e(function(e){return e.id()===t})},getByUri:function(t){return e(function(e){return e.blobUri()===t})},getByData:function(t,n){return e(function(e){return e.base64()===t&&e.blob().type===n})},findFirst:e=function(e){return K(n,e).getOrUndefined()},removeByUri:function(t){n=j(n,function(e){return e.blobUri()!==t||(URL.revokeObjectURL(e.blobUri()),!1)})},destroy:function(){$(n,function(e){URL.revokeObjectURL(e.blobUri())}),n=[]}}),f=(a={},u=function(e,t){return{status:e,resultUri:t}},{hasBlobUri:c=function(e){return e in a},getResultUri:function(e){var t=a[e];return t?t.resultUri:null},isPending:function(e){return!!c(e)&&1===a[e].status},isUploaded:function(e){return!!c(e)&&2===a[e].status},markPending:function(e){a[e]=u(1,null)},markUploaded:function(e,t){a[e]=u(2,t)},removeFailed:function(e){delete a[e]},destroy:function(){a={}}}),d=[],m=function(t){return function(e){return s.selection?t(e):[]}},p=function(e,t,n){for(var r=0;-1!==(r=e.indexOf(t,r))&&(e=e.substring(0,r)+n+e.substr(r+t.length),r+=n.length-t.length+1),-1!==r;);return e},g=function(e,t,n){var r='src="'+n+'"'+(n===vt.transparentSrc?' data-mce-placeholder="1"':"");return e=p(e,'src="'+t+'"',r),e=p(e,'data-mce-src="'+t+'"','data-mce-src="'+n+'"')},h=function(t,n){$(s.undoManager.data,function(e){"fragmented"===e.type?e.fragments=F(e.fragments,function(e){return g(e,t,n)}):e.content=g(e.content,t,n)})},v=function(){return s.notificationManager.open({text:s.translate("Image uploading..."),type:"info",timeout:-1,progressBar:!0})},y=function(e,t){var n,r=s.convertURL(t,"src");h(e.src,t),s.$(e).attr({src:s.getParam("images_reuse_filename",!1,"boolean")?(n=t)+(-1===n.indexOf("?")?"?":"&")+(new Date).getTime():t,"data-mce-src":r})},b=function(n){return r=r||Xy(f,{url:s.getParam("images_upload_url","","string"),basePath:s.getParam("images_upload_base_path","","string"),credentials:s.getParam("images_upload_credentials",!1,"boolean"),handler:s.getParam("images_upload_handler",null,"function")}),x().then(m(function(u){var e=F(u,function(e){return e.blobInfo});return r.upload(e,v).then(m(function(e){var a=[],t=F(e,function(e,t){var n,r,o=u[t].blobInfo,i=u[t].image;return e.status&&s.getParam("images_replace_blob_uris",!0,"boolean")?(l.removeByUri(i.src),y(i,e.url)):e.error&&(e.error.options.remove&&(h(i.getAttribute("src"),vt.transparentSrc),a.push(i)),n=s,r=e.error.message,Hy(n,Au.translate(["Failed to upload image: {0}",r]))),{element:i,status:e.status,uploadUri:e.url,blobInfo:o}});return 0<a.length&&(xv(s)?console.error("Removing images on failed uploads is currently unsupported for RTC"):s.undoManager.transact(function(){$(a,function(e){s.dom.remove(e),l.removeByUri(e.src)})})),n&&n(t),t}))}))},C=function(e){if(mc(s))return b(e)},w=function(t){return!1!==G(d,function(e){return e(t)})&&(0!==t.getAttribute("src").indexOf("data:")||s.getParam("images_dataimg_filter",k,"function")(t))},x=function(){return(i=i||jv(f,l)).findAll(s.getBody(),w).then(m(function(e){return e=j(e,function(e){return"string"!=typeof e||(Hy(s,e),!1)}),$(e,function(e){h(e.image.src,e.blobInfo.blobUri()),e.image.src=e.blobInfo.blobUri(),e.image.removeAttribute("data-mce-src")}),e}))},S=function(e){return e.replace(/src="(blob:[^"]+)"/g,function(e,n){var t=f.getResultUri(n);if(t)return'src="'+t+'"';var r=l.getByUri(n);return(r=r||W(s.editorManager.get(),function(e,t){return e||t.editorUpload&&t.editorUpload.blobCache.getByUri(n)},null))?'src="data:'+r.blob().type+";base64,"+r.base64()+'"':e})};return s.on("SetContent",function(){(mc(s)?C:x)()}),s.on("RawSaveContent",function(e){e.content=S(e.content)}),s.on("GetContent",function(e){e.source_view||"raw"===e.format||(e.content=S(e.content))}),s.on("PostRender",function(){s.parser.addNodeFilter("img",function(e){$(e,function(e){var t,n=e.attr("src");l.getByUri(n)||(t=f.getResultUri(n))&&e.attr("src",t)})})}),{blobCache:l,addFilter:function(e){d.push(e)},uploadImages:b,uploadImagesAuto:C,scanForImages:x,destroy:function(){l.destroy(),f.destroy(),i=r=null}}},Qy=function(r,e,t,n){var o=ne(t.get()),i={},a={},u=j(uf(r.dom,e),function(e){return 1===e.nodeType&&!e.getAttribute("data-mce-bogus")});oe(n,function(e,n){xt.each(u,function(t){return r.formatter.matchNode(t,n,{},e.similar)?(-1===o.indexOf(n)&&($(e.callbacks,function(e){e(!0,{node:t,format:n,parents:u})}),i[n]=e.callbacks),a[n]=e.callbacks,!1):!Vg(r,t,n)&&void 0})});var s=Zy(t.get(),a,e,u);t.set(xe(xe({},i),s))},Zy=function(e,n,r,o){return ce(e,function(e,t){return!!me(n,t)||($(e,function(e){e(!1,{node:r,format:t,parents:o})}),!1)}).t},eb=function(e,o,i,a,t){var n,r,u,s,c,l,f,d;return null===o.get()&&(r=e,u=ku({}),(n=o).set({}),r.on("NodeChange",function(e){Qy(r,e.element,u,n.get())})),c=i,l=a,f=t,d=(s=o).get(),$(c.split(","),function(e){d[e]||(d[e]={similar:f,callbacks:[]}),d[e].callbacks.push(l)}),s.set(d),{unbind:function(){return t=i,n=a,r=(e=o).get(),$(t.split(","),function(e){r[e].callbacks=j(r[e].callbacks,function(e){return e!==n}),0===r[e].callbacks.length&&delete r[e]}),void e.set(r);var e,t,n,r}}};function tb(e){var r,t,n={},o=function(e,t){e&&("string"!=typeof e?xt.each(e,function(e,t){o(t,e)}):(S(t)||(t=[t]),xt.each(t,function(e){"undefined"==typeof e.deep&&(e.deep=!e.selector),"undefined"==typeof e.split&&(e.split=!e.selector||e.inline),"undefined"==typeof e.remove&&e.selector&&!e.inline&&(e.remove="none"),e.selector&&e.inline&&(e.mixed=!0,e.block_expand=!0),"string"==typeof e.classes&&(e.classes=e.classes.split(/\s+/))}),n[e]=t))};return o((r=e.dom,t={valigntop:[{selector:"td,th",styles:{verticalAlign:"top"}}],valignmiddle:[{selector:"td,th",styles:{verticalAlign:"middle"}}],valignbottom:[{selector:"td,th",styles:{verticalAlign:"bottom"}}],alignleft:[{selector:"figure.image",collapsed:!1,classes:"align-left",ceFalseOverride:!0,preview:"font-family font-size"},{selector:"figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li",styles:{textAlign:"left"},inherit:!1,preview:!1,defaultBlock:"div"},{selector:"img,table",collapsed:!1,styles:{"float":"left"},preview:"font-family font-size"}],aligncenter:[{selector:"figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li",styles:{textAlign:"center"},inherit:!1,preview:"font-family font-size",defaultBlock:"div"},{selector:"figure.image",collapsed:!1,classes:"align-center",ceFalseOverride:!0,preview:"font-family font-size"},{selector:"img",collapsed:!1,styles:{display:"block",marginLeft:"auto",marginRight:"auto"},preview:!1},{selector:"table",collapsed:!1,styles:{marginLeft:"auto",marginRight:"auto"},preview:"font-family font-size"}],alignright:[{selector:"figure.image",collapsed:!1,classes:"align-right",ceFalseOverride:!0,preview:"font-family font-size"},{selector:"figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li",styles:{textAlign:"right"},inherit:!1,preview:"font-family font-size",defaultBlock:"div"},{selector:"img,table",collapsed:!1,styles:{"float":"right"},preview:"font-family font-size"}],alignjustify:[{selector:"figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li",styles:{textAlign:"justify"},inherit:!1,defaultBlock:"div",preview:"font-family font-size"}],bold:[{inline:"strong",remove:"all",preserve_attributes:["class","style"]},{inline:"span",styles:{fontWeight:"bold"}},{inline:"b",remove:"all",preserve_attributes:["class","style"]}],italic:[{inline:"em",remove:"all",preserve_attributes:["class","style"]},{inline:"span",styles:{fontStyle:"italic"}},{inline:"i",remove:"all",preserve_attributes:["class","style"]}],underline:[{inline:"span",styles:{textDecoration:"underline"},exact:!0},{inline:"u",remove:"all",preserve_attributes:["class","style"]}],strikethrough:[{inline:"span",styles:{textDecoration:"line-through"},exact:!0},{inline:"strike",remove:"all",preserve_attributes:["class","style"]}],forecolor:{inline:"span",styles:{color:"%value"},links:!0,remove_similar:!0,clear_child_styles:!0},hilitecolor:{inline:"span",styles:{backgroundColor:"%value"},links:!0,remove_similar:!0,clear_child_styles:!0},fontname:{inline:"span",toggle:!1,styles:{fontFamily:"%value"},clear_child_styles:!0},fontsize:{inline:"span",toggle:!1,styles:{fontSize:"%value"},clear_child_styles:!0},lineheight:{selector:"h1,h2,h3,h4,h5,h6,p,li,td,th,div",defaultBlock:"p",styles:{lineHeight:"%value"}},fontsize_class:{inline:"span",attributes:{"class":"%value"}},blockquote:{block:"blockquote",wrapper:!0,remove:"all"},subscript:{inline:"sub"},superscript:{inline:"sup"},code:{inline:"code"},link:{inline:"a",selector:"a",remove:"all",split:!0,deep:!0,onmatch:function(e,t,n){return Nn(e)&&e.hasAttribute("href")},onformat:function(n,e,t){xt.each(t,function(e,t){r.setAttrib(n,t,e)})}},removeformat:[{selector:"b,strong,em,i,font,u,strike,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins",remove:"all",split:!0,expand:!1,block_expand:!0,deep:!0},{selector:"span",attributes:["style","class"],remove:"empty",split:!0,expand:!1,deep:!0},{selector:"*",attributes:["style","class"],split:!1,expand:!1,deep:!0}]},xt.each("p h1 h2 h3 h4 h5 h6 div address pre div dt dd samp".split(/\s/),function(e){t[e]={block:e,remove:"all"}}),t)),o(e.getParam("formats")),{get:function(e){return e?n[e]:n},has:function(e){return me(n,e)},register:o,unregister:function(e){return e&&n[e]&&delete n[e],n}}}var nb,rb,ob=xt.each,ib=bu.DOM,ab=function(e,t){var n,o,r,m=t&&t.schema||pi({}),p=function(e){o="string"==typeof e?{name:e,classes:[],attrs:{}}:e;var t,n,r=ib.create(o.name);return t=r,(n=o).classes.length&&ib.addClass(t,n.classes.join(" ")),ib.setAttribs(t,n.attrs),r},g=function(n,e,t){var r,o,i,a,u,s,c,l=0<e.length&&e[0],f=l&&l.name,d=(a=f,u="string"!=typeof(i=n)?i.nodeName.toLowerCase():i,s=m.getElementRule(u),!(!(c=s&&s.parentsRequired)||!c.length)&&(a&&-1!==xt.inArray(c,a)?a:c[0]));if(d)f===d?(o=e[0],e=e.slice(1)):o=d;else if(l)o=e[0],e=e.slice(1);else if(!t)return n;return o&&(r=p(o)).appendChild(n),t&&(r||(r=ib.create("div")).appendChild(n),xt.each(t,function(e){var t=p(e);r.insertBefore(t,n)})),g(r,e,o&&o.siblings)};return e&&e.length?(o=e[0],n=p(o),(r=ib.create("div")).appendChild(g(n,e.slice(1),o.siblings)),r):""},ub=function(e){var t,a={classes:[],attrs:{}};return"*"!==(e=a.selector=xt.trim(e))&&(t=e.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g,function(e,t,n,r,o){switch(t){case"#":a.attrs.id=n;break;case".":a.classes.push(n);break;case":":-1!==xt.inArray("checked disabled enabled read-only required".split(" "),n)&&(a.attrs[n]=n)}var i;return"["!==r||(i=o.match(/([\w\-]+)(?:\=\"([^\"]+))?/))&&(a.attrs[i[1]]=i[2]),""})),a.name=t||"div",a},sb=function(n,e){var t,r,o,i="",a=(o=n.getParam("preview_styles","font-family font-size font-weight font-style text-decoration text-transform color background-color border border-radius outline text-shadow"),q(o)?o:"");if(""===a)return"";var u=function(e){return e.replace(/%(\w+)/g,"")};if("string"==typeof e){if(!(e=n.formatter.get(e)))return;e=e[0]}if("preview"in e){var s=de(e,"preview");if(s.is(!1))return"";a=s.getOr(a)}t=e.block||e.inline||"span";var c,l=(c=e.selector)&&"string"==typeof c?(c=(c=c.split(/\s*,\s*/)[0]).replace(/\s*(~\+|~|\+|>)\s*/g,"$1"),xt.map(c.split(/(?:>|\s+(?![^\[\]]+\]))/),function(e){var t=xt.map(e.split(/(?:~\+|~|\+)/),ub),n=t.pop();return t.length&&(n.siblings=t),n}).reverse()):[],f=l.length?(l[0].name||(l[0].name=t),t=e.selector,ab(l,n)):ab([t],n),d=ib.select(t,f)[0]||f.firstChild;return ob(e.styles,function(e,t){var n=u(e);n&&ib.setStyle(d,t,n)}),ob(e.attributes,function(e,t){var n=u(e);n&&ib.setAttrib(d,t,n)}),ob(e.classes,function(e){var t=u(e);ib.hasClass(d,t)||ib.addClass(d,t)}),n.fire("PreviewFormats"),ib.setStyles(f,{position:"absolute",left:-65535}),n.getBody().appendChild(f),r=ib.getStyle(n.getBody(),"fontSize",!0),r=/px$/.test(r)?parseInt(r,10):0,ob(a.split(" "),function(e){var t=ib.getStyle(d,e,!0);if(!("background-color"===e&&/transparent|rgba\s*\([^)]+,\s*0\)/.test(t)&&(t=ib.getStyle(n.getBody(),e,!0),"#ffffff"===ib.toHex(t).toLowerCase())||"color"===e&&"#000000"===ib.toHex(t).toLowerCase())){if("font-size"===e&&/em|%$/.test(t)){if(0===r)return;t=parseFloat(t)/(/%$/.test(t)?100:1)*r+"px"}"border"===e&&t&&(i+="padding:0 2px;"),i+=e+":"+t+";"}}),n.fire("AfterPreviewFormats"),ib.remove(f),i},cb=function(s){var e=tb(s),t=ku(null);return function(e){e.addShortcut("meta+b","","Bold"),e.addShortcut("meta+i","","Italic"),e.addShortcut("meta+u","","Underline");for(var t=1;t<=6;t++)e.addShortcut("access+"+t,"",["FormatBlock",!1,"h"+t]);e.addShortcut("access+7","",["FormatBlock",!1,"p"]),e.addShortcut("access+8","",["FormatBlock",!1,"div"]),e.addShortcut("access+9","",["FormatBlock",!1,"address"])}(s),sh(s),{get:e.get,has:e.has,register:e.register,unregister:e.unregister,apply:function(e,t,n){var r,o,i;r=e,o=t,i=n,Nv(s).formatter.apply(r,o,i)},remove:function(e,t,n,r){var o,i,a,u;o=e,i=t,a=n,u=r,Nv(s).formatter.remove(o,i,a,u)},toggle:function(e,t,n){var r,o,i;r=e,o=t,i=n,Nv(s).formatter.toggle(r,o,i)},match:E(Xg,s),matchAll:E(Yg,s),matchNode:E(Kg,s),canApply:E(Gg,s),formatChanged:E(eb,s,t),getCssText:E(sb,s)}},lb=function(n,r,o){var i=ku(!1),a=function(e){gv(r,!1,o),r.add({},e)};n.on("init",function(){r.add()}),n.on("BeforeExecCommand",function(e){var t=e.command.toLowerCase();"undo"!==t&&"redo"!==t&&"mcerepaint"!==t&&(hv(r,o),r.beforeChange())}),n.on("ExecCommand",function(e){var t=e.command.toLowerCase();"undo"!==t&&"redo"!==t&&"mcerepaint"!==t&&a(e)}),n.on("ObjectResizeStart cut",function(){r.beforeChange()}),n.on("SaveContent ObjectResized blur",a),n.on("dragend",a),n.on("keyup",function(e){var t=e.keyCode;e.isDefaultPrevented()||((33<=t&&t<=36||37<=t&&t<=40||45===t||e.ctrlKey)&&(a(),n.nodeChanged()),46!==t&&8!==t||n.nodeChanged(),i.get()&&r.typing&&!1===mv(cv(n),r.data[0])&&(!1===n.isDirty()&&(n.setDirty(!0),n.fire("change",{level:r.data[0],lastLevel:null})),n.fire("TypingUndo"),i.set(!1),n.nodeChanged()))}),n.on("keydown",function(e){var t,n=e.keyCode;e.isDefaultPrevented()||(33<=n&&n<=36||37<=n&&n<=40||45===n?r.typing&&a(e):(t=e.ctrlKey&&!e.altKey||e.metaKey,!(n<16||20<n)||224===n||91===n||r.typing||t||(r.beforeChange(),gv(r,!0,o),r.add({},e),i.set(!0))))}),n.on("mousedown",function(e){r.typing&&a(e)});n.on("input",function(e){var t,n;e.inputType&&("insertReplacementText"===e.inputType||"insertText"===(n=e).inputType&&null===n.data||("insertFromPaste"===(t=e).inputType||"insertFromDrop"===t.inputType))&&a(e)}),n.on("AddUndo Undo Redo ClearUndos",function(e){e.isDefaultPrevented()||n.nodeChanged()})},fb=function(s){var e,c=ku(U.none()),l=ku(0),f=ku(0),d={data:[],typing:!1,beforeChange:function(){var e,t;e=l,t=c,Nv(s).undoManager.beforeChange(e,t)},add:function(e,t){return n=d,r=f,o=l,i=c,a=e,u=t,Nv(s).undoManager.addUndoLevel(n,r,o,i,a,u);var n,r,o,i,a,u},undo:function(){return e=d,t=l,n=f,Nv(s).undoManager.undo(e,t,n);var e,t,n},redo:function(){return e=s,t=f,n=d.data,Nv(e).undoManager.redo(t,n);var e,t,n},clear:function(){var e,t;e=d,t=f,Nv(s).undoManager.clear(e,t)},reset:function(){var e;e=d,Nv(s).undoManager.reset(e)},hasUndo:function(){return e=d,t=f,Nv(s).undoManager.hasUndo(e,t);var e,t},hasRedo:function(){return e=d,t=f,Nv(s).undoManager.hasRedo(e,t);var e,t},transact:function(e){return t=d,n=l,r=e,Nv(s).undoManager.transact(t,n,r);var t,n,r},ignore:function(e){var t,n;t=l,n=e,Nv(s).undoManager.ignore(t,n)},extra:function(e,t){var n,r,o,i;n=d,r=f,o=e,i=t,Nv(s).undoManager.extra(n,r,o,i)}};return xv(s)||lb(s,d,l),(e=s).addShortcut("meta+z","","Undo"),e.addShortcut("meta+y,meta+shift+z","","Redo"),d},db=[9,27,Gf.HOME,Gf.END,19,20,44,144,145,33,34,45,16,17,18,91,92,93,Gf.DOWN,Gf.UP,Gf.LEFT,Gf.RIGHT].concat(vt.browser.isFirefox()?[224]:[]),mb="data-mce-placeholder",pb=function(e){return"keydown"===e.type||"keyup"===e.type},gb=function(e){var t=e.keyCode;return t===Gf.BACKSPACE||t===Gf.DELETE},hb=function(a){var e,u=a.dom,s=fc(a),c=(e=a).getParam("placeholder",sc.getAttrib(e.getElement(),"placeholder"),"string"),l=function(e,t){var n,r,o,i;!function(e){if(pb(e)){var t=e.keyCode;return!gb(e)&&(Gf.metaKeyPressed(e)||e.altKey||112<=t&&t<=123||I(db,t))}return!1}(e)&&(n=a.getBody(),r=!(pb(o=e)&&!(gb(o)||"keyup"===o.type&&229===o.keyCode))&&function(e,t,n){if(Uo(Nt.fromDom(t),!1)){var r=""===n,o=t.firstElementChild;return!o||!e.getStyle(t.firstElementChild,"padding-left")&&!e.getStyle(t.firstElementChild,"padding-right")&&(r?!e.isBlock(o):n===o.nodeName.toLowerCase())}return!1}(u,n,s),""!==u.getAttrib(n,mb)===r&&!t||(u.setAttrib(n,mb,r?c:null),u.setAttrib(n,"aria-placeholder",r?c:null),i=r,a.fire("PlaceholderToggle",{state:i}),a.on(r?"keydown":"keyup",l),a.off(r?"keyup":"keydown",l)))};c&&a.on("init",function(e){l(e,!0),a.on("change SetContent ExecCommand",l),a.on("paste",function(e){return Fr.setEditorTimeout(a,function(){return l(e)})})})},vb=/[\u0591-\u07FF\uFB1D-\uFDFF\uFE70-\uFEFC]/,yb=function(e,t){return kt(Nt.fromDom(t),e.getParam("inline_boundaries_selector","a[href],code,.mce-annotation","string"))},bb=function(e){return"rtl"===bu.DOM.getStyle(e,"direction",!0)||(t=e.textContent,vb.test(t));var t},Cb=function(e,t,n){var r,o,i,a=(r=e,o=t,i=n,j(bu.DOM.getParents(i.container(),"*",o),r));return U.from(a[a.length-1])},wb=function(e,t){if(!t)return t;var n=t.container(),r=t.offset();return e?fo(n)?On(n.nextSibling)?Us(n.nextSibling,0):Us.after(n):go(t)?Us(n,r+1):t:fo(n)?On(n.previousSibling)?Us(n.previousSibling,n.previousSibling.data.length):Us.before(n):ho(t)?Us(n,r-1):t},xb=E(wb,!0),Sb=E(wb,!1),Nb=function(e,t){return At(e,t)?Sr(t,function(e){return Jr(e)||Zr(e)},(n=e,function(e){return Rt(n,Nt.fromDom(e.dom.parentNode))})):U.none();var n},Eb=function(e){var t,n,r;e.dom.isEmpty(e.getBody())&&(e.setContent(""),n=(t=e).getBody(),r=n.firstChild&&t.dom.isBlock(n.firstChild)?n.firstChild:n,t.selection.setCursorLocation(r,0))},kb=function(e,t){return{from:e,to:t}},_b=function(e,t){var n=Nt.fromDom(e),r=Nt.fromDom(t.container());return Nb(n,r).map(function(e){return{block:e,position:t}})},Rb=function(o,i,e){var t=_b(o,Us.fromRangeStart(e)),n=t.bind(function(e){return kl(i,o,e.position).bind(function(e){return _b(o,e).map(function(e){return t=o,n=i,In((r=e).position.getNode())&&!1===Uo(r.block)?Tl(!1,r.block.dom).bind(function(e){return e.isEqual(r.position)?kl(n,t,e).bind(function(e){return _b(t,e)}):U.some(r)}).getOr(r):r;var t,n,r})})});return as(t,n,kb).filter(function(e){return!1===Rt((r=e).from.block,r.to.block)&&jt((n=e).from.block).bind(function(t){return jt(n.to.block).filter(function(e){return Rt(t,e)})}).isSome()&&(!1===Un((t=e).from.block.dom)&&!1===Un(t.to.block.dom));var t,n,r})},Tb=function(e){var t,n=(t=Wt(e),X(t,Xr).fold(function(){return t},function(e){return t.slice(0,e)}));return $(n,ln),n},Ab=function(e,t){var n=up(t,e);return K(n.reverse(),function(e){return Uo(e)}).each(ln)},Db=function(e,t,n,r){if(Uo(n))return rp(n),Ol(n.dom);0===j(qt(r),function(e){return!Uo(e)}).length&&Uo(t)&&rn(r,Nt.fromTag("br"));var o=Dl(n.dom,Us.before(r.dom));return $(Tb(t),function(e){rn(r,e)}),Ab(e,t),o},Ob=function(e,t,n){if(Uo(n))return ln(n),Uo(t)&&rp(t),Ol(t.dom);var r=Bl(n.dom);return $(Tb(t),function(e){un(n,e)}),Ab(e,t),r},Bb=function(e,t){return At(t,e)?(n=up(e,t),U.from(n[n.length-1])):U.none();var n},Pb=function(e,t){Tl(e,t.dom).map(function(e){return e.getNode()}).map(Nt.fromDom).filter(Gr).each(ln)},Lb=function(e,t,n){return Pb(!0,t),Pb(!1,n),Bb(t,n).fold(E(Ob,e,t,n),E(Db,e,t,n))},Ib=function(e,t,n,r){return t?Lb(e,r,n):Lb(e,n,r)},Mb=function(t,n){var e,r,o,i=Nt.fromDom(t.getBody()),a=(e=i.dom,r=n,((o=t.selection.getRng()).collapsed?Rb(e,r,o):U.none()).bind(function(e){return Ib(i,n,e.from.block,e.to.block)}));return a.each(function(e){t.selection.setRng(e.toRange())}),a.isSome()},Fb=function(e,t){var n=Nt.fromDom(t),r=E(Rt,e);return xr(n,to,r).isSome()},Ub=function(e,t){var n,r,o=Dl(e.dom,Us.fromRangeStart(t)).isNone(),i=Al(e.dom,Us.fromRangeEnd(t)).isNone();return!(Fb(n=e,(r=t).startContainer)||Fb(n,r.endContainer))&&o&&i},zb=function(e){var n,r,o,t,i=Nt.fromDom(e.getBody()),a=e.selection.getRng();return Ub(i,a)?((t=e).setContent(""),t.selection.setCursorLocation(),!0):(n=i,r=e.selection,o=r.getRng(),as(Nb(n,Nt.fromDom(o.startContainer)),Nb(n,Nt.fromDom(o.endContainer)),function(e,t){return!1===Rt(e,t)&&(o.deleteContents(),Ib(n,!0,e,t).each(function(e){r.setRng(e.toRange())}),!0)}).getOr(!1))},jb=function(e,t){return!e.selection.isCollapsed()&&zb(e)},Hb=Fn,Vb=Un,qb=function(e,t,n,r,o){return U.from(t._selectionOverrides.showCaret(e,n,r,o))},$b=function(e,t){var n,r;return e.fire("BeforeObjectSelected",{target:t}).isDefaultPrevented()?U.none():U.some(((r=(n=t).ownerDocument.createRange()).selectNode(n),r))},Wb=function(e,t,n){var r=ol(1,e.getBody(),t),o=Us.fromRangeStart(r),i=o.getNode();if(zc(i))return qb(1,e,i,!o.isAtEnd(),!1);var a=o.getNode(!0);if(zc(a))return qb(1,e,a,!1,!1);var u=e.dom.getParent(o.getNode(),function(e){return Vb(e)||Hb(e)});return zc(u)?qb(1,e,u,!1,n):U.none()},Kb=function(e,t,n){return t.collapsed?Wb(e,t,n).getOr(t):t},Xb=function(e){return ep(e)||Gm(e)},Yb=function(e){return tp(e)||Jm(e)},Gb=function(n,r,e,t,o,i){var a,u;return qb(t,n,i.getNode(!o),o,!0).each(function(e){var t;r.collapsed?(t=r.cloneRange(),o?t.setEnd(e.startContainer,e.startOffset):t.setStart(e.endContainer,e.endOffset),t.deleteContents()):r.deleteContents(),n.selection.setRng(e)}),a=n.dom,On(u=e)&&0===u.data.length&&a.remove(u),!0},Jb=function(e,t){var n=e.selection.getRng();if(!On(n.commonAncestorContainer))return!1;var r=t?Ms.Forwards:Ms.Backwards,o=wl(e.getBody()),i=E(sl,t?o.next:o.prev),a=t?Xb:Yb,u=al(r,e.getBody(),n),s=wb(t,i(u));if(!s||!cl(u,s))return!1;if(a(s))return Gb(e,n,u.getNode(),r,t,s);var c=i(s);return!!(c&&a(c)&&cl(s,c))&&Gb(e,n,u.getNode(),r,t,c)},Qb=gr([{remove:["element"]},{moveToElement:["element"]},{moveToPosition:["position"]}]),Zb=function(e,t,n,r){var o=r.getNode(!1===t);return Nb(Nt.fromDom(e),Nt.fromDom(n.getNode())).map(function(e){return Uo(e)?Qb.remove(e.dom):Qb.moveToElement(o)}).orThunk(function(){return U.some(Qb.moveToElement(o))})},eC=function(u,s,c){return kl(s,u,c).bind(function(e){return a=e.getNode(),to(Nt.fromDom(a))||Zr(Nt.fromDom(a))?U.none():(t=u,o=e,i=function(e){return Yr(Nt.fromDom(e))&&!Qc(r,o,t)},il(!(n=s),r=c).fold(function(){return il(n,o).fold(p,i)},i)?U.none():s&&Un(e.getNode())||!1===s&&Un(e.getNode(!0))?Zb(u,s,c,e):s&&tp(c)||!1===s&&ep(c)?U.some(Qb.moveToPosition(e)):U.none());var t,n,r,o,i,a})},tC=function(r,e,o){return i=e,a=o.getNode(!1===i),u=i?"after":"before",Nn(a)&&a.getAttribute("data-mce-caret")===u?(t=e,n=o.getNode(!1===e),(t&&Un(n.nextSibling)?U.some(Qb.moveToElement(n.nextSibling)):!1===t&&Un(n.previousSibling)?U.some(Qb.moveToElement(n.previousSibling)):U.none()).fold(function(){return eC(r,e,o)},U.some)):eC(r,e,o).bind(function(e){return t=r,n=o,e.fold(function(e){return U.some(Qb.remove(e))},function(e){return U.some(Qb.moveToElement(e))},function(e){return Qc(n,e,t)?U.none():U.some(Qb.moveToPosition(e))});var t,n});var t,n,i,a,u},nC=function(e,t){return U.from(Xf(e.getBody(),t))},rC=function(a,u){var e=a.selection.getNode();return nC(a,e).filter(Un).fold(function(){return e=a.getBody(),t=u,n=a.selection.getRng(),r=ol(t?1:-1,e,n),o=Us.fromRangeStart(r),i=Nt.fromDom(e),(!1===t&&tp(o)?U.some(Qb.remove(o.getNode(!0))):t&&ep(o)?U.some(Qb.remove(o.getNode())):!1===t&&ep(o)&&bp(i,o)?Cp(i,o).map(function(e){return Qb.remove(e.getNode())}):t&&tp(o)&&yp(i,o)?wp(i,o).map(function(e){return Qb.remove(e.getNode())}):tC(e,t,o)).exists(function(e){return e.fold(function(e){return o._selectionOverrides.hideFakeCaret(),Gp(o,i,Nt.fromDom(e)),!0},(r=i=u,function(e){var t=r?Us.before(e):Us.after(e);return n.selection.setRng(t.toRange()),!0}),(t=n=o=a,function(e){return t.selection.setRng(e.toRange()),!0}));var t,n,r,o,i});var e,t,n,r,o,i},k)},oC=function(t,n){var e=t.selection.getNode();return!!Un(e)&&nC(t,e.parentNode).filter(Un).fold(function(){var e;return e=Nt.fromDom(t.getBody()),$(qu(e,".mce-offscreen-selection"),ln),Gp(t,n,Nt.fromDom(t.selection.getNode())),Eb(t),!0},function(){return!0})},iC=function(e){var t,n=e.dom,r=e.selection,o=Xf(e.getBody(),r.getNode());return Fn(o)&&n.isBlock(o)&&n.isEmpty(o)&&(t=n.create("br",{"data-mce-bogus":"1"}),n.setHTML(o,""),o.appendChild(t),r.setRng(Us.before(t).toRange())),!0},aC=function(e,t){return(e.selection.isCollapsed()?rC:oC)(e,t)},uC=function(e,t){return!!e.selection.isCollapsed()&&(n=e,r=t,o=Us.fromRangeStart(n.selection.getRng()),kl(r,n.getBody(),o).filter(function(e){return(r?Xm:Ym)(e)}).bind(function(e){return U.from(Zc(r?0:-1,e))}).exists(function(e){return n.selection.select(e),!0}));var n,r,o},sC=On,cC=function(e){return sC(e)&&e.data[0]===io},lC=function(e){return sC(e)&&e.data[e.data.length-1]===io},fC=function(e){return e.ownerDocument.createTextNode(io)},dC=function(e,t){return(e?function(e){if(sC(e.previousSibling))return lC(e.previousSibling)||e.previousSibling.appendData(io),e.previousSibling;if(sC(e))return cC(e)||e.insertData(0,io),e;var t=fC(e);return e.parentNode.insertBefore(t,e),t}:function(e){if(sC(e.nextSibling))return cC(e.nextSibling)||e.nextSibling.insertData(0,io),e.nextSibling;if(sC(e))return lC(e)||e.appendData(io),e;var t=fC(e);return e.nextSibling?e.parentNode.insertBefore(t,e.nextSibling):e.parentNode.appendChild(t),t})(t)},mC=E(dC,!0),pC=E(dC,!1),gC=function(e,t){return On(e.container())?dC(t,e.container()):dC(t,e.getNode())},hC=function(e,t){var n=t.get();return n&&e.container()===n&&fo(n)},vC=function(n,e){return e.fold(function(e){Oc(n.get());var t=mC(e);return n.set(t),U.some(Us(t,t.length-1))},function(e){return Ol(e).map(function(e){if(hC(e,n))return Us(n.get(),1);Oc(n.get());var t=gC(e,!0);return n.set(t),Us(t,1)})},function(e){return Bl(e).map(function(e){if(hC(e,n))return Us(n.get(),n.get().length-1);Oc(n.get());var t=gC(e,!1);return n.set(t),Us(t,t.length-1)})},function(e){Oc(n.get());var t=pC(e);return n.set(t),U.some(Us(t,1))})},yC=function(e,t){for(var n=0;n<e.length;n++){var r=e[n].apply(null,t);if(r.isSome())return r}return U.none()},bC=gr([{before:["element"]},{start:["element"]},{end:["element"]},{after:["element"]}]),CC=function(e,t){var n=Jc(t,e);return n||e},wC=function(e,t,n){var r=xb(n),o=CC(t,r.container());return Cb(e,o,r).fold(function(){return Al(o,r).bind(E(Cb,e,o)).map(function(e){return bC.before(e)})},U.none)},xC=function(e,t){return null===Il(e,t)},SC=function(e,t,n){return Cb(e,t,n).filter(E(xC,t))},NC=function(e,t,n){var r=Sb(n);return SC(e,t,r).bind(function(e){return Dl(e,r).isNone()?U.some(bC.start(e)):U.none()})},EC=function(e,t,n){var r=xb(n);return SC(e,t,r).bind(function(e){return Al(e,r).isNone()?U.some(bC.end(e)):U.none()})},kC=function(e,t,n){var r=Sb(n),o=CC(t,r.container());return Cb(e,o,r).fold(function(){return Dl(o,r).bind(E(Cb,e,o)).map(function(e){return bC.after(e)})},U.none)},_C=function(e){return!1===bb(TC(e))},RC=function(e,t,n){return yC([wC,NC,EC,kC],[e,t,n]).filter(_C)},TC=function(e){return e.fold(o,o,o,o)},AC=function(e){return e.fold(N("before"),N("start"),N("end"),N("after"))},DC=function(e){return e.fold(bC.before,bC.before,bC.after,bC.after)},OC=function(e){return e.fold(bC.start,bC.start,bC.end,bC.end)},BC=function(a,e,u,t,n,s){return as(Cb(e,u,t),Cb(e,u,n),function(e,t){return e!==t&&(r=t,o=Jc(e,n=u),i=Jc(r,n),o&&o===i)?bC.after(a?e:t):s;var n,r,o,i}).getOr(s)},PC=function(e,r){return e.fold(k,function(e){return n=r,!(AC(t=e)===AC(n)&&TC(t)===TC(n));var t,n})},LC=function(e,t){return e?t.fold(a(U.some,bC.start),U.none,a(U.some,bC.after),U.none):t.fold(U.none,a(U.some,bC.before),U.none,a(U.some,bC.end))},IC=function(e,a,u,s){var t=wb(e,s),c=RC(a,u,t);return RC(a,u,t).bind(E(LC,e)).orThunk(function(){return n=a,r=u,o=c,i=wb(t=e,s),kl(t,r,i).map(E(wb,t)).fold(function(){return o.map(DC)},function(e){return RC(n,r,e).map(E(BC,t,n,r,i,e)).filter(E(PC,o))}).filter(_C);var t,n,r,o,i})},MC=(E(IC,!1),E(IC,!0),function(e,t,n){var r=e?1:-1;return t.setRng(Us(n.container(),n.offset()+r).toRange()),t.getSel().modify("move",e?"forward":"backward","word"),!0}),FC=function(e,t){var n=t.selection.getRng(),r=e?Us.fromRangeEnd(n):Us.fromRangeStart(n);return!!A(t.selection.getSel().modify)&&(e&&go(r)?MC(!0,t.selection,r):!(e||!ho(r))&&MC(!1,t.selection,r))},UC=function(e,t){var n=e.dom.createRng();n.setStart(t.container(),t.offset()),n.setEnd(t.container(),t.offset()),e.selection.setRng(n)},zC=function(e,t){e?t.setAttribute("data-mce-selected","inline-boundary"):t.removeAttribute("data-mce-selected")},jC=function(t,e,n){return vC(e,n).map(function(e){return UC(t,e),n})},HC=function(e,t){var n,r;e.selection.isCollapsed()&&!0!==e.composing&&t.get()&&(n=Us.fromRangeStart(e.selection.getRng()),Us.isTextPosition(n)&&!1===(go(r=n)||ho(r))&&(UC(e,Dc(t.get(),n)),t.set(null)))},VC=function(e,t,n){return!!wc(e)&&(o=t,i=n,a=(r=e).getBody(),u=Us.fromRangeStart(r.selection.getRng()),s=E(yb,r),IC(i,s,a,u).bind(function(e){return jC(r,o,e)}).isSome());var r,o,i,a,u,s},qC=function(e,t,n){return!!wc(t)&&FC(e,t)},$C=function(d){var m=ku(null),p=E(yb,d);return d.on("NodeChange",function(e){var n,r,o,t,i,a,u,s,c,l,f;!wc(d)||vt.browser.isIE()&&e.initial||(a=p,u=d.dom,s=e.parents,c=F(qu(Nt.fromDom(u.getRoot()),'*[data-mce-selected="inline-boundary"]'),function(e){return e.dom}),l=j(c,a),f=j(s,a),$(Q(l,f),E(zC,!1)),$(Q(f,l),E(zC,!0)),HC(d,m),n=p,r=d,o=m,t=e.parents,r.selection.isCollapsed()&&(i=j(t,n),$(i,function(e){var t=Us.fromRangeStart(r.selection.getRng());RC(n,r.getBody(),t).bind(function(e){return jC(r,o,e)})})))}),m},WC=E(qC,!0),KC=E(qC,!1),XC=function(t,n){return function(e){return vC(n,e).exists(function(e){return UC(t,e),!0})}},YC=function(r,o,i,a){var u=r.getBody(),s=E(yb,r);r.undoManager.ignore(function(){var e,t,n;r.selection.setRng((e=i,t=a,(n=document.createRange()).setStart(e.container(),e.offset()),n.setEnd(t.container(),t.offset()),n)),r.execCommand("Delete"),RC(s,u,Us.fromRangeStart(r.selection.getRng())).map(OC).map(XC(r,o))}),r.nodeChanged()},GC=function(n,r,i,o){var e,t,a=(e=n.getBody(),t=o.container(),Jc(t,e)||e),u=E(yb,n),s=RC(u,a,o);return s.bind(function(e){return i?e.fold(N(U.some(OC(e))),U.none,N(U.some(DC(e))),U.none):e.fold(U.none,N(U.some(DC(e))),U.none,N(U.some(OC(e))))}).map(XC(n,r)).getOrThunk(function(){var t=_l(i,a,o),e=t.bind(function(e){return RC(u,a,e)});return as(s,e,function(){return Cb(u,a,o).exists(function(e){return!!as(Ol(o=e),Bl(o),function(e,t){var n=wb(!0,e),r=wb(!1,t);return Al(o,n).forall(function(e){return e.isEqual(r)})}).getOr(!0)&&(Gp(n,i,Nt.fromDom(e)),!0);var o})}).orThunk(function(){return e.bind(function(e){return t.map(function(e){return i?YC(n,r,o,e):YC(n,r,e,o),!0})})}).getOr(!1)})},JC=function(e,t,n){if(e.selection.isCollapsed()&&wc(e)){var r=Us.fromRangeStart(e.selection.getRng());return GC(e,t,n,r)}return!1},QC=function(e){return 1===Wt(e).length},ZC=function(e,t,n,r){var o,i,a,u,s,c=E(ch,t),l=F(j(r,c),function(e){return e.dom});0===l.length?Gp(t,e,n):(i=n.dom,a=l,u=nh(!1),s=ah(a,u.dom),rn(Nt.fromDom(i),u),ln(Nt.fromDom(i)),o=Us(s,0),t.selection.setRng(o.toRange()))},ew=function(r,o){var t,e=Nt.fromDom(r.getBody()),n=Nt.fromDom(r.selection.getStart()),s=j((t=up(n,e),X(t,Xr).fold(N(t),function(e){return t.slice(0,e)})),QC);return ee(s).exists(function(e){var t,i,a,u,n=Us.fromRangeStart(r.selection.getRng());return i=o,a=n,u=e.dom,!(!as(Ol(u),Bl(u),function(e,t){var n=wb(!0,e),r=wb(!1,t),o=wb(!1,a);return i?Al(u,o).exists(function(e){return e.isEqual(r)&&a.isEqual(n)}):Dl(u,o).exists(function(e){return e.isEqual(n)&&a.isEqual(r)})}).getOr(!0)||Ll((t=e).dom)&&eh(t.dom))&&(ZC(o,r,e,s),!0)})},tw=function(e,t){return!!e.selection.isCollapsed()&&ew(e,t)},nw=function(e,t,n){return e._selectionOverrides.hideFakeCaret(),Gp(e,t,Nt.fromDom(n)),!0},rw=function(e,t){return e.selection.isCollapsed()?(i=e,u=(a=t)?Gm:Jm,s=a?Ms.Forwards:Ms.Backwards,c=al(s,i.getBody(),i.selection.getRng()),u(c)?nw(i,a,c.getNode(!a)):U.from(wb(a,c)).filter(function(e){return u(e)&&cl(c,e)}).exists(function(e){return nw(i,a,e.getNode(!a))})):(r=t,o=(n=e).selection.getNode(),!!jn(o)&&nw(n,r,o));var n,r,o,i,a,u,s,c},ow=function(e){var t=parseInt(e,10);return isNaN(t)?0:t},iw=function(e,t){return(e||"table"===Dt(t)?"margin":"padding")+("rtl"===Yn(t,"direction")?"-right":"-left")},aw=function(e){var r,t=sw(e);return!e.mode.isReadOnly()&&(1<t.length||(r=e,G(t,function(e){var t=iw(vc(r),e),n=Jn(e,t).map(ow).getOr(0);return"false"!==r.dom.getContentEditable(e.dom)&&0<n})))},uw=function(e){return Qr(e)||Zr(e)},sw=function(e){return j(F(e.selection.getSelectedBlocks(),Nt.fromDom),function(e){return!uw(e)&&!jt(e).map(uw).getOr(!1)&&Sr(e,function(e){return Fn(e.dom)||Un(e.dom)}).exists(function(e){return Fn(e.dom)})})},cw=function(e,c){var l=e.dom,t=e.selection,n=e.formatter,r=e.getParam("indentation","40px","string"),f=/[a-z%]+$/i.exec(r)[0],d=parseInt(r,10),m=vc(e),o=fc(e);e.queryCommandState("InsertUnorderedList")||e.queryCommandState("InsertOrderedList")||""!==o||l.getParent(t.getNode(),l.isBlock)||n.apply("div"),$(sw(e),function(e){var t,n,r,o,i,a,u,s;t=l,n=c,r=m,o=d,i=f,a=e.dom,s=iw(r,Nt.fromDom(a)),"outdent"===n?(u=Math.max(0,ow(a.style[s])-o),t.setStyle(a,s,u?u+i:"")):(u=ow(a.style[s])+o+i,t.setStyle(a,s,u))})},lw=function(e,t){if(e.selection.isCollapsed()&&aw(e)){var n=e.dom,r=e.selection.getRng(),o=Us.fromRangeStart(r),i=n.getParent(r.startContainer,n.isBlock);if(null!==i&&dp(Nt.fromDom(i),o))return cw(e,"outdent"),!0}return!1},fw=function(e,t){e.getDoc().execCommand(t,!1,null)},dw=function(n,r){n.addCommand("delete",function(){var e,t;t=r,lw(e=n)||aC(e,!1)||Jb(e,!1)||JC(e,t,!1)||Mb(e,!1)||Sg(e)||uC(e,!1)||rw(e,!1)||jb(e)||tw(e,!1)||(fw(e,"Delete"),Eb(e))}),n.addCommand("forwardDelete",function(){var e,t;t=r,aC(e=n,!0)||Jb(e,!0)||JC(e,t,!0)||Mb(e,!0)||Sg(e)||uC(e,!0)||rw(e,!0)||jb(e)||tw(e,!0)||fw(e,"ForwardDelete")})},mw=function(e){return e.touches===undefined||1!==e.touches.length?U.none():U.some(e.touches[0])},pw=function(a){var u=ku(U.none()),s=ku(!1),r=Lu(function(e){a.fire("longpress",xe(xe({},e),{type:"longpress"})),s.set(!0)},400);a.on("touchstart",function(n){mw(n).each(function(e){r.cancel();var t={x:e.clientX,y:e.clientY,target:n.target};r.throttle(n),s.set(!1),u.set(U.some(t))})},!0),a.on("touchmove",function(e){r.cancel(),mw(e).each(function(i){u.get().each(function(e){var t,n,r,o;t=i,n=e,r=Math.abs(t.clientX-n.x),o=Math.abs(t.clientY-n.y),(5<r||5<o)&&(u.set(U.none()),s.set(!1),a.fire("longpresscancel"))})})},!0),a.on("touchend touchcancel",function(t){r.cancel(),"touchcancel"!==t.type&&u.get().filter(function(e){return e.target.isEqualNode(t.target)}).each(function(){s.get()?t.preventDefault():a.fire("tap",xe(xe({},t),{type:"tap"}))})},!0)},gw=function(e,t){return e.hasOwnProperty(t.nodeName)},hw=function(e){var t,n,r,o=e.dom,i=e.selection,a=e.schema,u=a.getBlockElements(),s=i.getStart(),c=e.getBody(),l=fc(e);if(s&&Nn(s)&&l){var f=c.nodeName.toLowerCase();if(a.isValidChild(f,l.toLowerCase())&&(d=u,m=c,p=s,!M(ap(Nt.fromDom(p),Nt.fromDom(m)),function(e){return gw(d,e.dom)}))){for(var d,m,p,g,h,v=i.getRng(),y=v.startContainer,b=v.startOffset,C=v.endContainer,w=v.endOffset,x=pm(e),s=c.firstChild;s;)if(g=u,On(h=s)||Nn(h)&&!gw(g,h)&&!$l(h)){if(function(e,t){if(On(t)){if(0===t.nodeValue.length)return!0;if(/^\s+$/.test(t.nodeValue)&&(!t.nextSibling||gw(e,t.nextSibling)))return!0}return!1}(u,s)){s=(n=s).nextSibling,o.remove(n);continue}t||(t=o.create(l,dc(e)),s.parentNode.insertBefore(t,s),r=!0),s=(n=s).nextSibling,t.appendChild(n)}else t=null,s=s.nextSibling;r&&x&&(v.setStart(y,b),v.setEnd(C,w),i.setRng(v),e.nodeChanged())}}},vw=function(e,t){var n;t.hasAttribute("data-mce-caret")&&(Co(t),(n=e).selection.setRng(n.selection.getRng()),e.selection.scrollIntoView(t))},yw=function(e,t){var n,r=(n=e,Er(Nt.fromDom(n.getBody()),"*[data-mce-caret]").fold(N(null),function(e){return e.dom}));if(r)return"compositionstart"===t.type?(t.preventDefault(),t.stopPropagation(),void vw(e,r)):void(po(r)&&(vw(e,r),e.undoManager.add()))};(rb=nb=nb||{})[rb.Br=0]="Br",rb[rb.Block=1]="Block",rb[rb.Wrap=2]="Wrap",rb[rb.Eol=3]="Eol";var bw,Cw,ww=function(e,t){return e===Ms.Backwards?J(t):t},xw=function(e,t,n,r){for(var o,i,a,u,s,c,l=wl(n),f=r,d=[];f&&(s=l,c=f,o=t===Ms.Forwards?s.next(c):s.prev(c));){if(In(o.getNode(!1)))return t===Ms.Forwards?{positions:ww(t,d).concat([o]),breakType:nb.Br,breakAt:U.some(o)}:{positions:ww(t,d),breakType:nb.Br,breakAt:U.some(o)};if(o.isVisible()){if(e(f,o)){var m=(i=t,a=f,In((u=o).getNode(i===Ms.Forwards))?nb.Br:!1===Qc(a,u)?nb.Block:nb.Wrap);return{positions:ww(t,d),breakType:m,breakAt:U.some(o)}}d.push(o),f=o}else f=o}return{positions:ww(t,d),breakType:nb.Eol,breakAt:U.none()}},Sw=function(n,r,o,e){return r(o,e).breakAt.map(function(e){var t=r(o,e).positions;return n===Ms.Backwards?t.concat(e):[e].concat(t)}).getOr([])},Nw=function(e,i){return W(e,function(e,o){return e.fold(function(){return U.some(o)},function(r){return as(Z(r.getClientRects()),Z(o.getClientRects()),function(e,t){var n=Math.abs(i-e.left);return Math.abs(i-t.left)<=n?o:r}).or(e)})},U.none())},Ew=function(t,e){return Z(e.getClientRects()).bind(function(e){return Nw(t,e.left)})},kw=E(xw,Is.isAbove,-1),_w=E(xw,Is.isBelow,1),Rw=E(Sw,-1,kw),Tw=E(Sw,1,_w),Aw=function(t){var e=function(e){return F(e,function(e){return(e=ss(e)).node=t,e})};if(Nn(t))return e(t.getClientRects());if(On(t)){var n=t.ownerDocument.createRange();return n.setStart(t,0),n.setEnd(t,t.data.length),e(n.getClientRects())}},Dw=function(e){return Y(e,Aw)};(Cw=bw=bw||{})[Cw.Up=-1]="Up",Cw[Cw.Down=1]="Down";var Ow=function(o,i,a,e,u,t){var s=0,c=[],n=function(e){var t,n,r=Dw([e]);for(-1===o&&(r=r.reverse()),t=0;t<r.length;t++)if(n=r[t],!a(n,l)){if(0<c.length&&i(n,we(c))&&s++,n.line=s,u(n))return!0;c.push(n)}},l=we(t.getClientRects());if(!l)return c;var r=t.getNode();return n(r),function(e,t,n,r){for(;r=Gc(r,e,Do,t);)if(n(r))return}(o,e,n,r),c},Bw=E(Ow,bw.Up,fs,ds),Pw=E(Ow,bw.Down,ds,fs),Lw=function(n){return function(e){return t=n,e.line>t;var t}},Iw=function(n){return function(e){return t=n,e.line===t;var t}},Mw=Un,Fw=Gc,Uw=function(e,t){return Math.abs(e.left-t)},zw=function(e,t){return Math.abs(e.right-t)},jw=function(e,t){return e>=t.left&&e<=t.right},Hw=function(e,t){return e>=t.top&&e<=t.bottom},Vw=function(e,o){return be(e,function(e,t){var n=Math.min(Uw(e,o),zw(e,o)),r=Math.min(Uw(t,o),zw(t,o));return jw(o,t)||!jw(o,e)&&(r===n&&Mw(t.node)||r<n)?t:e})},qw=function(e,t,n,r,o){var i=Fw(r,e,Do,t,!o);do{if(!i||n(i))return}while(i=Fw(i,e,Do,t))},$w=function(e,t,n){var r,o,i=Dw(j(te(e.getElementsByTagName("*")),jc)),a=j(i,E(Hw,n));if(u=Vw(a,t)){var u,s=!Tn(u.node)&&!jn(u.node);if((u=Vw(function(e,r,t){void 0===t&&(t=!0);var o=[],n=function(t,e){var n=j(Dw([e]),function(e){return!t(e,r)});return o=o.concat(n),0===n.length};return o.push(r),qw(bw.Up,e,E(n,fs),r.node,t),qw(bw.Down,e,E(n,ds),r.node,t),o}(e,u,s),t))&&jc(u.node))return o=t,{node:(r=u).node,before:Uw(r,o)<zw(r,o)}}return null},Ww=function(e,t){e.selection.setRng(t),Md(e,e.selection.getRng())},Kw=function(e,t,n){return U.some(Kb(e,t,n))},Xw=function(e,t,n,r,o,i){var a=t===Ms.Forwards,u=wl(e.getBody()),s=E(sl,a?u.next:u.prev),c=a?r:o;if(!n.collapsed){var l=ps(n);if(i(l))return qb(t,e,l,t===Ms.Backwards,!1)}var f=al(t,e.getBody(),n);if(c(f))return $b(e,f.getNode(!a));var d=wb(a,s(f)),m=lo(n.startContainer);if(!d)return m?U.some(n):U.none();if(c(d))return qb(t,e,d.getNode(!a),a,!1);var p=s(d);return p&&c(p)&&cl(d,p)?qb(t,e,p.getNode(!a),a,!1):m?Kw(e,d.toRange(),!1):U.none()},Yw=function(t,e,n,r,o,i){var a=al(e,t.getBody(),n),u=we(a.getClientRects()),s=e===bw.Down;if(!u)return U.none();var c,l=(s?Pw:Bw)(t.getBody(),Lw(1),a),f=j(l,Iw(1)),d=u.left,m=Vw(f,d);if(m&&i(m.node)){var p=Math.abs(d-m.left),g=Math.abs(d-m.right);return qb(e,t,m.node,p<g,!1)}if(c=r(a)?a.getNode():o(a)?a.getNode(!0):ps(n)){var h=function(e,t,n,r){var o,i,a,u,s=wl(t),c=[],l=0,f=function(e){return we(e.getClientRects())},d=1===e?(o=s.next,i=ds,a=fs,Us.after(r)):(o=s.prev,i=fs,a=ds,Us.before(r)),m=f(d);do{if(d.isVisible()&&!a(u=f(d),m)){if(0<c.length&&i(u,we(c))&&l++,(u=ss(u)).position=d,u.line=l,n(u))return c;c.push(u)}}while(d=o(d));return c}(e,t.getBody(),Lw(1),c),v=Vw(j(h,Iw(1)),d);if(v)return Kw(t,v.position.toRange(),!1);if(v=we(j(h,Iw(0))))return Kw(t,v.position.toRange(),!1)}return 0===f.length?Gw(t,s).filter(s?o:r).map(function(e){return Kb(t,e.toRange(),!1)}):U.none()},Gw=function(e,t){var n=e.selection.getRng(),r=e.getBody();if(t){var o=Us.fromRangeEnd(n),i=_w(r,o);return ee(i.positions)}o=Us.fromRangeStart(n),i=kw(r,o);return Z(i.positions)},Jw=function(t,e,n){return Gw(t,e).filter(n).exists(function(e){return t.selection.setRng(e.toRange()),!0})},Qw=Un,Zw=function(e,t,n){var r,o,i=wl(e.getBody()),a=E(sl,1===t?i.next:i.prev);if(n.collapsed&&""!==fc(e)){var u,s=e.dom.getParent(n.startContainer,"PRE");if(!s)return;a(Us.fromRangeStart(n))||(o=(r=e).dom.create(fc(r)),(!vt.ie||11<=vt.ie)&&(o.innerHTML='<br data-mce-bogus="1">'),u=o,1===t?e.$(s).after(u):e.$(s).before(u),e.selection.select(u,!0),e.selection.collapse())}},ex=function(e,t){var n=t?Ms.Forwards:Ms.Backwards,r=e.selection.getRng();return Xw(e,n,r,ep,tp,Qw).orThunk(function(){return Zw(e,n,r),U.none()})},tx=function(e,t){var n=t?1:-1,r=e.selection.getRng();return Yw(e,n,r,function(e){return ep(e)||Qm(e)},function(e){return tp(e)||Zm(e)},Qw).orThunk(function(){return Zw(e,n,r),U.none()})},nx=function(t,e){return ex(t,e).exists(function(e){return Ww(t,e),!0})},rx=function(t,e){return tx(t,e).exists(function(e){return Ww(t,e),!0})},ox=function(e,t){return Jw(e,t,t?tp:ep)},ix=function(e){return I(["figcaption"],Dt(e))},ax=function(e){var t=document.createRange();return t.setStartBefore(e.dom),t.setEndBefore(e.dom),t},ux=function(e,t,n){(n?un:an)(e,t)},sx=function(e,t,n,r){return""===t?(l=e,f=r,d=Nt.fromTag("br"),ux(l,d,f),ax(d)):(o=e,i=r,a=t,u=n,s=Nt.fromTag(a),c=Nt.fromTag("br"),$n(s,u),un(s,c),ux(o,s,i),ax(c));var o,i,a,u,s,c,l,f,d},cx=function(e,t,n){return t?(o=e.dom,_w(o,n).breakAt.isNone()):(r=e.dom,kw(r,n).breakAt.isNone());var r,o},lx=function(t,n){var e,r,o=Nt.fromDom(t.getBody()),i=Us.fromRangeStart(t.selection.getRng()),a=fc(t),u=dc(t);return e=i,r=E(Rt,o),Sr(Nt.fromDom(e.container()),Xr,r).filter(ix).exists(function(){if(cx(o,n,i)){var e=sx(o,a,u,n);return t.selection.setRng(e),!0}return!1})},fx=function(e,t){return!!e.selection.isCollapsed()&&lx(e,t)},dx=function(e,r){return Y(F(e,function(e){return xe({shiftKey:!1,altKey:!1,ctrlKey:!1,metaKey:!1,keyCode:0,action:V},e)}),function(e){return t=e,(n=r).keyCode===t.keyCode&&n.shiftKey===t.shiftKey&&n.altKey===t.altKey&&n.ctrlKey===t.ctrlKey&&n.metaKey===t.metaKey?[e]:[];var t,n})},mx=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];return function(){return e.apply(null,t)}},px=function(e,t){return K(dx(e,t),function(e){return e.action()})},gx=function(t,e){var n=e?Ms.Forwards:Ms.Backwards,r=t.selection.getRng();return Xw(t,n,r,Gm,Jm,jn).exists(function(e){return Ww(t,e),!0})},hx=function(t,e){var n=e?1:-1,r=t.selection.getRng();return Yw(t,n,r,Gm,Jm,jn).exists(function(e){return Ww(t,e),!0})},vx=function(e,t){return Jw(e,t,t?Jm:Gm)},yx=function(o,e){return Y(e,function(e){var t,n,r=(t=ss(e.getBoundingClientRect()),n=-1,{left:t.left-n,top:t.top-n,right:t.right+2*n,bottom:t.bottom+2*n,width:t.width+n,height:t.height+n});return[{x:r.left,y:o(r),cell:e},{x:r.right,y:o(r),cell:e}]})},bx=function(e,t,n,r,o){var i,a,u=qu(Nt.fromDom(n),"td,th,caption").map(function(e){return e.dom}),s=j(yx(e,u),function(e){return t(e,o)});return i=r,a=o,W(s,function(e,r){return e.fold(function(){return U.some(r)},function(e){var t=Math.sqrt(Math.abs(e.x-i)+Math.abs(e.y-a)),n=Math.sqrt(Math.abs(r.x-i)+Math.abs(r.y-a));return U.some(n<t?r:e)})},U.none()).map(function(e){return e.cell})},Cx=E(bx,function(e){return e.bottom},function(e,t){return e.y<t}),wx=E(bx,function(e){return e.top},function(e,t){return e.y>t}),xx=function(t,n){return Z(n.getClientRects()).bind(function(e){return Cx(t,e.left,e.top)}).bind(function(e){return Ew(Bl(t=e).map(function(e){return kw(t,e).positions.concat(e)}).getOr([]),n);var t})},Sx=function(t,n){return ee(n.getClientRects()).bind(function(e){return wx(t,e.left,e.top)}).bind(function(e){return Ew(Ol(t=e).map(function(e){return[e].concat(_w(t,e).positions)}).getOr([]),n);var t})},Nx=function(e,t,n){var r,o,i,a,u=e(t,n);return(a=u).breakType===nb.Wrap&&0===a.positions.length||!In(n.getNode())&&((i=u).breakType===nb.Br&&1===i.positions.length)?(r=e,o=t,!u.breakAt.exists(function(e){return r(o,e).breakAt.isSome()})):u.breakAt.isNone()},Ex=E(Nx,kw),kx=E(Nx,_w),_x=function(t,e,n,r){var o,i,a,u,s=t.selection.getRng(),c=e?1:-1;return!(!Uc()||(o=e,i=s,a=n,u=Us.fromRangeStart(i),!Tl(!o,a).exists(function(e){return e.isEqual(u)})))&&(qb(c,t,n,!e,!1).each(function(e){Ww(t,e)}),!0)},Rx=function(e,t){var n=t.getNode(e);return Nn(n)&&"TABLE"===n.nodeName?U.some(n):U.none()},Tx=function(u,s,c){var e=Rx(!!s,c),t=!1===s;e.fold(function(){return Ww(u,c.toRange())},function(a){return Tl(t,u.getBody()).filter(function(e){return e.isEqual(c)}).fold(function(){return Ww(u,c.toRange())},function(e){return n=s,o=a,t=c,void((i=fc(r=u))?r.undoManager.transact(function(){var e=Nt.fromTag(i);$n(e,dc(r)),un(e,Nt.fromTag("br")),(n?on:rn)(Nt.fromDom(o),e);var t=r.dom.createRng();t.setStart(e.dom,0),t.setEnd(e.dom,0),Ww(r,t)}):Ww(r,t.toRange()));var n,r,o,t,i})})},Ax=function(e,t,n,r){var o,i,a,u,s,c,l=e.selection.getRng(),f=Us.fromRangeStart(l),d=e.getBody();if(!t&&Ex(r,f)){var m=(u=d,xx(s=n,c=f).orThunk(function(){return Z(c.getClientRects()).bind(function(e){return Nw(Rw(u,Us.before(s)),e.left)})}).getOr(Us.before(s)));return Tx(e,t,m),!0}if(t&&kx(r,f)){m=(o=d,Sx(i=n,a=f).orThunk(function(){return Z(a.getClientRects()).bind(function(e){return Nw(Tw(o,Us.after(i)),e.left)})}).getOr(Us.after(i)));return Tx(e,t,m),!0}return!1},Dx=function(n,r,o){return U.from(n.dom.getParent(n.selection.getNode(),"td,th")).bind(function(t){return U.from(n.dom.getParent(t,"table")).map(function(e){return o(n,r,e,t)})}).getOr(!1)},Ox=function(e,t){return Dx(e,t,_x)},Bx=function(e,t){return Dx(e,t,Ax)},Px=function(i,a){i.on("keydown",function(e){var t,n,r,o;!1===e.isDefaultPrevented()&&(t=i,n=a,r=e,o=st().os,px([{keyCode:Gf.RIGHT,action:mx(nx,t,!0)},{keyCode:Gf.LEFT,action:mx(nx,t,!1)},{keyCode:Gf.UP,action:mx(rx,t,!1)},{keyCode:Gf.DOWN,action:mx(rx,t,!0)},{keyCode:Gf.RIGHT,action:mx(Ox,t,!0)},{keyCode:Gf.LEFT,action:mx(Ox,t,!1)},{keyCode:Gf.UP,action:mx(Bx,t,!1)},{keyCode:Gf.DOWN,action:mx(Bx,t,!0)},{keyCode:Gf.RIGHT,action:mx(gx,t,!0)},{keyCode:Gf.LEFT,action:mx(gx,t,!1)},{keyCode:Gf.UP,action:mx(hx,t,!1)},{keyCode:Gf.DOWN,action:mx(hx,t,!0)},{keyCode:Gf.RIGHT,action:mx(VC,t,n,!0)},{keyCode:Gf.LEFT,action:mx(VC,t,n,!1)},{keyCode:Gf.RIGHT,ctrlKey:!o.isOSX(),altKey:o.isOSX(),action:mx(WC,t,n)},{keyCode:Gf.LEFT,ctrlKey:!o.isOSX(),altKey:o.isOSX(),action:mx(KC,t,n)},{keyCode:Gf.UP,action:mx(fx,t,!1)},{keyCode:Gf.DOWN,action:mx(fx,t,!0)}],r).each(function(e){r.preventDefault()}))})},Lx=function(o,i){o.on("keydown",function(e){var t,n,r;!1===e.isDefaultPrevented()&&(t=o,n=i,r=e,px([{keyCode:Gf.BACKSPACE,action:mx(lw,t,!1)},{keyCode:Gf.BACKSPACE,action:mx(aC,t,!1)},{keyCode:Gf.DELETE,action:mx(aC,t,!0)},{keyCode:Gf.BACKSPACE,action:mx(Jb,t,!1)},{keyCode:Gf.DELETE,action:mx(Jb,t,!0)},{keyCode:Gf.BACKSPACE,action:mx(JC,t,n,!1)},{keyCode:Gf.DELETE,action:mx(JC,t,n,!0)},{keyCode:Gf.BACKSPACE,action:mx(Sg,t,!1)},{keyCode:Gf.DELETE,action:mx(Sg,t,!0)},{keyCode:Gf.BACKSPACE,action:mx(uC,t,!1)},{keyCode:Gf.DELETE,action:mx(uC,t,!0)},{keyCode:Gf.BACKSPACE,action:mx(rw,t,!1)},{keyCode:Gf.DELETE,action:mx(rw,t,!0)},{keyCode:Gf.BACKSPACE,action:mx(jb,t,!1)},{keyCode:Gf.DELETE,action:mx(jb,t,!0)},{keyCode:Gf.BACKSPACE,action:mx(Mb,t,!1)},{keyCode:Gf.DELETE,action:mx(Mb,t,!0)},{keyCode:Gf.BACKSPACE,action:mx(tw,t,!1)},{keyCode:Gf.DELETE,action:mx(tw,t,!0)}],r).each(function(e){r.preventDefault()}))}),o.on("keyup",function(e){var t,n;!1===e.isDefaultPrevented()&&(t=o,n=e,px([{keyCode:Gf.BACKSPACE,action:mx(iC,t)},{keyCode:Gf.DELETE,action:mx(iC,t)}],n))})},Ix=function(e,t){var n,r,o=t,i=e.dom,a=e.schema.getMoveCaretBeforeOnEnterElements();if(t){!/^(LI|DT|DD)$/.test(t.nodeName)||(r=function(e){for(;e;){if(1===e.nodeType||3===e.nodeType&&e.data&&/[\r\n\s]/.test(e.data))return e;e=e.nextSibling}}(t.firstChild))&&/^(UL|OL|DL)$/.test(r.nodeName)&&t.insertBefore(i.doc.createTextNode(oo),t.firstChild);var u=i.createRng();if(t.normalize(),t.hasChildNodes()){for(var s=new Hr(t,t);n=s.current();){if(On(n)){u.setStart(n,0),u.setEnd(n,0);break}if(a[n.nodeName.toLowerCase()]){u.setStartBefore(n),u.setEndBefore(n);break}o=n,n=s.next()}n||(u.setStart(o,0),u.setEnd(o,0))}else In(t)?t.nextSibling&&i.isBlock(t.nextSibling)?(u.setStartBefore(t),u.setEndBefore(t)):(u.setStartAfter(t),u.setEndAfter(t)):(u.setStart(t,0),u.setEnd(t,0));e.selection.setRng(u),Md(e,u)}},Mx=function(e){return U.from(e.dom.getParent(e.selection.getStart(!0),e.dom.isBlock))},Fx=function(e,t){return e&&e.parentNode&&e.parentNode.nodeName===t},Ux=function(e){return e&&/^(OL|UL|LI)$/.test(e.nodeName)},zx=function(e){var t=e.parentNode;return/^(LI|DT|DD)$/.test(t.nodeName)?t:e},jx=function(e,t,n){for(var r=e[n?"firstChild":"lastChild"];r&&!Nn(r);)r=r[n?"nextSibling":"previousSibling"];return r===t},Hx=function(e,t,n,r,o){var i,a,u,s,c,l,f=e.dom,d=e.selection.getRng();n!==e.getBody()&&(Ux(i=n)&&Ux(i.parentNode)&&(o="LI"),a=o?t(o):f.create("BR"),jx(n,r,!0)&&jx(n,r,!1)?Fx(n,"LI")?f.insertAfter(a,zx(n)):f.replace(a,n):jx(n,r,!0)?Fx(n,"LI")?(f.insertAfter(a,zx(n)),a.appendChild(f.doc.createTextNode(" ")),a.appendChild(n)):n.parentNode.insertBefore(a,n):jx(n,r,!1)?f.insertAfter(a,zx(n)):(n=zx(n),(u=d.cloneRange()).setStartAfter(r),u.setEndAfter(n),s=u.extractContents(),"LI"===o&&(l="LI",(c=s).firstChild&&c.firstChild.nodeName===l)?(a=s.firstChild,f.insertAfter(s,n)):(f.insertAfter(s,n),f.insertAfter(a,n))),f.remove(r),Ix(e,a))},Vx=function(e){e.innerHTML='<br data-mce-bogus="1">'},qx=function(e,t){return e.nodeName===t||e.previousSibling&&e.previousSibling.nodeName===t},$x=function(e,t){return t&&e.isBlock(t)&&!/^(TD|TH|CAPTION|FORM)$/.test(t.nodeName)&&!/^(fixed|absolute)/i.test(t.style.position)&&"true"!==e.getContentEditable(t)},Wx=function(e,t,n){return!1===On(t)?n:e?1===n&&t.data.charAt(n-1)===io?0:n:n===t.data.length-1&&t.data.charAt(n)===io?t.data.length:n},Kx=function(e,t){for(var n,r=e.getRoot(),o=t;o!==r&&"false"!==e.getContentEditable(o);)"true"===e.getContentEditable(o)&&(n=o),o=o.parentNode;return o!==r?n:r},Xx=function(e,t){var n=fc(e);n&&n.toLowerCase()===t.tagName.toLowerCase()&&function(e,o,t){var i=e.dom;U.from(t.style).map(i.parseStyle).each(function(e){var t=Qn(Nt.fromDom(o)),n=xe(xe({},t),e);i.setStyles(o,n)});var n=U.from(t["class"]).map(function(e){return e.split(/\s+/)}),r=U.from(o.className).map(function(e){return j(e.split(/\s+/),function(e){return""!==e})});as(n,r,function(t,e){var n=j(e,function(e){return!I(t,e)}),r=Se(t,n);i.setAttrib(o,"class",r.join(" "))});var a=["style","class"],u=le(t,function(e,t){return!I(a,t)});i.setAttribs(o,u)}(e,t,dc(e))},Yx=function(a,e){var t,u,i,s,n,r,o,c,l,f=a.dom,d=a.schema,m=d.getNonEmptyElements(),p=a.selection.getRng(),g=function(e){var t,n=u,r=d.getTextInlineElements(),o=e||"TABLE"===c||"HR"===c?f.create(e||N):s.cloneNode(!1),i=o;if(!1===a.getParam("keep_styles",!0))f.setAttrib(o,"style",null),f.setAttrib(o,"class",null);else do{if(r[n.nodeName]){if(Ll(n)||$l(n))continue;t=n.cloneNode(!1),f.setAttrib(t,"id",""),o.hasChildNodes()?t.appendChild(o.firstChild):i=t,o.appendChild(t)}}while((n=n.parentNode)&&n!==E);return Xx(a,o),Vx(i),o},h=function(e){var t,n,r=Wx(e,u,i);if(On(u)&&(e?0<r:r<u.nodeValue.length))return!1;if(u.parentNode===s&&l&&!e)return!0;if(e&&Nn(u)&&u===s.firstChild)return!0;if(qx(u,"TABLE")||qx(u,"HR"))return l&&!e||!l&&e;var o=new Hr(u,s);for(On(u)&&(e&&0===r?o.prev():e||r!==u.nodeValue.length||o.next());t=o.current();){if(Nn(t)){if(!t.getAttribute("data-mce-bogus")&&(n=t.nodeName.toLowerCase(),m[n]&&"br"!==n))return!1}else if(On(t)&&!Bo(t.nodeValue))return!1;e?o.prev():o.next()}return!0},v=function(){n=/^(H[1-6]|PRE|FIGURE)$/.test(c)&&"HGROUP"!==C?g(N):g(),a.getParam("end_container_on_empty_block",!1)&&$x(f,o)&&f.isEmpty(s)?n=f.split(o,s):f.insertAfter(n,s),Ix(a,n)};ud(f,p).each(function(e){p.setStart(e.startContainer,e.startOffset),p.setEnd(e.endContainer,e.endOffset)}),u=p.startContainer,i=p.startOffset,N=fc(a);var y=!(!e||!e.shiftKey),b=!(!e||!e.ctrlKey);Nn(u)&&u.hasChildNodes()&&(l=i>u.childNodes.length-1,u=u.childNodes[Math.min(i,u.childNodes.length-1)]||u,i=l&&On(u)?u.nodeValue.length:0);var C,w,x,S,N,E=Kx(f,u);E&&((N&&!y||!N&&y)&&(u=function(e,t,n,r,o){var i,a,u,s,c,l,f=t||"P",d=e.dom,m=Kx(d,r),p=d.getParent(r,d.isBlock);if(!p||!$x(d,p)){if(c=(p=p||m)===e.getBody()||(l=p)&&/^(TD|TH|CAPTION)$/.test(l.nodeName)?p.nodeName.toLowerCase():p.parentNode.nodeName.toLowerCase(),!p.hasChildNodes())return i=d.create(f),Xx(e,i),p.appendChild(i),n.setStart(i,0),n.setEnd(i,0),i;for(u=r;u.parentNode!==p;)u=u.parentNode;for(;u&&!d.isBlock(u);)u=(a=u).previousSibling;if(a&&e.schema.isValidChild(c,f.toLowerCase())){for(i=d.create(f),Xx(e,i),a.parentNode.insertBefore(i,a),u=a;u&&!d.isBlock(u);)s=u.nextSibling,i.appendChild(u),u=s;n.setStart(r,o),n.setEnd(r,o)}}return r}(a,N,p,u,i)),s=f.getParent(u,f.isBlock),o=s?f.getParent(s.parentNode,f.isBlock):null,c=s?s.nodeName.toUpperCase():"","LI"!==(C=o?o.nodeName.toUpperCase():"")||b||(o=(s=o).parentNode,c=C),/^(LI|DT|DD)$/.test(c)&&f.isEmpty(s)?Hx(a,g,o,s,N):N&&s===a.getBody()||(N=N||"P",lo(s)?(n=Co(s),f.isEmpty(s)&&Vx(s),Xx(a,n),Ix(a,n)):h()?v():h(!0)?(n=s.parentNode.insertBefore(g(),s),Ix(a,qx(s,"HR")?n:s)):((S=(x=p).cloneRange()).setStart(x.startContainer,Wx(!0,x.startContainer,x.startOffset)),S.setEnd(x.endContainer,Wx(!1,x.endContainer,x.endOffset)),(t=S.cloneRange()).setEndAfter(s),r=t.extractContents(),w=r,$(Vu(Nt.fromDom(w),Lt),function(e){var t=e.dom;t.nodeValue=uo(t.nodeValue)}),function(e){for(;On(e)&&(e.nodeValue=e.nodeValue.replace(/^[\r\n]+/,"")),e=e.firstChild;);}(r),n=r.firstChild,f.insertAfter(r,s),function(e,t,n){var r,o,i,a=n,u=[];if(a){for(;a=a.firstChild;){if(e.isBlock(a))return;Nn(a)&&!t[a.nodeName.toLowerCase()]&&u.push(a)}for(r=u.length;r--;)!(a=u[r]).hasChildNodes()||a.firstChild===a.lastChild&&""===a.firstChild.nodeValue?e.remove(a):(o=e,(i=a)&&"A"===i.nodeName&&o.isEmpty(i)&&e.remove(a))}}(f,m,n),function(e,t){t.normalize();var n=t.lastChild;n&&!/^(left|right)$/gi.test(e.getStyle(n,"float",!0))||e.add(t,"br")}(f,s),f.isEmpty(s)&&Vx(s),n.normalize(),f.isEmpty(n)?(f.remove(n),v()):(Xx(a,n),Ix(a,n))),f.setAttrib(n,"id",""),a.fire("NewBlock",{newBlock:n})))},Gx=function(e,t,n){var r=e.create("span",{},"&nbsp;");n.parentNode.insertBefore(r,n),t.scrollIntoView(r),e.remove(r)},Jx=function(e,t,n,r){var o=e.createRng();r?(o.setStartBefore(n),o.setEndBefore(n)):(o.setStartAfter(n),o.setEndAfter(n)),t.setRng(o)},Qx=function(e,t){var n,r,o=e.selection,i=e.dom,a=o.getRng();ud(i,a).each(function(e){a.setStart(e.startContainer,e.startOffset),a.setEnd(e.endContainer,e.endOffset)});var u,s=a.startOffset,c=a.startContainer;1===c.nodeType&&c.hasChildNodes()&&(u=s>c.childNodes.length-1,c=c.childNodes[Math.min(s,c.childNodes.length-1)]||c,s=u&&3===c.nodeType?c.nodeValue.length:0);var l=i.getParent(c,i.isBlock),f=l?i.getParent(l.parentNode,i.isBlock):null,d=f?f.nodeName.toUpperCase():"",m=!(!t||!t.ctrlKey);"LI"!==d||m||(l=f),c&&3===c.nodeType&&s>=c.nodeValue.length&&!function(e,t,n){for(var r,o=new Hr(t,n),i=e.getNonEmptyElements();r=o.next();)if(i[r.nodeName.toLowerCase()]||0<r.length)return!0}(e.schema,c,l)&&(n=i.create("br"),a.insertNode(n),a.setStartAfter(n),a.setEndAfter(n),r=!0),n=i.create("br"),js(i,a,n),Gx(i,o,n),Jx(i,o,n,r),e.undoManager.add()},Zx=function(e,t){var n=Nt.fromTag("br");rn(Nt.fromDom(t),n),e.undoManager.add()},eS=function(e,t){tS(e.getBody(),t)||on(Nt.fromDom(t),Nt.fromTag("br"));var n=Nt.fromTag("br");on(Nt.fromDom(t),n),Gx(e.dom,e.selection,n.dom),Jx(e.dom,e.selection,n.dom,!1),e.undoManager.add()},tS=function(e,t){return n=Us.after(t),!!In(n.getNode())||Al(e,Us.after(t)).map(function(e){return In(e.getNode())}).getOr(!1);var n},nS=function(e){return e&&"A"===e.nodeName&&"href"in e},rS=function(e){return e.fold(p,nS,nS,p)},oS=function(e,t){t.fold(V,E(Zx,e),E(eS,e),V)},iS=function(e,t){var n,r,o,i=(r=E(yb,n=e),o=Us.fromRangeStart(n.selection.getRng()),RC(r,n.getBody(),o).filter(rS));i.isSome()?i.each(E(oS,e)):Qx(e,t)},aS=function(e,t){return Mx(e).filter(function(e){return 0<t.length&&kt(Nt.fromDom(e),t)}).isSome()},uS=gr([{br:[]},{block:[]},{none:[]}]),sS=function(e,t){return aS(n=e,n.getParam("no_newline_selector",""));var n},cS=function(n){return function(e,t){return""===fc(e)===n}},lS=function(n){return function(e,t){return Mx(e).filter(function(e){return Zr(Nt.fromDom(e))}).isSome()===n}},fS=function(n,r){return function(e,t){return Mx(e).fold(N(""),function(e){return e.nodeName.toUpperCase()})===n.toUpperCase()===r}},dS=function(e){return fS("pre",e)},mS=function(n){return function(e,t){return e.getParam("br_in_pre",!0)===n}},pS=function(e,t){return aS(n=e,n.getParam("br_newline_selector",".mce-toc h2,figcaption,caption"));var n},gS=function(e,t){return t},hS=function(e){var t=fc(e),n=function(e,t){for(var n,r=e.getRoot(),o=t;o!==r&&"false"!==e.getContentEditable(o);)"true"===e.getContentEditable(o)&&(n=o),o=o.parentNode;return o!==r?n:r}(e.dom,e.selection.getStart());return n&&e.schema.isValidChild(n.nodeName,t||"P")},vS=function(e,t){return function(n,r){return W(e,function(e,t){return e&&t(n,r)},!0)?U.some(t):U.none()}},yS=function(e,t){return yC([vS([sS],uS.none()),vS([fS("summary",!0)],uS.br()),vS([dS(!0),mS(!1),gS],uS.br()),vS([dS(!0),mS(!1)],uS.block()),vS([dS(!0),mS(!0),gS],uS.block()),vS([dS(!0),mS(!0)],uS.br()),vS([lS(!0),gS],uS.br()),vS([lS(!0)],uS.block()),vS([cS(!0),gS,hS],uS.block()),vS([cS(!0)],uS.br()),vS([pS],uS.br()),vS([cS(!1),gS],uS.br()),vS([hS],uS.block())],[e,!(!t||!t.shiftKey)]).getOr(uS.none())},bS=function(e,t){yS(e,t).fold(function(){iS(e,t)},function(){Yx(e,t)},V)},CS=function(o){o.on("keydown",function(e){var t,n,r;e.keyCode===Gf.ENTER&&(t=o,(n=e).isDefaultPrevented()||(n.preventDefault(),(r=t.undoManager).typing&&(r.typing=!1,r.add()),t.undoManager.transact(function(){!1===t.selection.isCollapsed()&&t.execCommand("Delete"),bS(t,n)})))})},wS=function(r){r.on("keydown",function(e){var t,n;!1===e.isDefaultPrevented()&&(t=r,n=e,px([{keyCode:Gf.END,action:mx(ox,t,!0)},{keyCode:Gf.HOME,action:mx(ox,t,!1)},{keyCode:Gf.END,action:mx(vx,t,!0)},{keyCode:Gf.HOME,action:mx(vx,t,!1)}],n).each(function(e){n.preventDefault()}))})},xS=st().browser,SS=function(t){var e,n;e=t,n=Pu(function(){e.composing||Lp(e)},0),xS.isIE()&&(e.on("keypress",function(e){n.throttle()}),e.on("remove",function(e){n.cancel()})),t.on("input",function(e){!1===e.isComposing&&Lp(t)})},NS=function(n,r){var e=r.container(),t=r.offset();return On(e)?(e.insertData(t,n),U.some(Is(e,t+n.length))):ul(r).map(function(e){var t=Nt.fromText(n);return(r.isAtEnd()?on:rn)(e,t),Is(t.dom,n.length)})},ES=E(NS,oo),kS=E(NS," "),_S=function(r,o){return function(e){return t=r,(!kp(n=e)&&(_p(t,n)||Np(t,n)||Ep(t,n))?ES:kS)(o);var t,n}},RS=function(e){var t,n,r=Us.fromRangeStart(e.selection.getRng()),o=Nt.fromDom(e.getBody());if(e.selection.isCollapsed()){var i=E(yb,e),a=Us.fromRangeStart(e.selection.getRng());return RC(i,e.getBody(),a).bind((n=o,function(e){return e.fold(function(e){return Dl(n.dom,Us.before(e))},function(e){return Ol(e)},function(e){return Bl(e)},function(e){return Al(n.dom,Us.after(e))})})).bind(_S(o,r)).exists((t=e,function(e){return t.selection.setRng(e.toRange()),t.nodeChanged(),!0}))}return!1},TS=function(r){r.on("keydown",function(e){var t,n;!1===e.isDefaultPrevented()&&(t=r,n=e,px([{keyCode:Gf.SPACEBAR,action:mx(RS,t)}],n).each(function(e){n.preventDefault()}))})},AS=function(e){var t,n=$C(e);return(t=e).on("keyup compositionstart",E(yw,t)),Px(e,n),Lx(e,n),CS(e),TS(e),SS(e),wS(e),n},DS=(OS.prototype.nodeChanged=function(e){var t,n,r,o=this.editor.selection;this.editor.initialized&&o&&!this.editor.getParam("disable_nodechange")&&!this.editor.mode.isReadOnly()&&(r=this.editor.getBody(),(t=o.getStart(!0)||r).ownerDocument===this.editor.getDoc()&&this.editor.dom.isChildOf(t,r)||(t=r),n=[],this.editor.dom.getParent(t,function(e){return e===r||void n.push(e)}),(e=e||{}).element=t,e.parents=n,this.editor.fire("NodeChange",e))},OS.prototype.isSameElementPath=function(e){var t,n=this.editor.$(e).parentsUntil(this.editor.getBody()).add(e);if(n.length===this.lastPath.length){for(t=n.length;0<=t&&n[t]===this.lastPath[t];t--);if(-1===t)return this.lastPath=n,!0}return this.lastPath=n,!1},OS);function OS(r){var o;this.lastPath=[],this.editor=r;var t=this;"onselectionchange"in r.getDoc()||r.on("NodeChange click mouseup keyup focus",function(e){var t=r.selection.getRng(),n={startContainer:t.startContainer,startOffset:t.startOffset,endContainer:t.endContainer,endOffset:t.endOffset};"nodechange"!==e.type&&td(n,o)||r.fire("SelectionChange"),o=n}),r.on("contextmenu",function(){r.fire("SelectionChange")}),r.on("SelectionChange",function(){var e=r.selection.getStart(!0);!e||!vt.range&&r.selection.isCollapsed()||Of(r)&&!t.isSameElementPath(e)&&r.dom.isChildOf(e,r.getBody())&&r.nodeChanged({selectionChange:!0})}),r.on("mouseup",function(e){!e.isDefaultPrevented()&&Of(r)&&("IMG"===r.selection.getNode().nodeName?Fr.setEditorTimeout(r,function(){r.nodeChanged()}):r.nodeChanged())})}var BS=function(e){var t,n;(t=e).on("click",function(e){t.dom.getParent(e.target,"details")&&e.preventDefault()}),(n=e).parser.addNodeFilter("details",function(e){$(e,function(e){e.attr("data-mce-open",e.attr("open")),e.attr("open","open")})}),n.serializer.addNodeFilter("details",function(e){$(e,function(e){var t=e.attr("data-mce-open");e.attr("open",q(t)?t:null),e.attr("data-mce-open",null)})})},PS=function(e){return Nn(e)&&Jr(Nt.fromDom(e))},LS=function(a){a.on("click",function(e){var t,n,r,o,i;3<=e.detail&&(r=(t=a).selection.getRng(),o=Is.fromRangeStart(r),i=Is.fromRangeEnd(r),Is.isElementPosition(o)&&(n=o.container(),PS(n)&&Ol(n).each(function(e){return r.setStart(e.container(),e.offset())})),Is.isElementPosition(i)&&(n=o.container(),PS(n)&&Bl(n).each(function(e){return r.setEnd(e.container(),e.offset())})),t.selection.setRng(Eg(r)))})},IS=function(e){var t=e.getBoundingClientRect(),n=e.ownerDocument,r=n.documentElement,o=n.defaultView;return{top:t.top+o.pageYOffset-r.clientTop,left:t.left+o.pageXOffset-r.clientLeft}},MS=function(e,t){return n=(u=e).inline?IS(u.getBody()):{left:0,top:0},a=(i=e).getBody(),r=i.inline?{left:a.scrollLeft,top:a.scrollTop}:{left:0,top:0},{pageX:(o=function(e,t){if(t.target.ownerDocument===e.getDoc())return{left:t.pageX,top:t.pageY};var n,r,o,i,a,u=IS(e.getContentAreaContainer()),s=(r=(n=e).getBody(),o=n.getDoc().documentElement,i={left:r.scrollLeft,top:r.scrollTop},a={left:r.scrollLeft||o.scrollLeft,top:r.scrollTop||o.scrollTop},n.inline?i:a);return{left:t.pageX-u.left+s.left,top:t.pageY-u.top+s.top}}(e,t)).left-n.left+r.left,pageY:o.top-n.top+r.top};var n,r,o,i,a,u},FS=Un,US=Fn,zS=function(e){e&&e.parentNode&&e.parentNode.removeChild(e)},jS=function(u,s){return function(e){var t,n,r,o,i,a;0===e.button&&(t=K(s.dom.getParents(e.target),function(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];return function(e){for(var t=0;t<n.length;t++)if(n[t](e))return!0;return!1}}(FS,US)).getOr(null),i=s.getBody(),FS(a=t)&&a!==i&&(n=s.dom.getPos(t),r=s.getBody(),o=s.getDoc().documentElement,u.set({element:t,dragging:!1,screenX:e.screenX,screenY:e.screenY,maxX:(s.inline?r.scrollWidth:o.offsetWidth)-2,maxY:(s.inline?r.scrollHeight:o.offsetHeight)-2,relX:e.pageX-n.x,relY:e.pageY-n.y,width:t.offsetWidth,height:t.offsetHeight,ghost:function(e,t,n,r){var o=e.dom,i=t.cloneNode(!0);o.setStyles(i,{width:n,height:r}),o.setAttrib(i,"data-mce-selected",null);var a=o.create("div",{"class":"mce-drag-container","data-mce-bogus":"all",unselectable:"on",contenteditable:"false"});return o.setStyles(a,{position:"absolute",opacity:.5,overflow:"hidden",border:0,padding:0,margin:0,width:n,height:r}),o.setStyles(i,{margin:0,boxSizing:"border-box"}),a.appendChild(i),a}(s,t,t.offsetWidth,t.offsetHeight)})))}},HS=function(e,h){var v=Fr.throttle(function(e,t){h._selectionOverrides.hideFakeCaret(),h.selection.placeCaretAt(e,t)},0);return function(g){return e.on(function(e){var t,n,r,o,i,a,u,s,c,l,f,d,m,p=Math.max(Math.abs(g.screenX-e.screenX),Math.abs(g.screenY-e.screenY));if(!e.dragging&&10<p){if(h.fire("dragstart",{target:e.element}).isDefaultPrevented())return;e.dragging=!0,h.focus()}e.dragging&&(d=e,t={pageX:(m=MS(h,g)).pageX-d.relX,pageY:m.pageY+5},l=e.ghost,f=h.getBody(),l.parentNode!==f&&f.appendChild(l),n=e.ghost,r=t,o=e.width,i=e.height,a=e.maxX,u=e.maxY,c=s=0,n.style.left=r.pageX+"px",n.style.top=r.pageY+"px",r.pageX+o>a&&(s=r.pageX+o-a),r.pageY+i>u&&(c=r.pageY+i-u),n.style.width=o-s+"px",n.style.height=i-c+"px",v(g.clientX,g.clientY))})}},VS=function(e,l){return function(c){e.on(function(e){var t,n,r,o,i,a,u,s;e.dragging&&(u=(o=l).selection,s=u.getSel().getRangeAt(0).startContainer,i=3===s.nodeType?s.parentNode:s,a=e.element,i===a||o.dom.isChildOf(i,a)||FS(i)||(n=e.element,(r=n.cloneNode(!0)).removeAttribute("data-mce-selected"),t=r,l.fire("drop",{clientX:c.clientX,clientY:c.clientY}).isDefaultPrevented()||l.undoManager.transact(function(){zS(e.element),l.insertContent(l.dom.getOuterHTML(t)),l._selectionOverrides.hideFakeCaret()})))}),qS(e)}},qS=function(e){e.on(function(e){zS(e.ghost)}),e.clear()},$S=function(e){var t,n,r,o=(t=ku(U.none()),{clear:function(){return t.set(U.none())},set:function(e){return t.set(U.some(e))},isSet:function(){return t.get().isSome()},on:function(e){return t.get().each(e)}}),i=bu.DOM,a=document,u=jS(o,e),s=HS(o,e),c=VS(o,e),l=(n=o,function(){n.on(function(e){e.dragging&&r.fire("dragend")}),qS(n)});(r=e).on("mousedown",u),e.on("mousemove",s),e.on("mouseup",c),i.bind(a,"mousemove",s),i.bind(a,"mouseup",l),e.on("remove",function(){i.unbind(a,"mousemove",s),i.unbind(a,"mouseup",l)})},WS=function(e){var n,i,a,u,t;$S(e),(n=e).on("drop",function(e){var t="undefined"!=typeof e.clientX?n.getDoc().elementFromPoint(e.clientX,e.clientY):null;!FS(t)&&"false"!==n.dom.getContentEditableParent(t)||e.preventDefault()}),e.getParam("block_unsupported_drop",!0,"boolean")&&(a=function(e){var t;e.defaultPrevented||(t=e.dataTransfer)&&(I(t.types,"Files")||0<t.files.length)&&(e.preventDefault(),"drop"===e.type&&Hy(i,"Dropped file type is not supported"))},u=function(e){am(i,e.target)&&a(e)},t=function(){var t=bu.DOM,n=i.dom,r=document,o=i.inline?i.getBody():i.getDoc(),e=["drop","dragover"];$(e,function(e){t.bind(r,e,u),n.bind(o,e,a)}),i.on("remove",function(){$(e,function(e){t.unbind(r,e,u),n.unbind(o,e,a)})})},(i=e).on("init",function(){Fr.setEditorTimeout(i,t,0)}))},KS=Fn,XS=Un,YS=function(e,t){return Xf(e.getBody(),t)},GS=function(u){var s,c=u.selection,l=u.dom,f=l.isBlock,d=u.getBody(),m=Fc(u,d,f,function(){return pm(u)}),p="sel-"+l.uniqueId(),i="data-mce-selected",g=function(e){return XS(e)||jn(e)},h=function(e){e&&c.setRng(e)},r=c.getRng,v=function(e,t,n,r){return void 0===r&&(r=!0),u.fire("ShowCaret",{target:t,direction:e,before:n}).isDefaultPrevented()?null:(r&&c.scrollIntoView(t,-1===e),m.show(n,t))},t=function(e){return mo(e)||yo(e)||bo(e)},y=function(e){return t(e.startContainer)||t(e.endContainer)},b=function(e){var t=u.schema.getShortEndedElements(),n=l.createRng(),r=e.startContainer,o=e.startOffset,i=e.endContainer,a=e.endOffset;return me(t,r.nodeName.toLowerCase())?0===o?n.setStartBefore(r):n.setStartAfter(r):n.setStart(r,o),me(t,i.nodeName.toLowerCase())?0===a?n.setEndBefore(i):n.setEndAfter(i):n.setEnd(i,a),n},C=function(e){var t=e.cloneNode(!0),n=u.fire("ObjectSelected",{target:e,targetClone:t});if(n.isDefaultPrevented())return null;var r=function(e,t,n){var r=u.$,o=Er(Nt.fromDom(u.getBody()),"#"+p).fold(function(){return r([])},function(e){return r([e.dom])});0===o.length&&(o=r('<div data-mce-bogus="all" class="mce-offscreen-selection"></div>').attr("id",p)).appendTo(u.getBody());var i=l.createRng();t===n&&vt.ie?(o.empty().append('<p style="font-size: 0" data-mce-bogus="all">\xa0</p>').append(t),i.setStartAfter(o[0].firstChild.firstChild),i.setEndAfter(t)):(o.empty().append(oo).append(t).append(oo),i.setStart(o[0].firstChild,1),i.setEnd(o[0].lastChild,0)),o.css({top:l.getPos(e,u.getBody()).y}),o[0].focus();var a=c.getSel();return a.removeAllRanges(),a.addRange(i),i}(e,n.targetClone,t),o=Nt.fromDom(e);return $(qu(Nt.fromDom(u.getBody()),"*[data-mce-selected]"),function(e){Rt(o,e)||Kn(e,i)}),l.getAttrib(e,i)||e.setAttribute(i,"1"),s=e,S(),r},w=function(e,t){if(!e)return null;if(e.collapsed){if(!y(e)){var n=t?1:-1,r=al(n,d,e),o=r.getNode(!t);if(jc(o))return v(n,o,!!t&&!r.isAtEnd(),!1);var i=r.getNode(t);if(jc(i))return v(n,i,!t&&!r.isAtEnd(),!1)}return null}var a=e.startContainer,u=e.startOffset,s=e.endOffset;if(3===a.nodeType&&0===u&&XS(a.parentNode)&&(a=a.parentNode,u=l.nodeIndex(a),a=a.parentNode),1!==a.nodeType)return null;if(s===u+1&&a===e.endContainer){var c=a.childNodes[u];if(g(c))return C(c)}return null},x=function(){s&&s.removeAttribute(i),Er(Nt.fromDom(u.getBody()),"#"+p).each(ln),s=null},S=function(){m.hide()};return vt.ceFalse&&function(){u.on("mouseup",function(e){var t=r();t.collapsed&&Ly(u,e.clientX,e.clientY)&&Wb(u,t,!1).each(h)}),u.on("click",function(e){var t=YS(u,e.target);t&&(XS(t)&&(e.preventDefault(),u.focus()),KS(t)&&l.isChildOf(t,c.getNode())&&x())}),u.on("blur NewBlock",x),u.on("ResizeWindow FullscreenStateChanged",m.reposition);var a=function(e){var t=wl(e);if(!e.firstChild)return!1;var n,r=Us.before(e.firstChild),o=t.next(r);return o&&!(ep(n=o)||tp(n)||Gm(n)||Jm(n))},i=function(e,t){var n,r,o=l.getParent(e,f),i=l.getParent(t,f);return!(!o||e===i||!l.isChildOf(o,i)||!1!==XS(YS(u,o)))||o&&(n=o,r=i,!(l.getParent(n,f)===l.getParent(r,f)))&&a(o)};u.on("tap",function(e){var t=e.target,n=YS(u,t);XS(n)?(e.preventDefault(),$b(u,n).each(w)):g(t)&&$b(u,t).each(w)},!0),u.on("mousedown",function(e){var t,n,r,o=e.target;o!==d&&"HTML"!==o.nodeName&&!l.isChildOf(o,d)||!1===Ly(u,e.clientX,e.clientY)||((t=YS(u,o))?XS(t)?(e.preventDefault(),$b(u,t).each(w)):(x(),KS(t)&&e.shiftKey||Yf(e.clientX,e.clientY,c.getRng())||(S(),c.placeCaretAt(e.clientX,e.clientY))):g(o)?$b(u,o).each(w):!1===jc(o)&&(x(),S(),(n=$w(d,e.clientX,e.clientY))&&(i(o,n.node)||(e.preventDefault(),r=v(1,n.node,n.before,!1),u.getBody().focus(),h(r)))))}),u.on("keypress",function(e){Gf.modifierPressed(e)||XS(c.getNode())&&e.preventDefault()}),u.on("GetSelectionRange",function(e){var t=e.range;if(s){if(!s.parentNode)return void(s=null);(t=t.cloneRange()).selectNode(s),e.range=t}}),u.on("SetSelectionRange",function(e){e.range=b(e.range);var t=w(e.range,e.forward);t&&(e.range=t)});var n,e,o;u.on("AfterSetSelectionRange",function(e){var t,n=e.range,r=n.startContainer.parentNode;y(n)||"mcepastebin"===r.id||S(),t=r,l.hasClass(t,"mce-offscreen-selection")||x()}),u.on("copy",function(e){var t,n,r=e.clipboardData;e.isDefaultPrevented()||!e.clipboardData||vt.ie||(t=(n=l.get(p))?n.getElementsByTagName("*")[0]:n)&&(e.preventDefault(),r.clearData(),r.setData("text/html",t.outerHTML),r.setData("text/plain",t.outerText||t.innerText))}),WS(u),e=Pu(function(){var e,t;n.removed||!n.getBody().contains(document.activeElement)||(e=n.selection.getRng()).collapsed&&(t=Kb(n,e,!1),n.selection.setRng(t))},0),(n=u).on("focus",function(){e.throttle()}),n.on("blur",function(){e.cancel()}),(o=u).on("init",function(){o.on("focusin",function(e){var t,n,r=e.target;jn(r)&&(t=Xf(o.getBody(),r),n=Un(t)?t:r,o.selection.getNode()!==n&&$b(o,n).each(function(e){return o.selection.setRng(e)}))})})}(),{showCaret:v,showBlockCaretContainer:function(e){e.hasAttribute("data-mce-caret")&&(Co(e),h(r()),c.scrollIntoView(e))},hideFakeCaret:S,destroy:function(){m.destroy(),s=null}}},JS=function(u){var s,n,r,o=xt.each,c=Gf.BACKSPACE,l=Gf.DELETE,f=u.dom,d=u.selection,e=u.parser,t=vt.gecko,i=vt.ie,a=vt.webkit,m="data:text/mce-internal,",p=i?"Text":"URL",g=function(e,t){try{u.getDoc().execCommand(e,!1,t)}catch(n){}},h=function(e){return e.isDefaultPrevented()},v=function(){u.shortcuts.add("meta+a",null,"SelectAll")},y=function(){u.on("keydown",function(e){if(!h(e)&&e.keyCode===c&&d.isCollapsed()&&0===d.getRng().startOffset){var t=d.getNode().previousSibling;if(t&&t.nodeName&&"table"===t.nodeName.toLowerCase())return e.preventDefault(),!1}})},b=function(){u.inline||(u.contentStyles.push("body {min-height: 150px}"),u.on("click",function(e){var t;if("HTML"===e.target.nodeName){if(11<vt.ie)return void u.getBody().focus();t=u.selection.getRng(),u.getBody().focus(),u.selection.setRng(t),u.selection.normalize(),u.nodeChanged()}}))};return u.on("keydown",function(e){var t;if(!h(e)&&e.keyCode===Gf.BACKSPACE){var n=(t=d.getRng()).startContainer,r=t.startOffset,o=f.getRoot(),i=n;if(t.collapsed&&0===r){for(;i&&i.parentNode&&i.parentNode.firstChild===i&&i.parentNode!==o;)i=i.parentNode;"BLOCKQUOTE"===i.tagName&&(u.formatter.toggle("blockquote",null,i),(t=f.createRng()).setStart(n,0),t.setEnd(n,0),d.setRng(t))}}}),s=function(e){var t=f.create("body"),n=e.cloneContents();return t.appendChild(n),d.serializer.serialize(t,{format:"html"})},u.on("keydown",function(e){var t,n,r,o,i,a=e.keyCode;if(!h(e)&&(a===l||a===c)){if(t=u.selection.isCollapsed(),n=u.getBody(),t&&!f.isEmpty(n))return;if(!t&&(r=u.selection.getRng(),o=s(r),(i=f.createRng()).selectNode(u.getBody()),o!==s(i)))return;e.preventDefault(),u.setContent(""),n.firstChild&&f.isBlock(n.firstChild)?u.selection.setCursorLocation(n.firstChild,0):u.selection.setCursorLocation(n,0),u.nodeChanged()}}),vt.windowsPhone||u.on("keyup focusin mouseup",function(e){Gf.modifierPressed(e)||d.normalize()},!0),a&&(u.inline||f.bind(u.getDoc(),"mousedown mouseup",function(e){var t;if(e.target===u.getDoc().documentElement)if(t=d.getRng(),u.getBody().focus(),"mousedown"===e.type){if(mo(t.startContainer))return;d.placeCaretAt(e.clientX,e.clientY)}else d.setRng(t)}),u.on("click",function(e){var t=e.target;/^(IMG|HR)$/.test(t.nodeName)&&"false"!==f.getContentEditableParent(t)&&(e.preventDefault(),u.selection.select(t),u.nodeChanged()),"A"===t.nodeName&&f.hasClass(t,"mce-item-anchor")&&(e.preventDefault(),d.select(t))}),fc(u)&&u.on("init",function(){g("DefaultParagraphSeparator",fc(u))}),u.on("init",function(){u.dom.bind(u.getBody(),"submit",function(e){e.preventDefault()})}),y(),e.addNodeFilter("br",function(e){for(var t=e.length;t--;)"Apple-interchange-newline"===e[t].attr("class")&&e[t].remove()}),vt.iOS?(u.inline||u.on("keydown",function(){document.activeElement===document.body&&u.getWin().focus()}),b(),u.on("click",function(e){var t=e.target;do{if("A"===t.tagName)return void e.preventDefault()}while(t=t.parentNode)}),u.contentStyles.push(".mce-content-body {-webkit-touch-callout: none}")):v()),11<=vt.ie&&(b(),y()),vt.ie&&(v(),g("AutoUrlDetect",!1),u.on("dragstart",function(e){var t,n,r;(t=e).dataTransfer&&(u.selection.isCollapsed()&&"IMG"===t.target.tagName&&d.select(t.target),0<(n=u.selection.getContent()).length&&(r=m+escape(u.id)+","+escape(n),t.dataTransfer.setData(p,r)))}),u.on("drop",function(e){var t,n,r,o,i,a;h(e)||(t=(i=e).dataTransfer&&(a=i.dataTransfer.getData(p))&&0<=a.indexOf(m)?(a=a.substr(m.length).split(","),{id:unescape(a[0]),html:unescape(a[1])}):null)&&t.id!==u.id&&(e.preventDefault(),n=ed(e.x,e.y,u.getDoc()),d.setRng(n),r=t.html,o=!0,u.queryCommandSupported("mceInsertClipboardContent")?u.execCommand("mceInsertClipboardContent",!1,{content:r,internal:o}):u.execCommand("mceInsertContent",!1,r))})),t&&(u.on("keydown",function(e){if(!h(e)&&e.keyCode===c){if(!u.getBody().getElementsByTagName("hr").length)return;if(d.isCollapsed()&&0===d.getRng().startOffset){var t=d.getNode(),n=t.previousSibling;if("HR"===t.nodeName)return f.remove(t),void e.preventDefault();n&&n.nodeName&&"hr"===n.nodeName.toLowerCase()&&(f.remove(n),e.preventDefault())}}}),Range.prototype.getClientRects||u.on("mousedown",function(e){var t;h(e)||"HTML"!==e.target.nodeName||((t=u.getBody()).blur(),Fr.setEditorTimeout(u,function(){t.focus()}))}),n=function(){var e=f.getAttribs(d.getStart().cloneNode(!1));return function(){var t=d.getStart();t!==u.getBody()&&(f.setAttrib(t,"style",null),o(e,function(e){t.setAttributeNode(e.cloneNode(!0))}))}},r=function(){return!d.isCollapsed()&&f.getParent(d.getStart(),f.isBlock)!==f.getParent(d.getEnd(),f.isBlock)},u.on("keypress",function(e){var t;if(!h(e)&&(8===e.keyCode||46===e.keyCode)&&r())return t=n(),u.getDoc().execCommand("delete",!1,null),t(),e.preventDefault(),!1}),f.bind(u.getDoc(),"cut",function(e){var t;!h(e)&&r()&&(t=n(),Fr.setEditorTimeout(u,function(){t()}))}),u.getParam("readonly")||u.on("BeforeExecCommand mousedown",function(){g("StyleWithCSS",!1),g("enableInlineTableEditing",!1),yc(u)||g("enableObjectResizing",!1)}),u.on("SetContent ExecCommand",function(e){"setcontent"!==e.type&&"mceInsertLink"!==e.command||o(f.select("a"),function(e){var t=e.parentNode,n=f.getRoot();if(t.lastChild===e){for(;t&&!f.isBlock(t);){if(t.parentNode.lastChild!==t||t===n)return;t=t.parentNode}f.add(t,"br",{"data-mce-bogus":1})}})}),u.contentStyles.push("img:-moz-broken {-moz-force-broken-image-icon:1;min-width:24px;min-height:24px}"),vt.mac&&u.on("keydown",function(e){!Gf.metaKeyPressed(e)||e.shiftKey||37!==e.keyCode&&39!==e.keyCode||(e.preventDefault(),u.selection.getSel().modify("move",37===e.keyCode?"backward":"forward","lineboundary"))}),y()),{refreshContentEditable:function(){},isHidden:function(){if(!t||u.removed)return!1;var e=u.selection.getSel();return!e||!e.rangeCount||0===e.rangeCount}}},QS=bu.DOM,ZS=function(e){return le(e,function(e){return!1===R(e)})},eN=function(e){var t,n=e.settings,r=e.editorUpload.blobCache;return ZS({allow_conditional_comments:n.allow_conditional_comments,allow_html_data_urls:n.allow_html_data_urls,allow_html_in_named_anchor:n.allow_html_in_named_anchor,allow_script_urls:n.allow_script_urls,allow_unsafe_link_target:n.allow_unsafe_link_target,convert_fonts_to_spans:n.convert_fonts_to_spans,fix_list_elements:n.fix_list_elements,font_size_legacy_values:n.font_size_legacy_values,forced_root_block:n.forced_root_block,forced_root_block_attrs:n.forced_root_block_attrs,padd_empty_with_br:n.padd_empty_with_br,preserve_cdata:n.preserve_cdata,remove_trailing_brs:n.remove_trailing_brs,inline_styles:n.inline_styles,root_name:(t=e).inline?t.getElement().nodeName.toLowerCase():undefined,validate:!0,blob_cache:r,images_dataimg_filter:n.images_dataimg_filter})},tN=function(u){var e=u.dom.getRoot();u.inline||Of(u)&&u.selection.getStart(!0)!==e||Ol(e).each(function(e){var t,n,r,o,i=e.getNode(),a=Tn(i)?Ol(i).getOr(e):e;vt.browser.isIE()?(t=u,n=a.toRange(),r=Nt.fromDom(t.getBody()),o=(Gd(t)?U.from(n):U.none()).map(Jd).filter(Yd(r)),t.bookmark=o.isSome()?o:t.bookmark):u.selection.setRng(a.toRange())})},nN=function(e){var t;e.bindPendingEventDelegates(),e.initialized=!0,e.fire("Init"),e.focus(!0),tN(e),e.nodeChanged({initial:!0}),e.execCallback("init_instance_callback",e),(t=e).settings.auto_focus&&Fr.setEditorTimeout(t,function(){var e=!0===t.settings.auto_focus?t:t.editorManager.get(t.settings.auto_focus);e.destroyed||e.focus()},100)},rN=function(t,e){var n=t.settings,r=t.getDoc(),o=t.getBody();n.browser_spellcheck||n.gecko_spellcheck||(r.body.spellcheck=!1,QS.setAttrib(o,"spellcheck","false")),t.quirks=JS(t),t.fire("PostRender");var i,a,u,s,c,l,f,d,m,p,g,h=t.getParam("directionality",Au.isRtl()?"rtl":undefined);h!==undefined&&(o.dir=h),n.protect&&t.on("BeforeSetContent",function(t){xt.each(n.protect,function(e){t.content=t.content.replace(e,function(e){return"\x3c!--mce:protected "+escape(e)+"--\x3e"})})}),t.on("SetContent",function(){t.addVisual(t.getBody())}),!1===e&&t.load({initial:!0,format:"html"}),t.startContent=t.getContent({format:"raw"}),t.on("compositionstart compositionend",function(e){t.composing="compositionstart"===e.type}),0<t.contentStyles.length&&(i="",xt.each(t.contentStyles,function(e){i+=e+"\r\n"}),t.dom.addStyle(i)),u=(a=t).contentCSS,c=(s=a).inline?s.ui.styleSheetLoader:s.dom.styleSheetLoader,l=function(){a.on("remove",function(){return c.unloadAll(u)}),nN(a)},c.loadAll(u,l,l),n.content_style&&(f=t,d=n.content_style,m=Nt.fromDom(f.getBody()),p=en(Zt(m)),g=Nt.fromTag("style"),qn(g,"type","text/css"),un(g,Nt.fromText(d)),un(p,g),f.on("remove",function(){ln(g)}))},oN=function(t,e){var n=t.settings,r=t.getElement(),o=t.getDoc();n.inline||(t.getElement().style.visibility=t.orgVisibility),e||t.inline||(o.open(),o.write(t.iframeHTML),o.close()),t.inline&&(QS.addClass(r,"mce-content-body"),t.contentDocument=o=document,t.contentWindow=window,t.bodyElement=r,t.contentAreaContainer=r);var u,i,a,s,c=t.getBody();c.disabled=!0,t.readonly=!!n.readonly,t.readonly||(t.inline&&"static"===QS.getStyle(c,"position",!0)&&(c.style.position="relative"),c.contentEditable=t.getParam("content_editable_state",!0)),c.disabled=!1,t.editorUpload=Jy(t),t.schema=pi(n),t.dom=bu(o,{keep_values:!0,url_converter:t.convertURL,url_converter_scope:t,hex_colors:n.force_hex_style_colors,update_styles:!0,root_element:t.inline?t.getBody():null,collect:function(){return t.inline},schema:t.schema,contentCssCors:t.getParam("content_css_cors",!1,"boolean"),referrerPolicy:gc(t),onSetAttrib:function(e){t.fire("SetAttrib",e)}}),t.parser=((i=Zv(eN(u=t),u.schema)).addAttributeFilter("src,href,style,tabindex",function(e,t){for(var n,r,o=e.length,i=u.dom,a="data-mce-"+t;o--;)if((r=(n=e[o]).attr(t))&&!n.attr(a)){if(0===r.indexOf("data:")||0===r.indexOf("blob:"))continue;"style"===t?((r=i.serializeStyle(i.parseStyle(r),n.name)).length||(r=null),n.attr(a,r),n.attr(t,r)):"tabindex"===t?(n.attr(a,r),n.attr(t,null)):n.attr(a,u.convertURL(r,t,n.name))}}),i.addNodeFilter("script",function(e){for(var t=e.length;t--;){var n=e[t],r=n.attr("type")||"no/type";0!==r.indexOf("mce-")&&n.attr("type","mce-"+r)}}),u.settings.preserve_cdata&&i.addNodeFilter("#cdata",function(e){for(var t=e.length;t--;){var n=e[t];n.type=8,n.name="#comment",n.value="[CDATA["+u.dom.encode(n.value)+"]]"}}),i.addNodeFilter("p,h1,h2,h3,h4,h5,h6,div",function(e){for(var t=e.length,n=u.schema.getNonEmptyElements();t--;){var r=e[t];r.isEmpty(n)&&0===r.getAll("br").length&&(r.append(new Em("br",1)).shortEnded=!0)}}),i),t.serializer=oy((s=(a=t).settings,xe(xe({},eN(a)),ZS({url_converter:s.url_converter,url_converter_scope:s.url_converter_scope,element_format:s.element_format,entities:s.entities,entity_encoding:s.entity_encoding,indent:s.indent,indent_after:s.indent_after,indent_before:s.indent_before,block_elements:s.block_elements,boolean_attributes:s.boolean_attributes,custom_elements:s.custom_elements,extended_valid_elements:s.extended_valid_elements,invalid_elements:s.invalid_elements,invalid_styles:s.invalid_styles,move_caret_before_on_enter_elements:s.move_caret_before_on_enter_elements,non_empty_elements:s.non_empty_elements,schema:s.schema,self_closing_elements:s.self_closing_elements,short_ended_elements:s.short_ended_elements,special:s.special,text_block_elements:s.text_block_elements,text_inline_elements:s.text_inline_elements,valid_children:s.valid_children,valid_classes:s.valid_classes,valid_elements:s.valid_elements,valid_styles:s.valid_styles,verify_html:s.verify_html,whitespace_elements:s.whitespace_elements}))),t),t.selection=Ov(t.dom,t.getWin(),t.serializer,t),t.annotator=qf(t),t.formatter=cb(t),t.undoManager=fb(t),t._nodeChangeDispatcher=new DS(t),t._selectionOverrides=GS(t),pw(t),BS(t),xv(t)||LS(t);var l,f,d,m,p=xv(l=t)?ku(null):AS(l);dw(t,p),fc(f=t)&&f.on("NodeChange",E(hw,f)),hb(t),t.fire("PreInit"),de((m=d=t).plugins,"rtc").fold(function(){return m.rtcInstance=Cv(d),U.none()},function(e){return U.some(e.setup().then(function(e){return m.rtcInstance=wv(d,e),e.isRemote}))}).fold(function(){rN(t,!1)},function(e){t.setProgressState(!0),e.then(function(e){t.setProgressState(!1),rN(t,e)})})},iN=bu.DOM,aN=function(e){var t=e.getParam("doctype","<!DOCTYPE html>")+"<html><head>";e.getParam("document_base_url","")!==e.documentBaseUrl&&(t+='<base href="'+e.documentBaseURI.getURI()+'" />'),t+='<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';var n=cc(e,"body_id","tinymce"),r=cc(e,"body_class","");return lc(e)&&(t+='<meta http-equiv="Content-Security-Policy" content="'+lc(e)+'" />'),t+='</head><body id="'+n+'" class="mce-content-body '+r+'" data-id="'+e.id+'"><br></body></html>'},uN=function(e,t){var n,r,o,i,a=e.editorManager.translate("Rich Text Area. Press ALT-0 for help."),u=(n=e.id,r=a,t.height,o=e.getParam("iframe_attrs",{}),i=Nt.fromTag("iframe"),$n(i,o),$n(i,{id:n+"_ifr",frameBorder:"0",allowTransparency:"true",title:r}),zu(i,"tox-edit-area__iframe"),i.dom);u.onload=function(){u.onload=null,e.fire("load")};var s=function(e,t){if(document.domain!==window.location.hostname&&vt.browser.isIE()){var n=Gy("mce");e[n]=function(){oN(e)};var r='javascript:(function(){document.open();document.domain="'+document.domain+'";var ed = window.parent.tinymce.get("'+e.id+'");document.write(ed.iframeHTML);document.close();ed.'+n+"(true);})()";return iN.setAttrib(t,"src",r),!0}return!1}(e,u);return e.contentAreaContainer=t.iframeContainer,e.iframeElement=u,e.iframeHTML=aN(e),iN.add(t.iframeContainer,u),s},sN=bu.DOM,cN=function(t,n,e){var r=Fy.get(e),o=Fy.urls[e]||t.documentBaseUrl.replace(/\/$/,"");if(e=xt.trim(e),r&&-1===xt.inArray(n,e)){if(xt.each(Fy.dependencies(e),function(e){cN(t,n,e)}),t.plugins[e])return;try{var i=new r(t,o,t.$);(t.plugins[e]=i).init&&(i.init(t,o),n.push(e))}catch(pk){!function(e,t,n){var r=Au.translate(["Failed to initialize plugin: {0}",t]);Wy(r,n),Hy(e,r)}(t,e,pk)}}},lN=function(e){return e.replace(/^\-/,"")},fN=function(e){return{editorContainer:e,iframeContainer:e,api:{}}},dN=function(e){var t,n,r=e.getElement();return e.inline?fN(null):(t=r,n=sN.create("div"),sN.insertAfter(n,t),fN(n))},mN=function(e){var t,n,r,o=e.getElement();return e.orgDisplay=o.style.display,q(Cc(e))?e.theme.renderUI():A(Cc(e))?(n=(t=e).getElement(),(r=Cc(t)(t,n)).editorContainer.nodeType&&(r.editorContainer.id=r.editorContainer.id||t.id+"_parent"),r.iframeContainer&&r.iframeContainer.nodeType&&(r.iframeContainer.id=r.iframeContainer.id||t.id+"_iframecontainer"),r.height=r.iframeHeight?r.iframeHeight:n.offsetHeight,r):dN(e)},pN=function(e){var n,t,r,o,i,a,u,s,c;e.fire("ScriptsLoaded"),n=e,t=xt.trim(pc(n)),r=n.ui.registry.getAll().icons,o=xe(xe({},Ry.get("default").icons),Ry.get(t).icons),oe(o,function(e,t){me(r,t)||n.ui.registry.addIcon(t,e)}),u=Cc(i=e),q(u)?(i.settings.theme=lN(u),a=Uy.get(u),i.theme=new a(i,Uy.urls[u]),i.theme.init&&i.theme.init(i,Uy.urls[u]||i.documentBaseUrl.replace(/\/$/,""),i.$)):i.theme={},s=e,c=[],xt.each(xc(s).split(/[ ,]/),function(e){cN(s,c,lN(e))});var l=mN(e);e.ui=xe(xe({},e.ui),l.api);var f,d,m,p,g={editorContainer:l.editorContainer,iframeContainer:l.iframeContainer};return e.editorContainer=g.editorContainer?g.editorContainer:null,(f=e).contentCSS=f.contentCSS.concat(Ky(f)),e.inline?oN(e):(p=uN(d=e,m=g),m.editorContainer&&(iN.get(m.editorContainer).style.display=d.orgDisplay,d.hidden=iN.isHidden(m.editorContainer)),d.getElement().style.display="none",iN.setAttrib(d.id,"aria-hidden","true"),void(p||oN(d)))},gN=bu.DOM,hN=function(e){return"-"===e.charAt(0)},vN=function(e,t){var n,r=hc(t),o=t.getParam("language_url","","string");!1===Au.hasCode(r)&&"en"!==r&&(n=""!==o?o:t.editorManager.baseURL+"/langs/"+r+".js",e.add(n,V,undefined,function(){Vy(t,"LanguageLoadError",qy("language",n,r))}))},yN=function(t,e,n){return U.from(e).filter(function(e){return 0<e.length&&!Ry.has(e)}).map(function(e){return{url:t.editorManager.baseURL+"/icons/"+e+"/icons"+n+".js",name:U.some(e)}})},bN=function(e,o,t){var n,r=yN(o,"default",t),i=(n=o,U.from(n.getParam("icons_url","","string")).filter(function(e){return 0<e.length}).map(function(e){return{url:e,name:U.none()}}).orThunk(function(){return yN(o,pc(o),"")}));$(function(e){for(var t=[],n=function(e){t.push(e)},r=0;r<e.length;r++)e[r].each(n);return t}([r,i]),function(r){e.add(r.url,V,undefined,function(){var e,t,n;e=o,t=r.url,n=r.name.getOrUndefined(),Vy(e,"IconsLoadError",qy("icons",t,n))})})},CN=function(e,t){var n,r,o,i,a,u,s=Su.ScriptLoader;n=s,o=t,i=function(){var r,o;vN(s,e),bN(s,e,t),r=e,o=t,xt.each(r.getParam("external_plugins"),function(e,t){Fy.load(t,e,V,undefined,function(){$y(r,e,t)}),r.settings.plugins+=" "+t}),xt.each(xc(r).split(/[ ,]/),function(e){var t,n;(e=xt.trim(e))&&!Fy.urls[e]&&(hN(e)?(e=e.substr(1,e.length),t=Fy.dependencies(e),xt.each(t,function(e){var t={prefix:"plugins/",resource:e,suffix:"/plugin"+o+".js"},n=Fy.createUrl(t,e);Fy.load(n.resource,n,V,undefined,function(){$y(r,n.prefix+n.resource+n.suffix,n.resource)})})):(n={prefix:"plugins/",resource:e,suffix:"/plugin"+o+".js"},Fy.load(e,n,V,undefined,function(){$y(r,n.prefix+n.resource+n.suffix,e)})))}),s.loadQueue(function(){e.removed||pN(e)},e,function(){e.removed||pN(e)})},u=Cc(r=e),q(u)?(hN(u)||Uy.urls.hasOwnProperty(u)||((a=r.getParam("theme_url"))?Uy.load(u,r.documentBaseURI.toAbsolute(a)):Uy.load(u,"themes/"+u+"/theme"+o+".js")),n.loadQueue(function(){Uy.waitFor(u,i)})):i()},wN=function(t){var e=t.id;Au.setCode(hc(t));var n,r,o,i,a,u=function(){gN.unbind(window,"ready",u),t.render()};Ni.Event.domLoaded?t.getElement()&&vt.contentEditable&&(n=Nt.fromDom(t.getElement()),r=W(n.dom.attributes,function(e,t){return e[t.name]=t.value,e},{}),t.on("remove",function(){z(n.dom.attributes,function(e){return Kn(n,e.name),0}),$n(n,r)}),t.ui.styleSheetLoader=(o=n,i=t,jr.forElement(o,{contentCssCors:i.getParam("content_css_cors"),referrerPolicy:gc(i)})),t.getParam("inline")?t.inline=!0:(t.orgVisibility=t.getElement().style.visibility,t.getElement().style.visibility="hidden"),(a=t.getElement().form||gN.getParent(e,"form"))&&(t.formElement=a,t.getParam("hidden_input")&&!Dn(t.getElement())&&(gN.insertAfter(gN.create("input",{type:"hidden",name:e}),e),t.hasHiddenInput=!0),t.formEventDelegate=function(e){t.fire(e.type,e)},gN.bind(a,"submit reset",t.formEventDelegate),t.on("reset",function(){t.resetContent()}),!t.getParam("submit_patch")||a.submit.nodeType||a.submit.length||a._mceOldSubmit||(a._mceOldSubmit=a.submit,a.submit=function(){return t.editorManager.triggerSave(),t.setDirty(!1),a._mceOldSubmit(a)})),t.windowManager=zy(t),t.notificationManager=My(t),"xml"===t.getParam("encoding")&&t.on("GetContent",function(e){e.save&&(e.content=gN.encode(e.content))}),t.getParam("add_form_submit_trigger")&&t.on("submit",function(){t.initialized&&t.save()}),t.getParam("add_unload_trigger")&&(t._beforeUnload=function(){!t.initialized||t.destroyed||t.isHidden()||t.save({format:"raw",no_events:!0,set_dirty:!1})},t.editorManager.on("BeforeUnload",t._beforeUnload)),t.editorManager.add(t),CN(t,t.suffix)):gN.bind(window,"ready",u)},xN=function(e){return A(e)?e:p},SN=function(e,t,n){var r=t(e),o=xN(n);return r.orThunk(function(){return o(e)?U.none():function(e,t,n){for(var r=e.dom,o=xN(n);r.parentNode;){r=r.parentNode;var i=Nt.fromDom(r),a=t(i);if(a.isSome())return a;if(o(i))break}return U.none()}(e,t,o)})},NN={"font-size":"size","font-family":"face"},EN=function(e,t,n){var r=function(r){return Jn(r,e).orThunk(function(){return"font"===Dt(r)?de(NN,e).bind(function(e){return t=r,n=e,U.from(Wn(t,n));var t,n}):U.none()})};return SN(Nt.fromDom(n),r,function(e){return Rt(Nt.fromDom(t),e)})},kN=function(o){return function(r,e){return U.from(e).map(Nt.fromDom).filter(Pt).bind(function(e){return EN(o,r,e.dom).or((t=o,n=e.dom,U.from(bu.DOM.getStyle(n,t,!0))));var t,n}).getOr("")}},_N=kN("font-size"),RN=a(function(e){return e.replace(/[\'\"\\]/g,"").replace(/,\s+/g,",")},kN("font-family")),TN=function(e){return Ol(e.getBody()).map(function(e){var t=e.container();return On(t)?t.parentNode:t})},AN=function(e,t){return n=e,U.from(n.selection.getRng()).bind(function(e){var t=n.getBody();return e.startContainer===t&&0===e.startOffset?U.none():U.from(n.selection.getStart(!0))}).orThunk(E(TN,e)).map(Nt.fromDom).filter(Pt).map(t);var n},DN=function(e,t){if(/^[0-9.]+$/.test(t)){var n=parseInt(t,10);if(1<=n&&n<=7){var r=(a=e,xt.explode(a.getParam("font_size_style_values","xx-small,x-small,small,medium,large,x-large,xx-large"))),o=(i=e,xt.explode(i.getParam("font_size_classes","")));return o?o[n-1]||t:r[n-1]||t}return t}return t;var i,a},ON=function(e,t){var n,r=DN(e,t);e.formatter.toggle("fontname",{value:(n=r.split(/\s*,\s*/),F(n,function(e){return-1===e.indexOf(" ")||Ue(e,'"')||Ue(e,"'")?e:"'"+e+"'"}).join(","))}),e.nodeChanged()},BN=function(e,t){var n,r,o,i,a="string"!=typeof(n=t)?(r=xt.extend({paste:n.paste,data:{paste:n.paste}},n),{content:n.content,details:r}):{content:n,details:{}};o=a.content,i=a.details,Sv(e).editor.insertContent(o,i)},PN=xt.each,LN=xt.map,IN=xt.inArray,MN=(FN.prototype.execCommand=function(t,n,r,e){var o,i,a=!1,u=this;if(!u.editor.removed){if(/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(t)||e&&e.skip_focus?(i=u.editor,tm(i).each(function(e){return i.selection.setRng(e)})):u.editor.focus(),(e=u.editor.fire("BeforeExecCommand",{command:t,ui:n,value:r})).isDefaultPrevented())return!1;var s=t.toLowerCase();if(o=u.commands.exec[s])return o(s,n,r),u.editor.fire("ExecCommand",{command:t,ui:n,value:r}),!0;if(PN(this.editor.plugins,function(e){if(e.execCommand&&e.execCommand(t,n,r))return u.editor.fire("ExecCommand",{command:t,ui:n,value:r}),!(a=!0)}),a)return a;if(u.editor.theme&&u.editor.theme.execCommand&&u.editor.theme.execCommand(t,n,r))return u.editor.fire("ExecCommand",{command:t,ui:n,value:r}),!0;try{a=u.editor.getDoc().execCommand(t,n,r)}catch(c){}return!!a&&(u.editor.fire("ExecCommand",{command:t,ui:n,value:r}),!0)}},FN.prototype.queryCommandState=function(e){var t;if(!this.editor.quirks.isHidden()&&!this.editor.removed){if(e=e.toLowerCase(),t=this.commands.state[e])return t(e);try{return this.editor.getDoc().queryCommandState(e)}catch(n){}return!1}},FN.prototype.queryCommandValue=function(e){var t;if(!this.editor.quirks.isHidden()&&!this.editor.removed){if(e=e.toLowerCase(),t=this.commands.value[e])return t(e);try{return this.editor.getDoc().queryCommandValue(e)}catch(n){}}},FN.prototype.addCommands=function(e,n){void 0===n&&(n="exec");var r=this;PN(e,function(t,e){PN(e.toLowerCase().split(","),function(e){r.commands[n][e]=t})})},FN.prototype.addCommand=function(e,o,i){var a=this;e=e.toLowerCase(),this.commands.exec[e]=function(e,t,n,r){return o.call(i||a.editor,t,n,r)}},FN.prototype.queryCommandSupported=function(e){if(e=e.toLowerCase(),this.commands.exec[e])return!0;try{return this.editor.getDoc().queryCommandSupported(e)}catch(t){}return!1},FN.prototype.addQueryStateHandler=function(e,t,n){var r=this;e=e.toLowerCase(),this.commands.state[e]=function(){return t.call(n||r.editor)}},FN.prototype.addQueryValueHandler=function(e,t,n){var r=this;e=e.toLowerCase(),this.commands.value[e]=function(){return t.call(n||r.editor)}},FN.prototype.hasCustomCommand=function(e){return e=e.toLowerCase(),!!this.commands.exec[e]},FN.prototype.execNativeCommand=function(e,t,n){return t===undefined&&(t=!1),n===undefined&&(n=null),this.editor.getDoc().execCommand(e,t,n)},FN.prototype.isFormatMatch=function(e){return this.editor.formatter.match(e)},FN.prototype.toggleFormat=function(e,t){this.editor.formatter.toggle(e,t?{value:t}:undefined),this.editor.nodeChanged()},FN.prototype.storeSelection=function(e){this.selectionBookmark=this.editor.selection.getBookmark(e)},FN.prototype.restoreSelection=function(){this.editor.selection.moveToBookmark(this.selectionBookmark)},FN.prototype.setupCommands=function(i){var a=this;this.addCommands({"mceResetDesignMode,mceBeginUndoLevel":function(){},"mceEndUndoLevel,mceAddUndoLevel":function(){i.undoManager.add()},"Cut,Copy,Paste":function(e){var t,n,r=i.getDoc();try{a.execNativeCommand(e)}catch(o){t=!0}"paste"!==e||r.queryCommandEnabled(e)||(t=!0),!t&&r.queryCommandSupported(e)||(n=i.translate("Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X/C/V keyboard shortcuts instead."),vt.mac&&(n=n.replace(/Ctrl\+/g,"\u2318+")),i.notificationManager.open({text:n,type:"error"}))},unlink:function(){var e;i.selection.isCollapsed()?(e=i.dom.getParent(i.selection.getStart(),"a"))&&i.dom.remove(e,!0):i.formatter.remove("link")},"JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,JustifyNone":function(e){var t=e.substring(7);"full"===t&&(t="justify"),PN("left,center,right,justify".split(","),function(e){t!==e&&i.formatter.remove("align"+e)}),"none"!==t&&a.toggleFormat("align"+t)},"InsertUnorderedList,InsertOrderedList":function(e){var t;a.execNativeCommand(e);var n=i.dom.getParent(i.selection.getNode(),"ol,ul");n&&(t=n.parentNode,/^(H[1-6]|P|ADDRESS|PRE)$/.test(t.nodeName)&&(a.storeSelection(),i.dom.split(t,n),a.restoreSelection()))},"Bold,Italic,Underline,Strikethrough,Superscript,Subscript":function(e){a.toggleFormat(e)},"ForeColor,HiliteColor":function(e,t,n){a.toggleFormat(e,n)},FontName:function(e,t,n){ON(i,n)},FontSize:function(e,t,n){var r,o;o=n,(r=i).formatter.toggle("fontsize",{value:DN(r,o)}),r.nodeChanged()},LineHeight:function(e,t,n){var r,o;o=n,(r=i).undoManager.transact(function(){r.formatter.toggle("lineheight",{value:String(o)}),r.nodeChanged()})},RemoveFormat:function(e){i.formatter.remove(e)},mceBlockQuote:function(){a.toggleFormat("blockquote")},FormatBlock:function(e,t,n){return a.toggleFormat(n||"p")},mceCleanup:function(){var e=i.selection.getBookmark();i.setContent(i.getContent()),i.selection.moveToBookmark(e)},mceRemoveNode:function(e,t,n){var r=n||i.selection.getNode();r!==i.getBody()&&(a.storeSelection(),i.dom.remove(r,!0),a.restoreSelection())},mceSelectNodeDepth:function(e,t,n){var r=0;i.dom.getParent(i.selection.getNode(),function(e){if(1===e.nodeType&&r++===n)return i.selection.select(e),!1},i.getBody())},mceSelectNode:function(e,t,n){i.selection.select(n)},mceInsertContent:function(e,t,n){BN(i,n)},mceInsertRawHTML:function(e,t,n){i.selection.setContent("tiny_mce_marker");var r=i.getContent();i.setContent(r.replace(/tiny_mce_marker/g,function(){return n}))},mceInsertNewLine:function(e,t,n){bS(i,n)},mceToggleFormat:function(e,t,n){a.toggleFormat(n)},mceSetContent:function(e,t,n){i.setContent(n)},"Indent,Outdent":function(e){cw(i,e)},mceRepaint:function(){},InsertHorizontalRule:function(){i.execCommand("mceInsertContent",!1,"<hr />")},mceToggleVisualAid:function(){i.hasVisual=!i.hasVisual,i.addVisual()},mceReplaceContent:function(e,t,n){i.execCommand("mceInsertContent",!1,n.replace(/\{\$selection\}/g,i.selection.getContent({format:"text"})))},mceInsertLink:function(e,t,n){"string"==typeof n&&(n={href:n});var r=i.dom.getParent(i.selection.getNode(),"a");n.href=n.href.replace(/ /g,"%20"),r&&n.href||i.formatter.remove("link"),n.href&&i.formatter.apply("link",n,r)},selectAll:function(){var e,t=i.dom.getParent(i.selection.getStart(),Fn);t&&((e=i.dom.createRng()).selectNodeContents(t),i.selection.setRng(e))},mceNewDocument:function(){i.setContent("")},InsertLineBreak:function(e,t,n){return iS(i,n),!0}});var e=function(r){return function(){var e=i.selection,t=e.isCollapsed()?[i.dom.getParent(e.getNode(),i.dom.isBlock)]:e.getSelectedBlocks(),n=LN(t,function(e){return!!i.formatter.matchNode(e,r)});return-1!==IN(n,!0)}};a.addCommands({JustifyLeft:e("alignleft"),JustifyCenter:e("aligncenter"),JustifyRight:e("alignright"),JustifyFull:e("alignjustify"),"Bold,Italic,Underline,Strikethrough,Superscript,Subscript":function(e){return a.isFormatMatch(e)},mceBlockQuote:function(){return a.isFormatMatch("blockquote")},Outdent:function(){return aw(i)},"InsertUnorderedList,InsertOrderedList":function(e){var t=i.dom.getParent(i.selection.getNode(),"ul,ol");return t&&("insertunorderedlist"===e&&"UL"===t.tagName||"insertorderedlist"===e&&"OL"===t.tagName)}},"state"),a.addCommands({Undo:function(){i.undoManager.undo()},Redo:function(){i.undoManager.redo()}}),a.addQueryValueHandler("FontName",function(){return AN(t=i,function(e){return RN(t.getBody(),e.dom)}).getOr("");var t},this),a.addQueryValueHandler("FontSize",function(){return AN(t=i,function(e){return _N(t.getBody(),e.dom)}).getOr("");var t},this),a.addQueryValueHandler("LineHeight",function(){return AN(t=i,function(n){var e=Nt.fromDom(t.getBody());return SN(n,function(e){return Jn(e,"line-height")},E(Rt,e)).getOrThunk(function(){var e=parseFloat(Yn(n,"line-height")),t=parseFloat(Yn(n,"font-size"));return String(e/t)})}).getOr("");var t},this)},FN);function FN(e){this.commands={state:{},exec:{},value:{}},this.editor=e,this.setupCommands(e)}var UN="data-mce-contenteditable",zN=function(e,t,n){var r,o;Hu(e,t)&&!1===n?(o=t,Mu(r=e)?r.dom.classList.remove(o):Uu(r,o),ju(r)):n&&zu(e,t)},jN=function(e,t,n){try{e.getDoc().execCommand(t,!1,String(n))}catch(r){}},HN=function(e,t){e.dom.contentEditable=t?"true":"false"},VN=function(e,t){var n,r,o,i=Nt.fromDom(e.getBody());zN(i,"mce-content-readonly",t),t?(e.selection.controlSelection.hideResizeRect(),e._selectionOverrides.hideFakeCaret(),o=e,U.from(o.selection.getNode()).each(function(e){e.removeAttribute("data-mce-selected")}),e.readonly=!0,HN(i,!1),$(qu(i,'*[contenteditable="true"]'),function(e){qn(e,UN,"true"),HN(e,!1)})):(e.readonly=!1,HN(i,!0),$(qu(i,"*["+UN+'="true"]'),function(e){Kn(e,UN),HN(e,!0)}),jN(e,"StyleWithCSS",!1),jN(e,"enableInlineTableEditing",!1),jN(e,"enableObjectResizing",!1),(pm(r=e)||mm(r))&&e.focus(),(n=e).selection.setRng(n.selection.getRng()),e.nodeChanged())},qN=function(e){return e.readonly},$N=function(t){t.parser.addAttributeFilter("contenteditable",function(e){qN(t)&&$(e,function(e){e.attr(UN,e.attr("contenteditable")),e.attr("contenteditable","false")})}),t.serializer.addAttributeFilter(UN,function(e){qN(t)&&$(e,function(e){e.attr("contenteditable",e.attr(UN))})}),t.serializer.addTempAttr(UN)},WN=xt.makeMap("focus blur focusin focusout click dblclick mousedown mouseup mousemove mouseover beforepaste paste cut copy selectionchange mouseout mouseenter mouseleave wheel keydown keypress keyup input beforeinput contextmenu dragstart dragend dragover draggesture dragdrop drop drag submit compositionstart compositionend compositionupdate touchstart touchmove touchend touchcancel"," "),KN=(XN.isNative=function(e){return!!WN[e.toLowerCase()]},XN.prototype.fire=function(e,t){var n=e.toLowerCase(),r=t||{};r.type=n,r.target||(r.target=this.scope),r.preventDefault||(r.preventDefault=function(){r.isDefaultPrevented=k},r.stopPropagation=function(){r.isPropagationStopped=k},r.stopImmediatePropagation=function(){r.isImmediatePropagationStopped=k},r.isDefaultPrevented=p,r.isPropagationStopped=p,r.isImmediatePropagationStopped=p),this.settings.beforeFire&&this.settings.beforeFire(r);var o=this.bindings[n];if(o)for(var i=0,a=o.length;i<a;i++){var u=o[i];if(u.once&&this.off(n,u.func),r.isImmediatePropagationStopped())return r.stopPropagation(),r;if(!1===u.func.call(this.scope,r))return r.preventDefault(),r}return r},XN.prototype.on=function(e,t,n,r){if(!1===t&&(t=p),t){var o={func:t};r&&xt.extend(o,r);for(var i=e.toLowerCase().split(" "),a=i.length;a--;){var u=i[a],s=this.bindings[u];s||(s=this.bindings[u]=[],this.toggleEvent(u,!0)),n?s.unshift(o):s.push(o)}}return this},XN.prototype.off=function(e,t){var n=this;if(e)for(var r=e.toLowerCase().split(" "),o=r.length;o--;){var i=r[o],a=this.bindings[i];if(!i)return oe(this.bindings,function(e,t){n.toggleEvent(t,!1),delete n.bindings[t]}),this;if(a){if(t)for(var u=a.length;u--;)a[u].func===t&&(a=a.slice(0,u).concat(a.slice(u+1)),this.bindings[i]=a);else a.length=0;a.length||(this.toggleEvent(e,!1),delete this.bindings[i])}}else oe(this.bindings,function(e,t){n.toggleEvent(t,!1)}),this.bindings={};return this},XN.prototype.once=function(e,t,n){return this.on(e,t,n,{once:!0})},XN.prototype.has=function(e){return e=e.toLowerCase(),!(!this.bindings[e]||0===this.bindings[e].length)},XN);function XN(e){this.bindings={},this.settings=e||{},this.scope=this.settings.scope||this,this.toggleEvent=this.settings.toggleEvent||p}var YN,GN=function(n){return n._eventDispatcher||(n._eventDispatcher=new KN({scope:n,toggleEvent:function(e,t){KN.isNative(e)&&n.toggleNativeEvent&&n.toggleNativeEvent(e,t)}})),n._eventDispatcher},JN={fire:function(e,t,n){if(this.removed&&"remove"!==e&&"detach"!==e)return t;var r=GN(this).fire(e,t);if(!1!==n&&this.parent)for(var o=this.parent();o&&!r.isPropagationStopped();)o.fire(e,r,!1),o=o.parent();return r},on:function(e,t,n){return GN(this).on(e,t,n)},off:function(e,t){return GN(this).off(e,t)},once:function(e,t){return GN(this).once(e,t)},hasEventListeners:function(e){return GN(this).has(e)}},QN=bu.DOM,ZN=function(e,t){if("selectionchange"===t)return e.getDoc();if(!e.inline&&/^mouse|touch|click|contextmenu|drop|dragover|dragend/.test(t))return e.getDoc().documentElement;var n=bc(e);return n?(e.eventRoot||(e.eventRoot=QN.select(n)[0]),e.eventRoot):e.getBody()},eE=function(e,t,n){var r,o,i,a,u;(u=e).hidden||qN(u)?qN(e)&&(r=e,a=(o=n).target,"click"!==o.type||Gf.metaKeyPressed(o)||(i=a,null===r.dom.getParent(i,"a"))||o.preventDefault()):e.fire(t,n)},tE=function(i,a){var e;if(i.delegates||(i.delegates={}),!i.delegates[a]&&!i.removed){var t=ZN(i,a);if(bc(i)){if(YN||(YN={},i.editorManager.on("removeEditor",function(){i.editorManager.activeEditor||YN&&(oe(YN,function(e,t){i.dom.unbind(ZN(i,t))}),YN=null)})),YN[a])return;e=function(e){for(var t=e.target,n=i.editorManager.get(),r=n.length;r--;){var o=n[r].getBody();o!==t&&!QN.isChildOf(t,o)||eE(n[r],a,e)}},YN[a]=e,QN.bind(t,a,e)}else e=function(e){eE(i,a,e)},QN.bind(t,a,e),i.delegates[a]=e}},nE=xe(xe({},JN),{bindPendingEventDelegates:function(){var t=this;xt.each(t._pendingNativeEvents,function(e){tE(t,e)})},toggleNativeEvent:function(e,t){var n=this;"focus"!==e&&"blur"!==e&&(t?n.initialized?tE(n,e):n._pendingNativeEvents?n._pendingNativeEvents.push(e):n._pendingNativeEvents=[e]:n.initialized&&(n.dom.unbind(ZN(n,e),e,n.delegates[e]),delete n.delegates[e]))},unbindAllNativeEvents:function(){var n=this,e=n.getBody(),t=n.dom;n.delegates&&(oe(n.delegates,function(e,t){n.dom.unbind(ZN(n,t),t,e)}),delete n.delegates),!n.inline&&e&&t&&(e.onload=null,t.unbind(n.getWin()),t.unbind(n.getDoc())),t&&(t.unbind(e),t.unbind(n.getContainer()))}}),rE=["design","readonly"],oE=function(e,t,n,r){var o,i=n[t.get()],a=n[r];try{a.activate()}catch(pk){return void console.error("problem while activating editor mode "+r+":",pk)}i.deactivate(),i.editorReadOnly!==a.editorReadOnly&&VN(e,a.editorReadOnly),t.set(r),o=r,e.fire("SwitchMode",{mode:o})},iE=function(t){var e,n,r=ku("design"),o=ku({design:{activate:V,deactivate:V,editorReadOnly:!1},readonly:{activate:V,deactivate:V,editorReadOnly:!0}});return(e=t).serializer?$N(e):e.on("PreInit",function(){$N(e)}),(n=t).on("ShowCaret",function(e){qN(n)&&e.preventDefault()}),n.on("ObjectSelected",function(e){qN(n)&&e.preventDefault()}),{isReadOnly:function(){return qN(t)},set:function(e){return function(e,t,n,r){if(r!==n.get()){if(!me(t,r))throw new Error("Editor mode '"+r+"' is invalid");e.initialized?oE(e,n,t,r):e.on("init",function(){return oE(e,n,t,r)})}}(t,o.get(),r,e)},get:function(){return r.get()},register:function(e,t){o.set(function(e,t,n){var r;if(I(rE,t))throw new Error("Cannot override default mode "+t);return xe(xe({},e),((r={})[t]=xe(xe({},n),{deactivate:function(){try{n.deactivate()}catch(pk){console.error("problem while deactivating editor mode "+t+":",pk)}}}),r))}(o.get(),e,t))}}},aE=xt.each,uE=xt.explode,sE={f1:112,f2:113,f3:114,f4:115,f5:116,f6:117,f7:118,f8:119,f9:120,f10:121,f11:122,f12:123},cE=xt.makeMap("alt,ctrl,shift,meta,access"),lE=(fE.prototype.add=function(e,n,t,r){var o=this,i=o.normalizeCommandFunc(t);return aE(uE(xt.trim(e)),function(e){var t=o.createShortcut(e,n,i,r);o.shortcuts[t.id]=t}),!0},fE.prototype.remove=function(e){var t=this.createShortcut(e);return!!this.shortcuts[t.id]&&(delete this.shortcuts[t.id],!0)},fE.prototype.normalizeCommandFunc=function(e){var t=this,n=e;return"string"==typeof n?function(){t.editor.execCommand(n,!1,null)}:xt.isArray(n)?function(){t.editor.execCommand(n[0],n[1],n[2])}:n},fE.prototype.parseShortcut=function(e){var t,n={};aE(uE(e.toLowerCase(),"+"),function(e){e in cE?n[e]=!0:/^[0-9]{2,}$/.test(e)?n.keyCode=parseInt(e,10):(n.charCode=e.charCodeAt(0),n.keyCode=sE[e]||e.toUpperCase().charCodeAt(0))});var r=[n.keyCode];for(t in cE)n[t]?r.push(t):n[t]=!1;return n.id=r.join(","),n.access&&(n.alt=!0,vt.mac?n.ctrl=!0:n.shift=!0),n.meta&&(vt.mac?n.meta=!0:(n.ctrl=!0,n.meta=!1)),n},fE.prototype.createShortcut=function(e,t,n,r){var o=xt.map(uE(e,">"),this.parseShortcut);return o[o.length-1]=xt.extend(o[o.length-1],{func:n,scope:r||this.editor}),xt.extend(o[0],{desc:this.editor.translate(t),subpatterns:o.slice(1)})},fE.prototype.hasModifier=function(e){return e.altKey||e.ctrlKey||e.metaKey},fE.prototype.isFunctionKey=function(e){return"keydown"===e.type&&112<=e.keyCode&&e.keyCode<=123},fE.prototype.matchShortcut=function(e,t){return!!t&&t.ctrl===e.ctrlKey&&t.meta===e.metaKey&&t.alt===e.altKey&&t.shift===e.shiftKey&&!!(e.keyCode===t.keyCode||e.charCode&&e.charCode===t.charCode)&&(e.preventDefault(),!0)},fE.prototype.executeShortcutAction=function(e){return e.func?e.func.call(e.scope):null},fE);function fE(e){this.shortcuts={},this.pendingPatterns=[],this.editor=e;var n=this;e.on("keyup keypress keydown",function(t){!n.hasModifier(t)&&!n.isFunctionKey(t)||t.isDefaultPrevented()||(aE(n.shortcuts,function(e){if(n.matchShortcut(t,e))return n.pendingPatterns=e.subpatterns.slice(0),"keydown"===t.type&&n.executeShortcutAction(e),!0}),n.matchShortcut(t,n.pendingPatterns[0])&&(1===n.pendingPatterns.length&&"keydown"===t.type&&n.executeShortcutAction(n.pendingPatterns[0]),n.pendingPatterns.shift()))})}var dE=function(){var e,t,n,r,o,i,a,u,s=(t={},n={},r={},o={},i={},a={},{addButton:(u=function(n,r){return function(e,t){return n[e.toLowerCase()]=xe(xe({},t),{type:r})}})(e={},"button"),addGroupToolbarButton:u(e,"grouptoolbarbutton"),addToggleButton:u(e,"togglebutton"),addMenuButton:u(e,"menubutton"),addSplitButton:u(e,"splitbutton"),addMenuItem:u(t,"menuitem"),addNestedMenuItem:u(t,"nestedmenuitem"),addToggleMenuItem:u(t,"togglemenuitem"),addAutocompleter:u(n,"autocompleter"),addContextMenu:u(o,"contextmenu"),addContextToolbar:u(i,"contexttoolbar"),addContextForm:u(i,"contextform"),addSidebar:u(a,"sidebar"),addIcon:function(e,t){return r[e.toLowerCase()]=t},getAll:function(){return{buttons:e,menuItems:t,icons:r,popups:n,contextMenus:o,contextToolbars:i,sidebars:a}}});return{addAutocompleter:s.addAutocompleter,addButton:s.addButton,addContextForm:s.addContextForm,addContextMenu:s.addContextMenu,addContextToolbar:s.addContextToolbar,addIcon:s.addIcon,addMenuButton:s.addMenuButton,addMenuItem:s.addMenuItem,addNestedMenuItem:s.addNestedMenuItem,addSidebar:s.addSidebar,addSplitButton:s.addSplitButton,addToggleButton:s.addToggleButton,addGroupToolbarButton:s.addGroupToolbarButton,addToggleMenuItem:s.addToggleMenuItem,getAll:s.getAll}},mE=xt.each,pE=xt.trim,gE="source protocol authority userInfo user password host port relative path directory file query anchor".split(" "),hE={ftp:21,http:80,https:443,mailto:25},vE=(yE.parseDataUri=function(e){var t,n=decodeURIComponent(e).split(","),r=/data:([^;]+)/.exec(n[0]);return r&&(t=r[1]),{type:t,data:n[1]}},yE.getDocumentBaseUrl=function(e){var t=0!==e.protocol.indexOf("http")&&"file:"!==e.protocol?e.href:e.protocol+"//"+e.host+e.pathname;return/^[^:]+:\/\/\/?[^\/]+\//.test(t)&&(t=t.replace(/[\?#].*$/,"").replace(/[\/\\][^\/]+$/,""),/[\/\\]$/.test(t)||(t+="/")),t},yE.prototype.setPath=function(e){var t=/^(.*?)\/?(\w+)?$/.exec(e);this.path=t[0],this.directory=t[1],this.file=t[2],this.source="",this.getURI()},yE.prototype.toRelative=function(e){var t;if("./"===e)return e;var n=new yE(e,{base_uri:this});if("mce_host"!==n.host&&this.host!==n.host&&n.host||this.port!==n.port||this.protocol!==n.protocol&&""!==n.protocol)return n.getURI();var r=this.getURI(),o=n.getURI();return r===o||"/"===r.charAt(r.length-1)&&r.substr(0,r.length-1)===o?r:(t=this.toRelPath(this.path,n.path),n.query&&(t+="?"+n.query),n.anchor&&(t+="#"+n.anchor),t)},yE.prototype.toAbsolute=function(e,t){var n=new yE(e,{base_uri:this});return n.getURI(t&&this.isSameOrigin(n))},yE.prototype.isSameOrigin=function(e){if(this.host==e.host&&this.protocol==e.protocol){if(this.port==e.port)return!0;var t=hE[this.protocol];if(t&&(this.port||t)==(e.port||t))return!0}return!1},yE.prototype.toRelPath=function(e,t){var n,r,o=0,i="",a=e.substring(0,e.lastIndexOf("/")).split("/"),u=t.split("/");if(a.length>=u.length)for(n=0,r=a.length;n<r;n++)if(n>=u.length||a[n]!==u[n]){o=n+1;break}if(a.length<u.length)for(n=0,r=u.length;n<r;n++)if(n>=a.length||a[n]!==u[n]){o=n+1;break}if(1===o)return t;for(n=0,r=a.length-(o-1);n<r;n++)i+="../";for(n=o-1,r=u.length;n<r;n++)i+=n!==o-1?"/"+u[n]:u[n];return i},yE.prototype.toAbsPath=function(e,t){var n,r,o=0,i=[],a=/\/$/.test(t)?"/":"",u=e.split("/"),s=t.split("/");for(mE(u,function(e){e&&i.push(e)}),u=i,n=s.length-1,i=[];0<=n;n--)0!==s[n].length&&"."!==s[n]&&(".."!==s[n]?0<o?o--:i.push(s[n]):o++);return 0!==(r=(n=u.length-o)<=0?J(i).join("/"):u.slice(0,n).join("/")+"/"+J(i).join("/")).indexOf("/")&&(r="/"+r),a&&r.lastIndexOf("/")!==r.length-1&&(r+=a),r},yE.prototype.getURI=function(e){var t;return void 0===e&&(e=!1),this.source&&!e||(t="",e||(this.protocol?t+=this.protocol+"://":t+="//",this.userInfo&&(t+=this.userInfo+"@"),this.host&&(t+=this.host),this.port&&(t+=":"+this.port)),this.path&&(t+=this.path),this.query&&(t+="?"+this.query),this.anchor&&(t+="#"+this.anchor),this.source=t),this.source},yE);function yE(e,t){e=pE(e),this.settings=t||{};var n,r,o,i,a=this.settings.base_uri,u=this;/^([\w\-]+):([^\/]{2})/i.test(e)||/^\s*#/.test(e)?u.source=e:(n=0===e.indexOf("//"),0!==e.indexOf("/")||n||(e=(a&&a.protocol||"http")+"://mce_host"+e),/^[\w\-]*:?\/\//.test(e)||(r=this.settings.base_uri?this.settings.base_uri.path:new yE(document.location.href).directory,e=this.settings.base_uri&&""==this.settings.base_uri.protocol?"//mce_host"+u.toAbsPath(r,e):(o=/([^#?]*)([#?]?.*)/.exec(e),(a&&a.protocol||"http")+"://mce_host"+u.toAbsPath(r,o[1])+o[2])),e=e.replace(/@@/g,"(mce_at)"),i=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(e),mE(gE,function(e,t){var n=(n=i[t])&&n.replace(/\(mce_at\)/g,"@@");u[e]=n}),a&&(u.protocol||(u.protocol=a.protocol),u.userInfo||(u.userInfo=a.userInfo),u.port||"mce_host"!==u.host||(u.port=a.port),u.host&&"mce_host"!==u.host||(u.host=a.host),u.source=""),n&&(u.protocol=""))}var bE=bu.DOM,CE=xt.extend,wE=xt.each,xE=xt.resolve,SE=vt.ie,NE=(EE.prototype.render=function(){wN(this)},EE.prototype.focus=function(e){var t,n;n=e,(t=this).removed||(n?hm:gm)(t)},EE.prototype.hasFocus=function(){return pm(this)},EE.prototype.execCallback=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var r,o=this.settings[e];if(o)return this.callbackLookup&&(r=this.callbackLookup[e])&&(o=r.func,r=r.scope),"string"==typeof o&&(r=(r=o.replace(/\.\w+$/,""))?xE(r):0,o=xE(o),this.callbackLookup=this.callbackLookup||{},this.callbackLookup[e]={func:o,scope:r}),o.apply(r||this,t)},EE.prototype.translate=function(e){return Au.translate(e)},EE.prototype.getParam=function(e,t,n){return _y(this,e,t,n)},EE.prototype.hasPlugin=function(e,t){return!(!I(xc(this).split(/[ ,]/),e)||t&&Fy.get(e)===undefined)},EE.prototype.nodeChanged=function(e){this._nodeChangeDispatcher.nodeChanged(e)},EE.prototype.addCommand=function(e,t,n){this.editorCommands.addCommand(e,t,n)},EE.prototype.addQueryStateHandler=function(e,t,n){this.editorCommands.addQueryStateHandler(e,t,n)},EE.prototype.addQueryValueHandler=function(e,t,n){this.editorCommands.addQueryValueHandler(e,t,n)},EE.prototype.addShortcut=function(e,t,n,r){this.shortcuts.add(e,t,n,r)},EE.prototype.execCommand=function(e,t,n,r){return this.editorCommands.execCommand(e,t,n,r)},EE.prototype.queryCommandState=function(e){return this.editorCommands.queryCommandState(e)},EE.prototype.queryCommandValue=function(e){return this.editorCommands.queryCommandValue(e)},EE.prototype.queryCommandSupported=function(e){return this.editorCommands.queryCommandSupported(e)},EE.prototype.show=function(){this.hidden&&(this.hidden=!1,this.inline?this.getBody().contentEditable="true":(bE.show(this.getContainer()),bE.hide(this.id)),this.load(),this.fire("show"))},EE.prototype.hide=function(){var e=this,t=e.getDoc();e.hidden||(SE&&t&&!e.inline&&t.execCommand("SelectAll"),e.save(),e.inline?(e.getBody().contentEditable="false",e===e.editorManager.focusedEditor&&(e.editorManager.focusedEditor=null)):(bE.hide(e.getContainer()),bE.setStyle(e.id,"display",e.orgDisplay)),e.hidden=!0,e.fire("hide"))},EE.prototype.isHidden=function(){return!!this.hidden},EE.prototype.setProgressState=function(e,t){this.fire("ProgressState",{state:e,time:t})},EE.prototype.load=function(e){var t=this.getElement();if(this.removed)return"";if(t){(e=e||{}).load=!0;var n=Dn(t)?t.value:t.innerHTML,r=this.setContent(n,e);return e.element=t,e.no_events||this.fire("LoadContent",e),e.element=t=null,r}},EE.prototype.save=function(e){var t,n,r=this,o=r.getElement();if(o&&r.initialized&&!r.removed)return(e=e||{}).save=!0,e.element=o,e.content=r.getContent(e),e.no_events||r.fire("SaveContent",e),"raw"===e.format&&r.fire("RawSaveContent",e),t=e.content,Dn(o)?o.value=t:(!e.is_removing&&r.inline||(o.innerHTML=t),(n=bE.getParent(r.id,"form"))&&wE(n.elements,function(e){if(e.name===r.id)return e.value=t,!1})),e.element=o=null,!1!==e.set_dirty&&r.setDirty(!1),t},EE.prototype.setContent=function(e,t){return ay(this,e,t)},EE.prototype.getContent=function(e){return iy(this,e)},EE.prototype.insertContent=function(e,t){t&&(e=CE({content:e},t)),this.execCommand("mceInsertContent",!1,e)},EE.prototype.resetContent=function(e){e===undefined?ay(this,this.startContent,{format:"raw"}):ay(this,e),this.undoManager.reset(),this.setDirty(!1),this.nodeChanged()},EE.prototype.isDirty=function(){return!this.isNotDirty},EE.prototype.setDirty=function(e){var t=!this.isNotDirty;this.isNotDirty=!e,e&&e!==t&&this.fire("dirty")},EE.prototype.getContainer=function(){return this.container||(this.container=bE.get(this.editorContainer||this.id+"_parent")),this.container},EE.prototype.getContentAreaContainer=function(){return this.contentAreaContainer},EE.prototype.getElement=function(){return this.targetElm||(this.targetElm=bE.get(this.id)),this.targetElm},EE.prototype.getWin=function(){var e;return this.contentWindow||(e=this.iframeElement)&&(this.contentWindow=e.contentWindow),this.contentWindow},EE.prototype.getDoc=function(){var e;return this.contentDocument||(e=this.getWin())&&(this.contentDocument=e.document),this.contentDocument},EE.prototype.getBody=function(){var e=this.getDoc();return this.bodyElement||(e?e.body:null)},EE.prototype.convertURL=function(e,t,n){var r=this.settings;return r.urlconverter_callback?this.execCallback("urlconverter_callback",e,n,!0,t):!r.convert_urls||n&&"LINK"===n.nodeName||0===e.indexOf("file:")||0===e.length?e:r.relative_urls?this.documentBaseURI.toRelative(e):e=this.documentBaseURI.toAbsolute(e,r.remove_script_host)},EE.prototype.addVisual=function(e){var n,r=this,o=r.settings,i=r.dom;e=e||r.getBody(),r.hasVisual===undefined&&(r.hasVisual=o.visual),wE(i.select("table,a",e),function(e){var t;switch(e.nodeName){case"TABLE":return n=o.visual_table_class||"mce-item-table",void((t=i.getAttrib(e,"border"))&&"0"!==t||!r.hasVisual?i.removeClass(e,n):i.addClass(e,n));case"A":return void(i.getAttrib(e,"href")||(t=i.getAttrib(e,"name")||e.id,n=o.visual_anchor_class||"mce-item-anchor",t&&r.hasVisual?i.addClass(e,n):i.removeClass(e,n)))}}),r.fire("VisualAid",{element:e,hasVisual:r.hasVisual})},EE.prototype.remove=function(){cy(this)},EE.prototype.destroy=function(e){ly(this,e)},EE.prototype.uploadImages=function(e){return this.editorUpload.uploadImages(e)},EE.prototype._scanForImages=function(){return this.editorUpload.scanForImages()},EE.prototype.addButton=function(){throw new Error("editor.addButton has been removed in tinymce 5x, use editor.ui.registry.addButton or editor.ui.registry.addToggleButton or editor.ui.registry.addSplitButton instead")},EE.prototype.addSidebar=function(){throw new Error("editor.addSidebar has been removed in tinymce 5x, use editor.ui.registry.addSidebar instead")},EE.prototype.addMenuItem=function(){throw new Error("editor.addMenuItem has been removed in tinymce 5x, use editor.ui.registry.addMenuItem instead")},EE.prototype.addContextToolbar=function(){throw new Error("editor.addContextToolbar has been removed in tinymce 5x, use editor.ui.registry.addContextToolbar instead")},EE);function EE(e,t,n){var r=this;this.plugins={},this.contentCSS=[],this.contentStyles=[],this.loadedCSS={},this.isNotDirty=!1,this.editorManager=n,this.documentBaseUrl=n.documentBaseURL,CE(this,nE),this.settings=Ey(this,e,this.documentBaseUrl,n.defaultSettings,t),this.settings.suffix&&(n.suffix=this.settings.suffix),this.suffix=n.suffix,this.settings.base_url&&n._setBaseUrl(this.settings.base_url),this.baseUri=n.baseURI,this.settings.referrer_policy&&(Su.ScriptLoader._setReferrerPolicy(this.settings.referrer_policy),bu.DOM.styleSheetLoader._setReferrerPolicy(this.settings.referrer_policy)),Bu.languageLoad=this.settings.language_load,Bu.baseURL=n.baseURL,this.id=e,this.setDirty(!1),this.documentBaseURI=new vE(this.settings.document_base_url,{base_uri:this.baseUri}),this.baseURI=this.baseUri,this.inline=!!this.settings.inline,this.shortcuts=new lE(this),this.editorCommands=new MN(this),this.settings.cache_suffix&&(vt.cacheSuffix=this.settings.cache_suffix.replace(/^[\?\&]+/,"")),this.ui={registry:dE(),styleSheetLoader:undefined,show:V,hide:V};var o=iE(this);this.mode=o,this.setMode=o.set,n.fire("SetupEditor",{editor:this}),this.execCallback("setup",this),this.$=lu.overrideDefaults(function(){return{context:r.inline?r.getBody():r.getDoc(),element:r.getBody()}})}var kE,_E=bu.DOM,RE=xt.explode,TE=xt.each,AE=xt.extend,DE=0,OE=!1,BE=[],PE=[],LE=function(t){var n=t.type;TE(UE.get(),function(e){switch(n){case"scroll":e.fire("ScrollWindow",t);break;case"resize":e.fire("ResizeWindow",t)}})},IE=function(e){e!==OE&&(e?lu(window).on("resize scroll",LE):lu(window).off("resize scroll",LE),OE=e)},ME=function(t){var e=PE;delete BE[t.id];for(var n=0;n<BE.length;n++)if(BE[n]===t){BE.splice(n,1);break}return PE=j(PE,function(e){return t!==e}),UE.activeEditor===t&&(UE.activeEditor=0<PE.length?PE[0]:null),UE.focusedEditor===t&&(UE.focusedEditor=null),e.length!==PE.length},FE="CSS1Compat"!==document.compatMode,UE=xe(xe({},JN),{baseURI:null,baseURL:null,defaultSettings:{},documentBaseURL:null,suffix:null,$:lu,majorVersion:"5",minorVersion:"5.1",releaseDate:"2020-10-01",editors:BE,i18n:Au,activeEditor:null,focusedEditor:null,settings:{},setup:function(){var e,t="",n=vE.getDocumentBaseUrl(document.location);/^[^:]+:\/\/\/?[^\/]+\//.test(n)&&(n=n.replace(/[\?#].*$/,"").replace(/[\/\\][^\/]+$/,""),/[\/\\]$/.test(n)||(n+="/"));var r,o=window.tinymce||window.tinyMCEPreInit;if(o)e=o.base||o.baseURL,t=o.suffix;else{for(var i,a=document.getElementsByTagName("script"),u=0;u<a.length;u++){if(""!==(i=a[u].src||"")){var s=i.substring(i.lastIndexOf("/"));if(/tinymce(\.full|\.jquery|)(\.min|\.dev|)\.js/.test(i)){-1!==s.indexOf(".min")&&(t=".min"),e=i.substring(0,i.lastIndexOf("/"));break}}}!e&&document.currentScript&&(-1!==(i=document.currentScript.src).indexOf(".min")&&(t=".min"),e=i.substring(0,i.lastIndexOf("/")))}this.baseURL=new vE(n).toAbsolute(e),this.documentBaseURL=n,this.baseURI=new vE(this.baseURL),this.suffix=t,(r=this).on("AddEditor",E(um,r)),r.on("RemoveEditor",E(sm,r))},overrideDefaults:function(e){var t=e.base_url;t&&this._setBaseUrl(t);var n=e.suffix;e.suffix&&(this.suffix=n);var r=(this.defaultSettings=e).plugin_base_urls;r!==undefined&&oe(r,function(e,t){Bu.PluginManager.urls[t]=e})},init:function(r){var n,u=this,s=xt.makeMap("area base basefont br col frame hr img input isindex link meta param embed source wbr track colgroup option table tbody tfoot thead tr th td script noscript style textarea video audio iframe object menu"," "),c=function(e){var t=e.id;return t||(t=de(e,"name").filter(function(e){return!_E.get(e)}).getOrThunk(_E.uniqueId),e.setAttribute("id",t)),t},l=function(e,t){return t.constructor===RegExp?t.test(e.className):_E.hasClass(e,t)},f=function(e){n=e},e=function(){var o,i=0,a=[],n=function(e,t,n){var r=new NE(e,t,u);a.push(r),r.on("init",function(){++i===o.length&&f(a)}),r.targetElm=r.targetElm||n,r.render()};_E.unbind(window,"ready",e),function(e){var t=r[e];if(t)t.apply(u,Array.prototype.slice.call(arguments,2))}("onpageload"),o=lu.unique(function(t){var n=[];if(vt.browser.isIE()&&vt.browser.version.major<11)return Wy("TinyMCE does not support the browser you are using. For a list of supported browsers please see: https://www.tinymce.com/docs/get-started/system-requirements/"),[];if(FE)return Wy("Failed to initialize the editor as the document is not in standards mode. TinyMCE requires standards mode."),[];if(t.types)return TE(t.types,function(e){n=n.concat(_E.select(e.selector))}),n;if(t.selector)return _E.select(t.selector);if(t.target)return[t.target];switch(t.mode){case"exact":var e=t.elements||"";0<e.length&&TE(RE(e),function(t){var e=_E.get(t);e?n.push(e):TE(document.forms,function(e){TE(e.elements,function(e){e.name===t&&(t="mce_editor_"+DE++,_E.setAttrib(e,"id",t),n.push(e))})})});break;case"textareas":case"specific_textareas":TE(_E.select("textarea"),function(e){t.editor_deselector&&l(e,t.editor_deselector)||t.editor_selector&&!l(e,t.editor_selector)||n.push(e)})}return n}(r)),r.types?TE(r.types,function(t){xt.each(o,function(e){return!_E.is(e,t.selector)||(n(c(e),AE({},r,t),e),!1)})}):(xt.each(o,function(e){var t;(t=u.get(e.id))&&t.initialized&&!(t.getContainer()||t.getBody()).parentNode&&(ME(t),t.unbindAllNativeEvents(),t.destroy(!0),t.removed=!0,t=null)}),0===(o=xt.grep(o,function(e){return!u.get(e.id)})).length?f([]):TE(o,function(e){var t;t=e,r.inline&&t.tagName.toLowerCase()in s?Wy("Could not initialize inline editor on invalid inline target element",e):n(c(e),r,e)}))};return u.settings=r,_E.bind(window,"ready",e),new _r(function(t){n?t(n):f=function(e){t(e)}})},get:function(t){return 0===arguments.length?PE.slice(0):q(t)?K(PE,function(e){return e.id===t}).getOr(null):D(t)&&PE[t]?PE[t]:null},add:function(e){var n=this;return BE[e.id]===e||(null===n.get(e.id)&&("length"!==e.id&&(BE[e.id]=e),BE.push(e),PE.push(e)),IE(!0),n.activeEditor=e,n.fire("AddEditor",{editor:e}),kE||(kE=function(e){var t=n.fire("BeforeUnload");if(t.returnValue)return e.preventDefault(),e.returnValue=t.returnValue,t.returnValue},window.addEventListener("beforeunload",kE))),e},createEditor:function(e,t){return this.add(new NE(e,t,this))},remove:function(e){var t,n,r=this;if(e){if(!q(e))return n=e,w(r.get(n.id))?null:(ME(n)&&r.fire("RemoveEditor",{editor:n}),0===PE.length&&window.removeEventListener("beforeunload",kE),n.remove(),IE(0<PE.length),n);TE(_E.select(e),function(e){(n=r.get(e.id))&&r.remove(n)})}else for(t=PE.length-1;0<=t;t--)r.remove(PE[t])},execCommand:function(e,t,n){var r=this.get(n);switch(e){case"mceAddEditor":return this.get(n)||new NE(n,this.settings,this).render(),!0;case"mceRemoveEditor":return r&&r.remove(),!0;case"mceToggleEditor":return r?(r.isHidden()?r.show():r.hide(),!0):(this.execCommand("mceAddEditor",0,n),!0)}return!!this.activeEditor&&this.activeEditor.execCommand(e,t,n)},triggerSave:function(){TE(PE,function(e){e.save()})},addI18n:function(e,t){Au.add(e,t)},translate:function(e){return Au.translate(e)},setActive:function(e){var t=this.activeEditor;this.activeEditor!==e&&(t&&t.fire("deactivate",{relatedTarget:e}),e.fire("activate",{relatedTarget:t})),this.activeEditor=e},_setBaseUrl:function(e){this.baseURL=new vE(this.documentBaseURL).toAbsolute(e.replace(/\/+$/,"")),this.baseURI=new vE(this.baseURL)}});UE.setup();var zE,jE,HE,VE,qE=Math.min,$E=Math.max,WE=Math.round,KE=function(e,t,n){var r=t.x,o=t.y,i=e.w,a=e.h,u=t.w,s=t.h,c=(n||"").split("");return"b"===c[0]&&(o+=s),"r"===c[1]&&(r+=u),"c"===c[0]&&(o+=WE(s/2)),"c"===c[1]&&(r+=WE(u/2)),"b"===c[3]&&(o-=a),"r"===c[4]&&(r-=i),"c"===c[3]&&(o-=WE(a/2)),"c"===c[4]&&(r-=WE(i/2)),XE(r,o,i,a)},XE=function(e,t,n,r){return{x:e,y:t,w:n,h:r}},YE={inflate:function(e,t,n){return XE(e.x-t,e.y-n,e.w+2*t,e.h+2*n)},relativePosition:KE,findBestRelativePosition:function(e,t,n,r){for(var o,i=0;i<r.length;i++)if((o=KE(e,t,r[i])).x>=n.x&&o.x+o.w<=n.w+n.x&&o.y>=n.y&&o.y+o.h<=n.h+n.y)return r[i];return null},intersect:function(e,t){var n=$E(e.x,t.x),r=$E(e.y,t.y),o=qE(e.x+e.w,t.x+t.w),i=qE(e.y+e.h,t.y+t.h);return o-n<0||i-r<0?null:XE(n,r,o-n,i-r)},clamp:function(e,t,n){var r=e.x,o=e.y,i=e.x+e.w,a=e.y+e.h,u=t.x+t.w,s=t.y+t.h,c=$E(0,t.x-r),l=$E(0,t.y-o),f=$E(0,i-u),d=$E(0,a-s);return r+=c,o+=l,n&&(i+=c,a+=l,r-=f,o-=d),XE(r,o,(i-=f)-r,(a-=d)-o)},create:XE,fromClientRect:function(e){return XE(e.left,e.top,e.width,e.height)}},GE=(zE={},jE={},{load:function(r,o){var i='Script at URL "'+o+'" failed to load',a='Script at URL "'+o+"\" did not call `tinymce.Resource.add('"+r+"', data)` within 1 second";if(zE[r]!==undefined)return zE[r];var e=new _r(function(e,t){var n=function(e,t,n){void 0===n&&(n=1e3);var r=!1,o=null,i=function(n){return function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];r||(r=!0,null!==o&&(clearTimeout(o),o=null),n.apply(null,e))}},a=i(e),u=i(t);return{start:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];r||null!==o||(o=setTimeout(function(){return u.apply(null,e)},n))},resolve:a,reject:u}}(e,t);jE[r]=n.resolve,Su.ScriptLoader.loadScript(o,function(){return n.start(a)},function(){return n.reject(i)})});return zE[r]=e},add:function(e,t){jE[e]!==undefined&&(jE[e](t),delete jE[e]),zE[e]=_r.resolve(t)}}),JE=xt.each,QE=xt.extend,ZE=function(){};ZE.extend=HE=function(n){var o=this.prototype,r=function(){var e,t,n;if(!VE&&(this.init&&this.init.apply(this,arguments),t=this.Mixins))for(e=t.length;e--;)(n=t[e]).init&&n.init.apply(this,arguments)},t=function(){return this};VE=!0;var i=new this;return VE=!1,n.Mixins&&(JE(n.Mixins,function(e){for(var t in e)"init"!==t&&(n[t]=e[t])}),o.Mixins&&(n.Mixins=o.Mixins.concat(n.Mixins))),n.Methods&&JE(n.Methods.split(","),function(e){n[e]=t}),n.Properties&&JE(n.Properties.split(","),function(e){var t="_"+e;n[e]=function(e){return e!==undefined?(this[t]=e,this):this[t]}}),n.Statics&&JE(n.Statics,function(e,t){r[t]=e}),n.Defaults&&o.Defaults&&(n.Defaults=QE({},o.Defaults,n.Defaults)),oe(n,function(e,t){var n,r;"function"==typeof e&&o[t]?i[t]=(n=t,r=e,function(){var e=this._super;this._super=o[n];var t=r.apply(this,arguments);return this._super=e,t}):i[t]=e}),r.prototype=i,(r.constructor=r).extend=HE,r};var ek=Math.min,tk=Math.max,nk=Math.round,rk={serialize:function(e){var t=JSON.stringify(e);return q(t)?t.replace(/[\u0080-\uFFFF]/g,function(e){var t=e.charCodeAt(0).toString(16);return"\\u"+"0000".substring(t.length)+t}):t},parse:function(e){try{return JSON.parse(e)}catch(t){}}},ok={callbacks:{},count:0,send:function(t){var n=this,r=bu.DOM,o=t.count!==undefined?t.count:n.count,i="tinymce_jsonp_"+o;n.callbacks[o]=function(e){r.remove(i),delete n.callbacks[o],t.callback(e)},r.add(r.doc.body,"script",{id:i,src:t.url,type:"text/javascript"}),n.count++}},ik=xe(xe({},JN),{send:function(e){var t,n=0,r=function(){!e.async||4===t.readyState||1e4<n++?(e.success&&n<1e4&&200===t.status?e.success.call(e.success_scope,""+t.responseText,t,e):e.error&&e.error.call(e.error_scope,1e4<n?"TIMED_OUT":"GENERAL",t,e),t=null):Fr.setTimeout(r,10)};if(e.scope=e.scope||this,e.success_scope=e.success_scope||e.scope,e.error_scope=e.error_scope||e.scope,e.async=!1!==e.async,e.data=e.data||"",ik.fire("beforeInitialize",{settings:e}),(t=new XMLHttpRequest).overrideMimeType&&t.overrideMimeType(e.content_type),t.open(e.type||(e.data?"POST":"GET"),e.url,e.async),e.crossDomain&&(t.withCredentials=!0),e.content_type&&t.setRequestHeader("Content-Type",e.content_type),e.requestheaders&&xt.each(e.requestheaders,function(e){t.setRequestHeader(e.key,e.value)}),t.setRequestHeader("X-Requested-With","XMLHttpRequest"),(t=ik.fire("beforeSend",{xhr:t,settings:e}).xhr).send(e.data),!e.async)return r();Fr.setTimeout(r,10)}}),ak=xt.extend,uk=(sk.sendRPC=function(e){return(new sk).send(e)},sk.prototype.send=function(e){var n=e.error,r=e.success,o=ak(this.settings,e);o.success=function(e,t){void 0===(e=rk.parse(e))&&(e={error:"JSON Parse error."}),e.error?n.call(o.error_scope||o.scope,e.error,t):r.call(o.success_scope||o.scope,e.result)},o.error=function(e,t){n&&n.call(o.error_scope||o.scope,e,t)},o.data=rk.serialize({id:e.id||"c"+this.count++,method:e.method,params:e.params}),o.content_type="application/json",ik.send(o)},sk);function sk(e){this.settings=ak({},e),this.count=0}try{var ck,lk="__storage_test__";(ck=window.localStorage).setItem(lk,lk),ck.removeItem(lk)}catch(pk){ck=function(){return n={},r=[],e={getItem:function(e){var t=n[e];return t||null},setItem:function(e,t){r.push(e),n[e]=String(t)},key:function(e){return r[e]},removeItem:function(t){r=r.filter(function(e){return e===t}),delete n[t]},clear:function(){r=[],n={}},length:0},Object.defineProperty(e,"length",{get:function(){return r.length},configurable:!1,enumerable:!1}),e;var n,r,e}()}var fk,dk={geom:{Rect:YE},util:{Promise:_r,Delay:Fr,Tools:xt,VK:Gf,URI:vE,Class:ZE,EventDispatcher:KN,Observable:JN,I18n:Au,XHR:ik,JSON:rk,JSONRequest:uk,JSONP:ok,LocalStorage:ck,Color:function(e){var n={},u=0,s=0,c=0,t=function(e){var t;return"object"==typeof e?"r"in e?(u=e.r,s=e.g,c=e.b):"v"in e&&function(e,t,n){if(e=(parseInt(e,10)||0)%360,t=parseInt(t,10)/100,n=parseInt(n,10)/100,t=tk(0,ek(t,1)),n=tk(0,ek(n,1)),0!==t){var r=e/60,o=n*t,i=o*(1-Math.abs(r%2-1)),a=n-o;switch(Math.floor(r)){case 0:u=o,s=i,c=0;break;case 1:u=i,s=o,c=0;break;case 2:u=0,s=o,c=i;break;case 3:u=0,s=i,c=o;break;case 4:u=i,s=0,c=o;break;case 5:u=o,s=0,c=i;break;default:u=s=c=0}u=nk(255*(u+a)),s=nk(255*(s+a)),c=nk(255*(c+a))}else u=s=c=nk(255*n)}(e.h,e.s,e.v):(t=/rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)[^\)]*\)/gi.exec(e))?(u=parseInt(t[1],10),s=parseInt(t[2],10),c=parseInt(t[3],10)):(t=/#([0-F]{2})([0-F]{2})([0-F]{2})/gi.exec(e))?(u=parseInt(t[1],16),s=parseInt(t[2],16),c=parseInt(t[3],16)):(t=/#([0-F])([0-F])([0-F])/gi.exec(e))&&(u=parseInt(t[1]+t[1],16),s=parseInt(t[2]+t[2],16),c=parseInt(t[3]+t[3],16)),u=u<0?0:255<u?255:u,s=s<0?0:255<s?255:s,c=c<0?0:255<c?255:c,n};return e&&t(e),n.toRgb=function(){return{r:u,g:s,b:c}},n.toHsv=function(){return e=u,t=s,n=c,o=0,i=ek(e/=255,ek(t/=255,n/=255)),a=tk(e,tk(t,n)),i===a?{h:0,s:0,v:100*(o=i)}:(r=(a-i)/a,{h:nk(60*((e===i?3:n===i?1:5)-(e===i?t-n:n===i?e-t:n-e)/((o=a)-i))),s:nk(100*r),v:nk(100*o)});var e,t,n,r,o,i,a},n.toHex=function(){var e=function(e){return 1<(e=parseInt(e,10).toString(16)).length?e:"0"+e};return"#"+e(u)+e(s)+e(c)},n.parse=t,n}},dom:{EventUtils:Ni,Sizzle:Na,DomQuery:lu,TreeWalker:Hr,TextSeeker:is,DOMUtils:bu,ScriptLoader:Su,RangeUtils:fd,Serializer:oy,StyleSheetLoader:Ur,ControlSelection:Qf,BookmarkManager:Kf,Selection:Ov,Event:Ni.Event},html:{Styles:hi,Entities:ri,Node:Em,Schema:pi,SaxParser:Lm,DomParser:Zv,Writer:Rm,Serializer:Tm},Env:vt,AddOnManager:Bu,Annotator:qf,Formatter:cb,UndoManager:fb,EditorCommands:MN,WindowManager:zy,NotificationManager:My,EditorObservable:nE,Shortcuts:lE,Editor:NE,FocusManager:nm,EditorManager:UE,DOM:bu.DOM,ScriptLoader:Su.ScriptLoader,PluginManager:Fy,ThemeManager:Uy,IconManager:Ry,Resource:GE,trim:xt.trim,isArray:xt.isArray,is:xt.is,toArray:xt.toArray,makeMap:xt.makeMap,each:xt.each,map:xt.map,grep:xt.grep,inArray:xt.inArray,extend:xt.extend,create:xt.create,walk:xt.walk,createNS:xt.createNS,resolve:xt.resolve,explode:xt.explode,_addCacheSuffix:xt._addCacheSuffix,isOpera:vt.opera,isWebKit:vt.webkit,isIE:vt.ie,isGecko:vt.gecko,isMac:vt.mac},mk=xt.extend(UE,dk);fk=mk,window.tinymce=fk,window.tinyMCE=fk,function(e){if("object"==typeof module)try{module.exports=e}catch(t){}}(mk)}();;
/*!
 * MockJax - jQuery Plugin to Mock Ajax requests
 *
 * Version:  1.5.0pre
 * Released:
 * Home:   http://github.com/appendto/jquery-mockjax
 * Author:   Jonathan Sharp (http://jdsharp.com)
 * License:  MIT,GPL
 *
 * Copyright (c) 2011 appendTo LLC.
 * Dual licensed under the MIT or GPL licenses.
 * http://appendto.com/open-source-licenses
 */
(function ($) {
    var _ajax = $.ajax,
        mockHandlers = [],
        CALLBACK_REGEX = /=\?(&|$)/,
        jsc = (new Date()).getTime();


    // Parse the given XML string. 
    function parseXML(xml) {
        if (window['DOMParser'] == undefined && window.ActiveXObject) {
            DOMParser = function () { };
            DOMParser.prototype.parseFromString = function (xmlString) {
                var doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = 'false';
                doc.loadXML(xmlString);
                return doc;
            };
        }

        try {
            var xmlDoc = (new DOMParser()).parseFromString(xml, 'text/xml');
            if ($.isXMLDoc(xmlDoc)) {
                var err = $('parsererror', xmlDoc);
                if (err.length == 1) {
                    throw ('Error: ' + $(xmlDoc).text());
                }
            } else {
                throw ('Unable to parse XML');
            }
        } catch (e) {
            var msg = (e.name == undefined ? e : e.name + ': ' + e.message);
            $(document).trigger('xmlParseError', [msg]);
            return undefined;
        }
        return xmlDoc;
    }

    // Trigger a jQuery event
    function trigger(s, type, args) {
        (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args);
    }

    // Check if the data field on the mock handler and the request match. This 
    // can be used to restrict a mock handler to being used only when a certain
    // set of data is passed to it.
    function isMockDataEqual(mock, live) {
        var identical = false;
        // Test for situations where the data is a querystring (not an object)
        if (typeof live === 'string') {
            // Querystring may be a regex
            return $.isFunction(mock.test) ? mock.test(live) : mock == live;
        }
        $.each(mock, function (k, v) {
            if (live[k] === undefined) {
                identical = false;
                return identical;
            } else {
                identical = true;
                if (typeof live[k] == 'object') {
                    return isMockDataEqual(mock[k], live[k]);
                } else {
                    if ($.isFunction(mock[k].test)) {
                        identical = mock[k].test(live[k]);
                    } else {
                        identical = (mock[k] == live[k]);
                    }
                    return identical;
                }
            }
        });

        return identical;
    }

    // Check the given handler should mock the given request
    function getMockForRequest(handler, requestSettings) {
        // If the mock was registered with a function, let the function decide if we
        // want to mock this request
        if ($.isFunction(handler)) {
            return handler(requestSettings);
        }

        // Inspect the URL of the request and check if the mock handler's url
        // matches the url for this ajax request
        if ($.isFunction(handler.url.test)) {
            // The user provided a regex for the url, test it
            if (!handler.url.test(requestSettings.url)) {
                return null;
            }
        } else {
            // Look for a simple wildcard '*' or a direct URL match
            var star = handler.url.indexOf('*');
            if (handler.url !== requestSettings.url && star === -1 ||
                !new RegExp(handler.url.replace(/[-[\]{}()+?.,\\^$|#\s]/g, "\\$&").replace('*', '.+')).test(requestSettings.url)) {
                return null;
            }
        }

        // Inspect the data submitted in the request (either POST body or GET query string)
        if (handler.data && requestSettings.data) {
            if (!isMockDataEqual(handler.data, requestSettings.data)) {
                // They're not identical, do not mock this request
                return null;
            }
        }
        // Inspect the request type
        if (handler && handler.type &&
            handler.type.toLowerCase() != requestSettings.type.toLowerCase()) {
            // The request type doesn't match (GET vs. POST)
            return null;
        }

        return handler;
    }

    // If logging is enabled, log the mock to the console
    function logMock(mockHandler, requestSettings) {
        var c = $.extend({}, $.mockjaxSettings, mockHandler);
        if (c.log && $.isFunction(c.log)) {
            c.log('MOCK ' + requestSettings.type.toUpperCase() + ': ' + requestSettings.url, $.extend({}, requestSettings));
        }
    }

    // Process the xhr objects send operation
    function _xhrSend(mockHandler, requestSettings, origSettings) {

        // This is a substitute for < 1.4 which lacks $.proxy
        var process = (function (that) {
            return function () {
                return (function () {
                    // The request has returned
                    this.status = mockHandler.status;
                    this.statusText = mockHandler.statusText;
                    this.readyState = 4;

                    // We have an executable function, call it to give
                    // the mock handler a chance to update it's data
                    if ($.isFunction(mockHandler.response)) {
                        mockHandler.response(origSettings);
                    }
                    // Copy over our mock to our xhr object before passing control back to
                    // jQuery's onreadystatechange callback
                    if (requestSettings.dataType == 'json' && (typeof mockHandler.responseText == 'object')) {
                        this.responseText = JSON.stringify(mockHandler.responseText);
                    } else if (requestSettings.dataType == 'xml') {
                        if (typeof mockHandler.responseXML == 'string') {
                            this.responseXML = parseXML(mockHandler.responseXML);
                        } else {
                            this.responseXML = mockHandler.responseXML;
                        }
                    } else {
                        this.responseText = mockHandler.responseText;
                    }
                    if (typeof mockHandler.status == 'number' || typeof mockHandler.status == 'string') {
                        this.status = mockHandler.status;
                    }
                    if (typeof mockHandler.statusText === "string") {
                        this.statusText = mockHandler.statusText;
                    }
                    // jQuery < 1.4 doesn't have onreadystate change for xhr
                    if ($.isFunction(this.onreadystatechange)) {
                        if (mockHandler.isTimeout) {
                            this.status = -1;
                        }
                        this.onreadystatechange(mockHandler.isTimeout ? 'timeout' : undefined);
                    } else if (mockHandler.isTimeout) {
                        // Fix for 1.3.2 timeout to keep success from firing.
                        this.status = -1;
                    }
                }).apply(that);
            };
        })(this);

        if (mockHandler.proxy) {
            // We're proxying this request and loading in an external file instead
            _ajax({
                global: false,
                url: mockHandler.proxy,
                type: mockHandler.proxyType,
                data: mockHandler.data,
                dataType: requestSettings.dataType === "script" ? "text/plain" : requestSettings.dataType,
                complete: function (xhr, txt) {
                    mockHandler.responseXML = xhr.responseXML;
                    mockHandler.responseText = xhr.responseText;
                    mockHandler.status = xhr.status;
                    mockHandler.statusText = xhr.statusText;
                    this.responseTimer = setTimeout(process, mockHandler.responseTime || 0);
                }
            });
        } else {
            // type == 'POST' || 'GET' || 'DELETE'
            if (requestSettings.async === false) {
                // TODO: Blocking delay
                process();
            } else {
                this.responseTimer = setTimeout(process, mockHandler.responseTime || 50);
            }
        }
    }

    // Construct a mocked XHR Object
    function xhr(mockHandler, requestSettings, origSettings, origHandler) {
        // Extend with our default mockjax settings
        mockHandler = $.extend({}, $.mockjaxSettings, mockHandler);

        if (typeof mockHandler.headers === 'undefined') {
            mockHandler.headers = {};
        }
        if (mockHandler.contentType) {
            mockHandler.headers['content-type'] = mockHandler.contentType;
        }

        return {
            status: mockHandler.status,
            statusText: mockHandler.statusText,
            readyState: 1,
            open: function () { },
            send: function () {
                origHandler.fired = true;
                _xhrSend.call(this, mockHandler, requestSettings, origSettings);
            },
            abort: function () {
                clearTimeout(this.responseTimer);
            },
            setRequestHeader: function (header, value) {
                mockHandler.headers[header] = value;
            },
            getResponseHeader: function (header) {
                // 'Last-modified', 'Etag', 'content-type' are all checked by jQuery
                if (mockHandler.headers && mockHandler.headers[header]) {
                    // Return arbitrary headers
                    return mockHandler.headers[header];
                } else if (header.toLowerCase() == 'last-modified') {
                    return mockHandler.lastModified || (new Date()).toString();
                } else if (header.toLowerCase() == 'etag') {
                    return mockHandler.etag || '';
                } else if (header.toLowerCase() == 'content-type') {
                    return mockHandler.contentType || 'text/plain';
                }
            },
            getAllResponseHeaders: function () {
                var headers = '';
                $.each(mockHandler.headers, function (k, v) {
                    headers += k + ': ' + v + "\n";
                });
                return headers;
            }
        };
    }

    // Process a JSONP mock request.
    function processJsonpMock(requestSettings, mockHandler, origSettings) {
        // Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here
        // because there isn't an easy hook for the cross domain script tag of jsonp

        processJsonpUrl(requestSettings);

        requestSettings.dataType = "json";
        if (requestSettings.data && CALLBACK_REGEX.test(requestSettings.data) || CALLBACK_REGEX.test(requestSettings.url)) {
            createJsonpCallback(requestSettings, mockHandler);

            // We need to make sure
            // that a JSONP style response is executed properly

            var rurl = /^(\w+:)?\/\/([^\/?#]+)/,
                parts = rurl.exec(requestSettings.url),
                remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);

            requestSettings.dataType = "script";
            if (requestSettings.type.toUpperCase() === "GET" && remote) {
                var newMockReturn = processJsonpRequest(requestSettings, mockHandler, origSettings);

                // Check if we are supposed to return a Deferred back to the mock call, or just 
                // signal success
                if (newMockReturn) {
                    return newMockReturn;
                } else {
                    return true;
                }
            }
        }
        return null;
    }

    // Append the required callback parameter to the end of the request URL, for a JSONP request
    function processJsonpUrl(requestSettings) {
        if (requestSettings.type.toUpperCase() === "GET") {
            if (!CALLBACK_REGEX.test(requestSettings.url)) {
                requestSettings.url += (/\?/.test(requestSettings.url) ? "&" : "?") +
                    (requestSettings.jsonp || "callback") + "=?";
            }
        } else if (!requestSettings.data || !CALLBACK_REGEX.test(requestSettings.data)) {
            requestSettings.data = (requestSettings.data ? requestSettings.data + "&" : "") + (requestSettings.jsonp || "callback") + "=?";
        }
    }

    // Process a JSONP request by evaluating the mocked response text
    function processJsonpRequest(requestSettings, mockHandler, origSettings) {
        // Synthesize the mock request for adding a script tag
        var callbackContext = origSettings && origSettings.context || requestSettings,
            newMock = null;


        // If the response handler on the moock is a function, call it
        if (mockHandler.response && $.isFunction(mockHandler.response)) {
            mockHandler.response(origSettings);
        } else {

            // Evaluate the responseText javascript in a global context
            if (typeof mockHandler.responseText === 'object') {
                $.globalEval('(' + JSON.stringify(mockHandler.responseText) + ')');
            } else {
                $.globalEval('(' + mockHandler.responseText + ')');
            }
        }

        // Successful response
        jsonpSuccess(requestSettings, mockHandler);
        jsonpComplete(requestSettings, mockHandler);

        // If we are running under jQuery 1.5+, return a deferred object
        if (jQuery.Deferred) {
            newMock = new jQuery.Deferred();
            if (typeof mockHandler.responseText == "object") {
                newMock.resolve(mockHandler.responseText);
            }
            else {
                newMock.resolve(jQuery.parseJSON(mockHandler.responseText));
            }
        }
        return newMock;
    }


    // Create the required JSONP callback function for the request
    function createJsonpCallback(requestSettings, mockHandler) {
        jsonp = requestSettings.jsonpCallback || ("jsonp" + jsc++);

        // Replace the =? sequence both in the query string and the data
        if (requestSettings.data) {
            requestSettings.data = (requestSettings.data + "").replace(CALLBACK_REGEX, "=" + jsonp + "$1");
        }

        requestSettings.url = requestSettings.url.replace(CALLBACK_REGEX, "=" + jsonp + "$1");


        // Handle JSONP-style loading
        window[jsonp] = window[jsonp] || function (tmp) {
            data = tmp;
            jsonpSuccess(requestSettings, mockHandler);
            jsonpComplete(requestSettings, mockHandler);
            // Garbage collect
            window[jsonp] = undefined;

            try {
                delete window[jsonp];
            } catch (e) { }

            if (head) {
                head.removeChild(script);
            }
        };
    }

    // The JSONP request was successful
    function jsonpSuccess(requestSettings, mockHandler) {
        // If a local callback was specified, fire it and pass it the data
        if (requestSettings.success) {
            requestSettings.success.call(callbackContext, (mockHandler.response ? mockHandler.response.toString() : mockHandler.responseText || ''), status, {});
        }

        // Fire the global callback
        if (requestSettings.global) {
            trigger(requestSettings, "ajaxSuccess", [{}, requestSettings]);
        }
    }

    // The JSONP request was completed
    function jsonpComplete(requestSettings, mockHandler) {
        // Process result
        if (requestSettings.complete) {
            requestSettings.complete.call(callbackContext, {}, status);
        }

        // The request was completed
        if (requestSettings.global) {
            trigger("ajaxComplete", [{}, requestSettings]);
        }

        // Handle the global AJAX counter
        if (requestSettings.global && ! --jQuery.active) {
            jQuery.event.trigger("ajaxStop");
        }
    }


    // The core $.ajax replacement.  
    function handleAjax(url, origSettings) {
        var mockRequest, requestSettings, mockHandler;

        // If url is an object, simulate pre-1.5 signature
        if (typeof url === "object") {
            origSettings = url;
            url = undefined;
        } else {
            // work around to support 1.5 signature
            origSettings.url = url;
        }

        // Extend the original settings for the request
        requestSettings = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings);

        // Iterate over our mock handlers (in registration order) until we find
        // one that is willing to intercept the request
        for (var k = 0; k < mockHandlers.length; k++) {
            if (!mockHandlers[k]) {
                continue;
            }

            mockHandler = getMockForRequest(mockHandlers[k], requestSettings);
            if (!mockHandler) {
                // No valid mock found for this request
                continue;
            }

            // Handle console logging
            logMock(mockHandler, requestSettings);


            if (requestSettings.dataType === "jsonp") {
                if ((mockRequest = processJsonpMock(requestSettings, mockHandler, origSettings))) {
                    // This mock will handle the JSONP request
                    return mockRequest;
                }
            }


            // Removed to fix #54 - keep the mocking data object intact
            //mockHandler.data = requestSettings.data;

            mockHandler.cache = requestSettings.cache;
            mockHandler.timeout = requestSettings.timeout;
            mockHandler.global = requestSettings.global;

            (function (mockHandler, requestSettings, origSettings, origHandler) {
                mockRequest = _ajax.call($, $.extend(true, {}, origSettings, {
                    // Mock the XHR object
                    xhr: function () { return xhr(mockHandler, requestSettings, origSettings, origHandler) }
                }));
            })(mockHandler, requestSettings, origSettings, mockHandlers[k]);

            return mockRequest;
        }

        // We don't have a mock request, trigger a normal request
        return _ajax.apply($, [origSettings]);
    }


    // Public

    $.extend({
        ajax: handleAjax
    });

    $.mockjaxSettings = {
        //url:        null,
        //type:       'GET',
        log: function (msg) {
            window['console'] && window.console.log && window.console.log(msg);
        },
        status: 200,
        statusText: "OK",
        responseTime: 500,
        isTimeout: false,
        contentType: 'text/plain',
        response: '',
        responseText: '',
        responseXML: '',
        proxy: '',
        proxyType: 'GET',

        lastModified: null,
        etag: '',
        headers: {
            etag: 'IJF@H#@923uf8023hFO@I#H#',
            'content-type': 'text/plain'
        }
    };

    $.mockjax = function (settings) {
        var i = mockHandlers.length;
        mockHandlers[i] = settings;
        return i;
    };
    $.mockjaxClear = function (i) {
        if (arguments.length == 1) {
            mockHandlers[i] = null;
        } else {
            mockHandlers = [];
        }
    };
    $.mockjax.handler = function (i) {
        if (arguments.length == 1) {
            return mockHandlers[i];
        }
    };
})(jQuery);;
/*! X-editable - v1.5.1 
* In-place editing with Twitter Bootstrap, jQuery UI or pure jQuery
* http://github.com/vitalets/x-editable
* Copyright (c) 2013 Vitaliy Potapov; Licensed MIT */
/**
Form with single input element, two buttons and two states: normal/loading.
Applied as jQuery method to DIV tag (not to form tag!). This is because form can be in loading state when spinner shown.
Editableform is linked with one of input types, e.g. 'text', 'select' etc.

@class editableform
@uses text
@uses textarea
**/
(function ($) {
    "use strict";

    var EditableForm = function (div, options) {
        this.options = $.extend({}, $.fn.editableform.defaults, options);
        this.$div = $(div); //div, containing form. Not form tag. Not editable-element.
        if (!this.options.scope) {
            this.options.scope = this;
        }
        //nothing shown after init
    };

    EditableForm.prototype = {
        constructor: EditableForm,
        initInput: function () {  //called once
            //take input from options (as it is created in editable-element)
            this.input = this.options.input;

            //set initial value
            //todo: may be add check: typeof str === 'string' ? 
            this.value = this.input.str2value(this.options.value);

            //prerender: get input.$input
            this.input.prerender();
        },
        initTemplate: function () {
            this.$form = $($.fn.editableform.template);
        },
        initButtons: function () {
            var $btn = this.$form.find('.editable-buttons');
            $btn.append($.fn.editableform.buttons);
            if (this.options.showbuttons === 'bottom') {
                $btn.addClass('editable-buttons-bottom');
            }
        },
      
        render: function () {
            //init loader
            this.$loading = $($.fn.editableform.loading);
            this.$div.empty().append(this.$loading);

            //init form template and buttons
            this.initTemplate();
            if (this.options.showbuttons) {
                this.initButtons();
            } else {
                this.$form.find('.editable-buttons').remove();
            }

            //show loading state
            this.showLoading();

            //flag showing is form now saving value to server. 
            //It is needed to wait when closing form.
            this.isSaving = false;

            /**        
            Fired when rendering starts
            @event rendering 
            @param {Object} event event object
            **/
            this.$div.triggerHandler('rendering');

            //init input
            this.initInput();

            //append input to form
            this.$form.find('div.editable-input').append(this.input.$tpl);

            //append form to container
            this.$div.append(this.$form);

            //render input
            $.when(this.input.render())
                .then($.proxy(function () {
                    //setup input to submit automatically when no buttons shown
                    if (!this.options.showbuttons) {
                        this.input.autosubmit();
                    }

                    //attach 'cancel' handler
                    this.$form.find('.editable-cancel').click($.proxy(this.cancel, this));

                    if (this.input.error) {
                        this.error(this.input.error);
                        this.$form.find('.editable-submit').attr('disabled', true);
                        this.input.$input.attr('disabled', true);
                        //prevent form from submitting
                        this.$form.submit(function (e) { e.preventDefault(); });
                    } else {
                        this.error(false);
                        this.input.$input.removeAttr('disabled');
                        this.$form.find('.editable-submit').removeAttr('disabled');
                        var value = (this.value === null || this.value === undefined || this.value === '') ? this.options.defaultValue : this.value;
                        this.input.value2input(value);
                        //attach submit handler
                        this.$form.submit($.proxy(this.submit, this));
                    }

                    /**        
                    Fired when form is rendered
                    @event rendered
                    @param {Object} event event object
                    **/
                    this.$div.triggerHandler('rendered');

                    this.showForm();

                    //call postrender method to perform actions required visibility of form
                    if (this.input.postrender) {
                        this.input.postrender();
                    }
                }, this));
        },
        cancel: function () {
            /**        
            Fired when form was cancelled by user
            @event cancel 
            @param {Object} event event object
            **/
            this.$div.triggerHandler('cancel');
        },
        showLoading: function () {
            var w, h;
            if (this.$form) {
                //set loading size equal to form
                w = this.$form.outerWidth();
                h = this.$form.outerHeight();
                if (w) {
                    this.$loading.width(w);
                }
                if (h) {
                    this.$loading.height(h);
                }
                this.$form.hide();
            } else {
                //stretch loading to fill container width
                w = this.$loading.parent().width();
                if (w) {
                    this.$loading.width(w);
                }
            }
            this.$loading.show();
        },

        showForm: function (activate) {
            this.$loading.hide();
            this.$form.show();
            if (activate !== false) {
                this.input.activate();
            }
            /**        
            Fired when form is shown
            @event show 
            @param {Object} event event object
            **/
            this.$div.triggerHandler('show');
        },

        error: function (msg) {
            var $group = this.$form.find('.control-group'),
                $block = this.$form.find('.editable-error-block'),
                lines;

            if (msg === false) {
                $group.removeClass($.fn.editableform.errorGroupClass);
                $block.removeClass($.fn.editableform.errorBlockClass).empty().hide();
            } else {
                //convert newline to <br> for more pretty error display
                if (msg) {
                    lines = ('' + msg).split('\n');
                    for (var i = 0; i < lines.length; i++) {
                        lines[i] = $('<div>').text(lines[i]).html();
                    }
                    msg = lines.join('<br>');
                }
                $group.addClass($.fn.editableform.errorGroupClass);
                $block.addClass($.fn.editableform.errorBlockClass).html(msg).show();
            }
        },

        submit: function (e) {
            e.stopPropagation();
            e.preventDefault();

            //get new value from input
            var newValue = this.input.input2value();

            //validation: if validate returns string or truthy value - means error
            //if returns object like {newValue: '...'} => submitted value is reassigned to it
            var error = this.validate(newValue);
            if ($.type(error) === 'object' && error.newValue !== undefined) {
                newValue = error.newValue;
                this.input.value2input(newValue);
                if (typeof error.msg === 'string') {
                    this.error(error.msg);
                    this.showForm();
                    return;
                }
            } else if (error) {
                this.error(error);
                this.showForm();
                return;
            }

            //if value not changed --> trigger 'nochange' event and return
            /*jslint eqeq: true*/
            if (!this.options.savenochange && this.input.value2str(newValue) == this.input.value2str(this.value)) {
                /*jslint eqeq: false*/
                /**        
                Fired when value not changed but form is submitted. Requires savenochange = false.
                @event nochange 
                @param {Object} event event object
                **/
                this.$div.triggerHandler('nochange');
                return;
            }

            //convert value for submitting to server
            var submitValue = this.input.value2submit(newValue);

            this.isSaving = true;

            //sending data to server
            $.when(this.save(submitValue))
                .done($.proxy(function (response) {
                    this.isSaving = false;

                    //run success callback
                    var res = typeof this.options.success === 'function' ? this.options.success.call(this.options.scope, response, newValue) : null;

                    //if success callback returns false --> keep form open and do not activate input
                    if (res === false) {
                        this.error(false);
                        this.showForm(false);
                        return;
                    }

                    //if success callback returns string -->  keep form open, show error and activate input               
                    if (typeof res === 'string') {
                        this.error(res);
                        this.showForm();
                        return;
                    }

                    //if success callback returns object like {newValue: <something>} --> use that value instead of submitted
                    //it is usefull if you want to chnage value in url-function
                    if (res && typeof res === 'object' && res.hasOwnProperty('newValue')) {
                        newValue = res.newValue;
                    }

                    //clear error message
                    this.error(false);
                    this.value = newValue;
                    /**        
                    Fired when form is submitted
                    @event save 
                    @param {Object} event event object
                    @param {Object} params additional params
                    @param {mixed} params.newValue raw new value
                    @param {mixed} params.submitValue submitted value as string
                    @param {Object} params.response ajax response
    
                    @example
                    $('#form-div').on('save'), function(e, params){
                        if(params.newValue === 'username') {...}
                    });
                    **/
                    this.$div.triggerHandler('save', { newValue: newValue, submitValue: submitValue, response: response });
                }, this))
                .fail($.proxy(function (xhr) {
                    this.isSaving = false;

                    var msg;
                    if (typeof this.options.error === 'function') {
                        msg = this.options.error.call(this.options.scope, xhr, newValue);
                    } else {
                        msg = typeof xhr === 'string' ? xhr : xhr.responseText || xhr.statusText || 'Unknown error!';
                    }

                    this.error(msg);
                    this.showForm();
                }, this));
        },

  
        save: function (submitValue) {
            //try parse composite pk defined as json string in data-pk 
            this.options.pk = $.fn.editableutils.tryParseJson(this.options.pk, true);

            var pk = (typeof this.options.pk === 'function') ? this.options.pk.call(this.options.scope) : this.options.pk,
                /*
                  send on server in following cases:
                  1. url is function
                  2. url is string AND (pk defined OR send option = always) 
                */
                send = !!(typeof this.options.url === 'function' || (this.options.url && ((this.options.send === 'always') || (this.options.send === 'auto' && pk !== null && pk !== undefined)))),
                params;

            var escapeHtml = function (unsafe) {
                return unsafe
                    .replace(/</g, "&lt;")
                    .replace(/>/g, "&gt;");
            };


            if (send) { //send to server
                this.showLoading();

                //standard params
                params = {
                    name: this.options.name || '',
                    value:  escapeHtml(submitValue),
                    pk: pk
                };

                //additional params
                if (typeof this.options.params === 'function') {
                    params = this.options.params.call(this.options.scope, params);
                } else {
                    //try parse json in single quotes (from data-params attribute)
                    this.options.params = $.fn.editableutils.tryParseJson(this.options.params, true);
                    $.extend(params, this.options.params);
                }

                if (typeof this.options.url === 'function') { //user's function
                    return this.options.url.call(this.options.scope, params);
                } else {
                    //send ajax to server and return deferred object
                    return $.ajax($.extend({
                        url: this.options.url,
                        data: params,
                        type: 'POST'
                    }, this.options.ajaxOptions));
                }
            }
        },

        validate: function (value) {
            if (value === undefined) {
                value = this.value;
            }
            if (typeof this.options.validate === 'function') {
                return this.options.validate.call(this.options.scope, value);
            }
        },

        option: function (key, value) {
            if (key in this.options) {
                this.options[key] = value;
            }

            if (key === 'value') {
                this.setValue(value);
            }

            //do not pass option to input as it is passed in editable-element
        },

        setValue: function (value, convertStr) {
            if (convertStr) {
                this.value = this.input.str2value(value);
            } else {
                this.value = value;
            }

            //if form is visible, update input
            if (this.$form && this.$form.is(':visible')) {
                this.input.value2input(this.value);
            }
        }
    };

    /*
    Initialize editableform. Applied to jQuery object.

    @method $().editableform(options)
    @params {Object} options
    @example
    var $form = $('&lt;div&gt;').editableform({
        type: 'text',
        name: 'username',
        url: '/post',
        value: 'vitaliy'
    });

    //to display form you should call 'render' method
    $form.editableform('render');     
    */
    $.fn.editableform = function (option) {
        var args = arguments;
        return this.each(function () {
            var $this = $(this),
                data = $this.data('editableform'),
                options = typeof option === 'object' && option;
            if (!data) {
                $this.data('editableform', (data = new EditableForm(this, options)));
            }

            if (typeof option === 'string') { //call method 
                data[option].apply(data, Array.prototype.slice.call(args, 1));
            }
        });
    };

    //keep link to constructor to allow inheritance
    $.fn.editableform.Constructor = EditableForm;

    //defaults
    $.fn.editableform.defaults = {
        /* see also defaults for input */

        /**
        Type of input. Can be <code>text|textarea|select|date|checklist</code>

        @property type 
        @type string
        @default 'text'
        **/
        type: 'text',
        /**
        Url for submit, e.g. <code>'/post'</code>  
        If function - it will be called instead of ajax. Function should return deferred object to run fail/done callbacks.

        @property url 
        @type string|function
        @default null
        @example
        url: function(params) {
            var d = new $.Deferred;
            if(params.value === 'abc') {
                return d.reject('error message'); //returning error via deferred object
            } else {
                //async saving data in js model
                someModel.asyncSaveMethod({
                   ..., 
                   success: function(){
                      d.resolve();
                   }
                }); 
                return d.promise();
            }
        } 
        **/
        url: null,
        /**
        Additional params for submit. If defined as <code>object</code> - it is **appended** to original ajax data (pk, name and value).  
        If defined as <code>function</code> - returned object **overwrites** original ajax data.
        @example
        params: function(params) {
            //originally params contain pk, name and value
            params.a = 1;
            return params;
        }

        @property params 
        @type object|function
        @default null
        **/
        params: null,
        /**
        Name of field. Will be submitted on server. Can be taken from <code>id</code> attribute

        @property name 
        @type string
        @default null
        **/
        name: null,
        /**
        Primary key of editable object (e.g. record id in database). For composite keys use object, e.g. <code>{id: 1, lang: 'en'}</code>.
        Can be calculated dynamically via function.

        @property pk 
        @type string|object|function
        @default null
        **/
        pk: null,
        /**
        Initial value. If not defined - will be taken from element's content.
        For __select__ type should be defined (as it is ID of shown text).

        @property value 
        @type string|object
        @default null
        **/
        value: null,
        /**
        Value that will be displayed in input if original field value is empty (`null|undefined|''`).

        @property defaultValue 
        @type string|object
        @default null
        @since 1.4.6
        **/
        defaultValue: null,
        /**
        Strategy for sending data on server. Can be `auto|always|never`.
        When 'auto' data will be sent on server **only if pk and url defined**, otherwise new value will be stored locally.

        @property send 
        @type string
        @default 'auto'
        **/
        send: 'auto',
        /**
        Function for client-side validation. If returns string - means validation not passed and string showed as error.
        Since 1.5.1 you can modify submitted value by returning object from `validate`: 
        `{newValue: '...'}` or `{newValue: '...', msg: '...'}`

        @property validate 
        @type function
        @default null
        @example
        validate: function(value) {
            if($.trim(value) == '') {
                return 'This field is required';
            }
        }
        **/
        validate: null,
        /**
        Success callback. Called when value successfully sent on server and **response status = 200**.  
        Usefull to work with json response. For example, if your backend response can be <code>{success: true}</code>
        or <code>{success: false, msg: "server error"}</code> you can check it inside this callback.  
        If it returns **string** - means error occured and string is shown as error message.  
        If it returns **object like** <code>{newValue: &lt;something&gt;}</code> - it overwrites value, submitted by user.  
        Otherwise newValue simply rendered into element.
        
        @property success 
        @type function
        @default null
        @example
        success: function(response, newValue) {
            if(!response.success) return response.msg;
        }
        **/
        success: null,
        /**
        Error callback. Called when request failed (response status != 200).  
        Usefull when you want to parse error response and display a custom message.
        Must return **string** - the message to be displayed in the error block.
                
        @property error 
        @type function
        @default null
        @since 1.4.4
        @example
        error: function(response, newValue) {
            if(response.status === 500) {
                return 'Service unavailable. Please try later.';
            } else {
                return response.responseText;
            }
        }
        **/
        error: null,
        /**
        Additional options for submit ajax request.
        List of values: http://api.jquery.com/jQuery.ajax
        
        @property ajaxOptions 
        @type object
        @default null
        @since 1.1.1        
        @example 
        ajaxOptions: {
            type: 'put',
            dataType: 'json'
        }        
        **/
        ajaxOptions: null,
        /**
        Where to show buttons: left(true)|bottom|false  
        Form without buttons is auto-submitted.

        @property showbuttons 
        @type boolean|string
        @default true
        @since 1.1.1
        **/
        showbuttons: true,
        /**
        Scope for callback methods (success, validate).  
        If <code>null</code> means editableform instance itself. 

        @property scope 
        @type DOMElement|object
        @default null
        @since 1.2.0
        @private
        **/
        scope: null,

         /**
         Privacy policy type
        
        @property savenochange 
        @type boolean
        @default false
        @since 1.2.0
        **/
        privacytype: null,
        /**
        Whether to save or cancel value when it was not changed but form was submitted

        @property savenochange 
        @type boolean
        @default false
        @since 1.2.0
        **/
        savenochange: false
    };

    /*
    Note: following params could redefined in engine: bootstrap or jqueryui:
    Classes 'control-group' and 'editable-error-block' must always present!
    */
    $.fn.editableform.template = '<form class="form-inline editableform">' +
        '<div class="control-group">' +
        '<div><div class="editable-input"></div><div class="editable-buttons"></div></div>' +
        '<div class="editable-error-block"></div>' +
        '</div>' +
        '</form>';

    //loading div
    $.fn.editableform.loading = '<div class="editableform-loading"></div>';

    //buttons
    $.fn.editableform.buttons = '<button type="submit" class="editable-submit">ok</button>' +
        '<button type="button" class="editable-cancel">cancel</button>';

    //error class attached to control-group
    $.fn.editableform.errorGroupClass = null;

    //error class attached to editable-error-block
    $.fn.editableform.errorBlockClass = 'editable-error';

    //engine
    $.fn.editableform.engine = 'jquery';
}(window.jQuery));

/**
* EditableForm utilites
*/
(function ($) {
    "use strict";

    //utils
    $.fn.editableutils = {
        /**
        * classic JS inheritance function
        */
        inherit: function (Child, Parent) {
            var F = function () { };
            F.prototype = Parent.prototype;
            Child.prototype = new F();
            Child.prototype.constructor = Child;
            Child.superclass = Parent.prototype;
        },

        /**
        * set caret position in input
        * see http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area
        */
        setCursorPosition: function (elem, pos) {
            if (elem.setSelectionRange) {
                elem.setSelectionRange(pos, pos);
            } else if (elem.createTextRange) {
                var range = elem.createTextRange();
                range.collapse(true);
                range.moveEnd('character', pos);
                range.moveStart('character', pos);
                range.select();
            }
        },

        /**
        * function to parse JSON in *single* quotes. (jquery automatically parse only double quotes)
        * That allows such code as: <a data-source="{'a': 'b', 'c': 'd'}">
        * safe = true --> means no exception will be thrown
        * for details see http://stackoverflow.com/questions/7410348/how-to-set-json-format-to-html5-data-attributes-in-the-jquery
        */
        tryParseJson: function (s, safe) {
            if (typeof s === 'string' && s.length && s.match(/^[\{\[].*[\}\]]$/)) {
                if (safe) {
                    try {
                        /*jslint evil: true*/
                        s = (new Function('return ' + s))();
                        /*jslint evil: false*/
                    } catch (e) { } finally {
                        return s;
                    }
                } else {
                    /*jslint evil: true*/
                    s = (new Function('return ' + s))();
                    /*jslint evil: false*/
                }
            }
            return s;
        },

        /**
        * slice object by specified keys
        */
        sliceObj: function (obj, keys, caseSensitive /* default: false */) {
            var key, keyLower, newObj = {};

            if (!$.isArray(keys) || !keys.length) {
                return newObj;
            }

            for (var i = 0; i < keys.length; i++) {
                key = keys[i];
                if (obj.hasOwnProperty(key)) {
                    newObj[key] = obj[key];
                }

                if (caseSensitive === true) {
                    continue;
                }

                //when getting data-* attributes via $.data() it's converted to lowercase.
                //details: http://stackoverflow.com/questions/7602565/using-data-attributes-with-jquery
                //workaround is code below.
                keyLower = key.toLowerCase();
                if (obj.hasOwnProperty(keyLower)) {
                    newObj[key] = obj[keyLower];
                }
            }

            return newObj;
        },

        /*
        exclude complex objects from $.data() before pass to config
        */
        getConfigData: function ($element) {
            var data = {};
            $.each($element.data(), function (k, v) {
                if (typeof v !== 'object' || (v && typeof v === 'object' && (v.constructor === Object || v.constructor === Array))) {
                    data[k] = v;
                }
            });
            return data;
        },

        /*
         returns keys of object
        */
        objectKeys: function (o) {
            if (Object.keys) {
                return Object.keys(o);
            } else {
                if (o !== Object(o)) {
                    throw new TypeError('Object.keys called on a non-object');
                }
                var k = [], p;
                for (p in o) {
                    if (Object.prototype.hasOwnProperty.call(o, p)) {
                        k.push(p);
                    }
                }
                return k;
            }

        },

        /**
         method to escape html.
        **/
        escape: function (str) {
            return $('<div>').text(str).html();
        },

        /*
         returns array items from sourceData having value property equal or inArray of 'value'
        */
        itemsByValue: function (value, sourceData, valueProp) {
            if (!sourceData || value === null) {
                return [];
            }

            if (typeof (valueProp) !== "function") {
                var idKey = valueProp || 'value';
                valueProp = function (e) { return e[idKey]; };
            }

            var isValArray = $.isArray(value),
                result = [],
                that = this;

            $.each(sourceData, function (i, o) {
                if (o.children) {
                    result = result.concat(that.itemsByValue(value, o.children, valueProp));
                } else {
                    /*jslint eqeq: true*/
                    if (isValArray) {
                        if ($.grep(value, function (v) { return v == (o && typeof o === 'object' ? valueProp(o) : o); }).length) {
                            result.push(o);
                        }
                    } else {
                        var itemValue = (o && (typeof o === 'object')) ? valueProp(o) : o;
                        if (value == itemValue) {
                            result.push(o);
                        }
                    }
                    /*jslint eqeq: false*/
                }
            });

            return result;
        },

        /*
        Returns input by options: type, mode. 
        */
        createInput: function (options) {
            
            var TypeConstructor, typeOptions, input,
                type = options.type;

            //`date` is some kind of virtual type that is transformed to one of exact types
            //depending on mode and core lib
            if (type === 'date') {
                //inline
                if (options.mode === 'inline') {
                    if ($.fn.editabletypes.datefield) {
                        type = 'datefield';
                    } else if ($.fn.editabletypes.dateuifield) {
                        type = 'dateuifield';
                    }
                    //popup
                } else {
                    if ($.fn.editabletypes.date) {
                        type = 'date';
                    } else if ($.fn.editabletypes.dateui) {
                        type = 'dateui';
                    }
                }

                //if type still `date` and not exist in types, replace with `combodate` that is base input
                if (type === 'date' && !$.fn.editabletypes.date) {
                    type = 'combodate';
                }
            }

            //`datetime` should be datetimefield in 'inline' mode
            if (type === 'datetime' && options.mode === 'inline') {
                type = 'datetimefield';
            }

            //change wysihtml5 to textarea for jquery UI and plain versions
            if (type === 'textarea' && !$.fn.editabletypes[type]) {
                type = 'textarea';
            }

            //create input of specified type. Input will be used for converting value, not in form
            if (typeof $.fn.editabletypes[type] === 'function') {
                TypeConstructor = $.fn.editabletypes[type];
                typeOptions = this.sliceObj(options, this.objectKeys(TypeConstructor.defaults));
                input = new TypeConstructor(typeOptions);
                return input;
            } else {
                $.error('Unknown type: ' + type);
                return false;
            }
        },

        //see http://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr
        supportsTransitions: function () {
            var b = document.body || document.documentElement,
                s = b.style,
                p = 'transition',
                v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms'];

            if (typeof s[p] === 'string') {
                return true;
            }

            // Tests for vendor specific prop
            p = p.charAt(0).toUpperCase() + p.substr(1);
            for (var i = 0; i < v.length; i++) {
                if (typeof s[v[i] + p] === 'string') {
                    return true;
                }
            }
            return false;
        }

    };
}(window.jQuery));

/**
Attaches stand-alone container with editable-form to HTML element. Element is used only for positioning, value is not stored anywhere.<br>
This method applied internally in <code>$().editable()</code>. You should subscribe on it's events (save / cancel) to get profit of it.<br>
Final realization can be different: bootstrap-popover, jqueryui-tooltip, poshytip, inline-div. It depends on which js file you include.<br>
Applied as jQuery method.

@class editableContainer
@uses editableform
**/
(function ($) {
    "use strict";

    var Popup = function (element, options) {
        this.init(element, options);
    };

    var Inline = function (element, options) {
        this.init(element, options);
    };

    //methods
    Popup.prototype = {
        containerName: null, //method to call container on element
        containerDataName: null, //object name in element's .data()
        innerCss: null, //tbd in child class
        containerClass: 'editable-container editable-popup', //css class applied to container element
        defaults: {}, //container itself defaults

        init: function (element, options) {
            this.$element = $(element);
            //since 1.4.1 container do not use data-* directly as they already merged into options.
            this.options = $.extend({}, $.fn.editableContainer.defaults, options);
            this.splitOptions();

            //set scope of form callbacks to element
            this.formOptions.scope = this.$element[0];

            this.initContainer();

            //flag to hide container, when saving value will finish
            this.delayedHide = false;

            //bind 'destroyed' listener to destroy container when element is removed from dom
            this.$element.on('destroyed', $.proxy(function () {
                this.destroy();
            }, this));

            //attach document handler to close containers on click / escape
            if (!$(document).data('editable-handlers-attached')) {
                //close all on escape
                $(document).on('keyup.editable', function (e) {
                    if (e.which === 27) {
                        $('.editable-open').editableContainer('hide');
                        //todo: return focus on element 
                    }
                });

                //close containers when click outside 
                //(mousedown could be better than click, it closes everything also on drag drop)
                $(document).on('click.editable', function (e) {
                    var $target = $(e.target), i,
                        exclude_classes = ['.editable-container',
                            '.ui-datepicker-header',
                            '.datepicker', //in inline mode datepicker is rendered into body
                            '.modal-backdrop',
                            '.bootstrap-wysihtml5-insert-image-modal',
                            '.bootstrap-wysihtml5-insert-link-modal'
                        ];

                    //check if element is detached. It occurs when clicking in bootstrap datepicker
                    if (!$.contains(document.documentElement, e.target)) {
                        return;
                    }

                    //for some reason FF 20 generates extra event (click) in select2 widget with e.target = document
                    //we need to filter it via construction below. See https://github.com/vitalets/x-editable/issues/199
                    //Possibly related to http://stackoverflow.com/questions/10119793/why-does-firefox-react-differently-from-webkit-and-ie-to-click-event-on-selec
                    if ($target.is(document)) {
                        return;
                    }

                    //if click inside one of exclude classes --> no nothing
                    for (i = 0; i < exclude_classes.length; i++) {
                        if ($target.is(exclude_classes[i]) || $target.parents(exclude_classes[i]).length) {
                            return;
                        }
                    }

                    //close all open containers (except one - target)
                    Popup.prototype.closeOthers(e.target);
                });

                $(document).data('editable-handlers-attached', true);
            }
        },

        //split options on containerOptions and formOptions
        splitOptions: function () {
            this.containerOptions = {};
            this.formOptions = {};

            if (!$.fn[this.containerName]) {
                throw new Error(this.containerName + ' not found. Have you included corresponding js file?');
            }

            //keys defined in container defaults go to container, others go to form
            for (var k in this.options) {
                if (k in this.defaults) {
                    this.containerOptions[k] = this.options[k];
                } else {
                    this.formOptions[k] = this.options[k];
                }
            }
        },

        /*
        Returns jquery object of container
        @method tip()
        */
        tip: function () {
            return this.container() ? this.container().$tip : null;
        },

        /* returns container object */
        container: function () {
            var container;
            //first, try get it by `containerDataName`
            if (this.containerDataName) {
                if (container = this.$element.data(this.containerDataName)) {
                    return container;
                }
            }
            //second, try `containerName`
            container = this.$element.data(this.containerName);
            return container;
        },

        /* call native method of underlying container, e.g. this.$element.popover('method') */
        call: function () {
            this.$element[this.containerName].apply(this.$element, arguments);
        },

        initContainer: function () {
            this.call(this.containerOptions);
        },

        renderForm: function () {
            this.$form
                .editableform(this.formOptions)
                .on({
                    save: $.proxy(this.save, this), //click on submit button (value changed)
                    nochange: $.proxy(function () { this.hide('nochange'); }, this), //click on submit button (value NOT changed)                
                    cancel: $.proxy(function () { this.hide('cancel'); }, this), //click on calcel button
                    show: $.proxy(function () {
                        if (this.delayedHide) {
                            this.hide(this.delayedHide.reason);
                            this.delayedHide = false;
                        } else {
                            this.setPosition();
                        }
                    }, this), //re-position container every time form is shown (occurs each time after loading state)
                    rendering: $.proxy(this.setPosition, this), //this allows to place container correctly when loading shown
                    resize: $.proxy(this.setPosition, this), //this allows to re-position container when form size is changed 
                    rendered: $.proxy(function () {
                        /**        
                        Fired when container is shown and form is rendered (for select will wait for loading dropdown options).  
                        **Note:** Bootstrap popover has own `shown` event that now cannot be separated from x-editable's one.
                        The workaround is to check `arguments.length` that is always `2` for x-editable.                     
                        
                        @event shown 
                        @param {Object} event event object
                        @example
                        $('#username').on('shown', function(e, editable) {
                            editable.input.$input.val('overwriting value of input..');
                        });                     
                        **/
                        /*
                         TODO: added second param mainly to distinguish from bootstrap's shown event. It's a hotfix that will be solved in future versions via namespaced events.  
                        */
                        this.$element.triggerHandler('shown', $(this.options.scope).data('editable'));
                    }, this)
                })
                .editableform('render');
        },

        /**
        Shows container with form
        @method show()
        @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true.
        **/
        /* Note: poshytip owerwrites this method totally! */
        show: function (closeAll) {
            this.$element.addClass('editable-open');
            if (closeAll !== false) {
                //close all open containers (except this)
                this.closeOthers(this.$element[0]);
            }

            //show container itself
            this.innerShow();
            this.tip().addClass(this.containerClass);

            /*
            Currently, form is re-rendered on every show. 
            The main reason is that we dont know, what will container do with content when closed:
            remove(), detach() or just hide() - it depends on container.
            
            Detaching form itself before hide and re-insert before show is good solution, 
            but visually it looks ugly --> container changes size before hide.  
            */

            //if form already exist - delete previous data 
            if (this.$form) {
                //todo: destroy prev data!
                //this.$form.destroy();
            }

            this.$form = $('<div>');

            //insert form into container body
            if (this.tip().is(this.innerCss)) {
                //for inline container
                this.tip().append(this.$form);
            } else {
                this.tip().find(this.innerCss).append(this.$form);
            }

            //render form
            this.renderForm();
        },

        /**
        Hides container with form
        @method hide()
        @param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|undefined (=manual)</code>
        **/
        hide: function (reason) {
            if (!this.tip() || !this.tip().is(':visible') || !this.$element.hasClass('editable-open')) {
                return;
            }

            //if form is saving value, schedule hide
            if (this.$form.data('editableform').isSaving) {
                this.delayedHide = { reason: reason };
                return;
            } else {
                this.delayedHide = false;
            }

            this.$element.removeClass('editable-open');
            this.innerHide();

            /**
            Fired when container was hidden. It occurs on both save or cancel.  
            **Note:** Bootstrap popover has own `hidden` event that now cannot be separated from x-editable's one.
            The workaround is to check `arguments.length` that is always `2` for x-editable. 

            @event hidden 
            @param {object} event event object
            @param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|manual</code>
            @example
            $('#username').on('hidden', function(e, reason) {
                if(reason === 'save' || reason === 'cancel') {
                    //auto-open next editable
                    $(this).closest('tr').next().find('.editable').editable('show');
                } 
            });
            **/
            this.$element.triggerHandler('hidden', reason || 'manual');
        },

        /* internal show method. To be overwritten in child classes */
        innerShow: function () {

        },

        /* internal hide method. To be overwritten in child classes */
        innerHide: function () {

        },

        /**
        Toggles container visibility (show / hide)
        @method toggle()
        @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true.
        **/
        toggle: function (closeAll) {
            if (this.container() && this.tip() && this.tip().is(':visible')) {
                this.hide();
            } else {
                this.show(closeAll);
            }
        },

        /*
        Updates the position of container when content changed.
        @method setPosition()
        */
        setPosition: function () {
            //tbd in child class
        },

        save: function (e, params) {
            /**        
            Fired when new value was submitted. You can use <code>$(this).data('editableContainer')</code> inside handler to access to editableContainer instance
            
            @event save 
            @param {Object} event event object
            @param {Object} params additional params
            @param {mixed} params.newValue submitted value
            @param {Object} params.response ajax response
            @example
            $('#username').on('save', function(e, params) {
                //assuming server response: '{success: true}'
                var pk = $(this).data('editableContainer').options.pk;
                if(params.response && params.response.success) {
                    alert('value: ' + params.newValue + ' with pk: ' + pk + ' saved!');
                } else {
                    alert('error!'); 
                } 
            });
            **/
            this.$element.triggerHandler('save', params);

            //hide must be after trigger, as saving value may require methods of plugin, applied to input
            this.hide('save');
        },

        /**
        Sets new option
        
        @method option(key, value)
        @param {string} key 
        @param {mixed} value 
        **/
        option: function (key, value) {
            this.options[key] = value;
            if (key in this.containerOptions) {
                this.containerOptions[key] = value;
                this.setContainerOption(key, value);
            } else {
                this.formOptions[key] = value;
                if (this.$form) {
                    this.$form.editableform('option', key, value);
                }
            }
        },

        setContainerOption: function (key, value) {
            this.call('option', key, value);
        },

        /**
        Destroys the container instance
        @method destroy()
        **/
        destroy: function () {
            this.hide();
            this.innerDestroy();
            this.$element.off('destroyed');
            this.$element.removeData('editableContainer');
        },

        /* to be overwritten in child classes */
        innerDestroy: function () {

        },

        /*
        Closes other containers except one related to passed element. 
        Other containers can be cancelled or submitted (depends on onblur option)
        */
        closeOthers: function (element) {
            $('.editable-open').each(function (i, el) {
                //do nothing with passed element and it's children
                if (el === element || $(el).find(element).length) {
                    return;
                }

                //otherwise cancel or submit all open containers 
                var $el = $(el),
                    ec = $el.data('editableContainer');

                if (!ec) {
                    return;
                }

                if (ec.options.onblur === 'cancel') {
                    $el.data('editableContainer').hide('onblur');
                } else if (ec.options.onblur === 'submit') {
                    $el.data('editableContainer').tip().find('form').submit();
                }
            });

        },

        /**
        Activates input of visible container (e.g. set focus)
        @method activate()
        **/
        activate: function () {
            if (this.tip && this.tip().is(':visible') && this.$form) {
                this.$form.data('editableform').input.activate();
            }
        }

    };

    /**
    jQuery method to initialize editableContainer.
    
    @method $().editableContainer(options)
    @params {Object} options
    @example
    $('#edit').editableContainer({
        type: 'text',
        url: '/post',
        pk: 1,
        value: 'hello'
    });
    **/
    $.fn.editableContainer = function (option) {
        var args = arguments;
        return this.each(function () {
            var $this = $(this),
                dataKey = 'editableContainer',
                data = $this.data(dataKey),
                options = typeof option === 'object' && option,
                Constructor = (options.mode === 'inline') ? Inline : Popup;

            if (!data) {
                $this.data(dataKey, (data = new Constructor(this, options)));
            }

            if (typeof option === 'string') { //call method 
                data[option].apply(data, Array.prototype.slice.call(args, 1));
            }
        });
    };

    //store constructors
    $.fn.editableContainer.Popup = Popup;
    $.fn.editableContainer.Inline = Inline;

    //defaults
    $.fn.editableContainer.defaults = {
        /**
        Initial value of form input

        @property value 
        @type mixed
        @default null
        @private
        **/
        value: null,
        /**
        Placement of container relative to element. Can be <code>top|right|bottom|left</code>. Not used for inline container.

        @property placement 
        @type string
        @default 'top'
        **/
        placement: 'top',
        /**
        Whether to hide container on save/cancel.

        @property autohide 
        @type boolean
        @default true
        @private 
        **/
        autohide: true,
        /**
        Action when user clicks outside the container. Can be <code>cancel|submit|ignore</code>.  
        Setting <code>ignore</code> allows to have several containers open. 

        @property onblur 
        @type string
        @default 'cancel'
        @since 1.1.1
        **/
        onblur: 'cancel',

        /**
        Animation speed (inline mode only)
        @property anim 
        @type string
        @default false
        **/
        anim: false,

        /**
        Mode of editable, can be `popup` or `inline` 
        
        @property mode 
        @type string         
        @default 'popup'
        @since 1.4.0        
        **/
        mode: 'popup'
    };

    /* 
    * workaround to have 'destroyed' event to destroy popover when element is destroyed
    * see http://stackoverflow.com/questions/2200494/jquery-trigger-event-when-an-element-is-removed-from-the-dom
    */
    jQuery.event.special.destroyed = {
        remove: function (o) {
            if (o.handler) {
                o.handler();
            }
        }
    };

}(window.jQuery));

/**
* Editable Inline 
* ---------------------
*/
(function ($) {
    "use strict";

    //copy prototype from EditableContainer
    //extend methods
    $.extend($.fn.editableContainer.Inline.prototype, $.fn.editableContainer.Popup.prototype, {
        containerName: 'editableform',
        innerCss: '.editable-inline',
        containerClass: 'editable-container editable-inline', //css class applied to container element

        initContainer: function () {
            //container is <span> element
            this.$tip = $('<span></span>');

            //convert anim to miliseconds (int)
            if (!this.options.anim) {
                this.options.anim = 0;
            }
        },

        splitOptions: function () {
            //all options are passed to form
            this.containerOptions = {};
            this.formOptions = this.options;
        },

        tip: function () {
            return this.$tip;
        },

        innerShow: function () {
            this.$element.hide();
            this.tip().insertAfter(this.$element).show();
        },

        innerHide: function () {
            this.$tip.hide(this.options.anim, $.proxy(function () {
                this.$element.show();
                this.innerDestroy();
            }, this));
        },

        innerDestroy: function () {
            if (this.tip()) {
                this.tip().empty().remove();
            }
        }
    });

}(window.jQuery));
/**
Makes editable any HTML element on the page. Applied as jQuery method.

@class editable
@uses editableContainer
**/
(function ($) {
    "use strict";

    var Editable = function (element, options) {
        this.$element = $(element);
        //data-* has more priority over js options: because dynamically created elements may change data-* 
        this.options = $.extend({}, $.fn.editable.defaults, options, $.fn.editableutils.getConfigData(this.$element));
        if (this.options.selector) {
            this.initLive();
        } else {
            this.init();
        }

        //check for transition support
        if (this.options.highlight && !$.fn.editableutils.supportsTransitions()) {
            this.options.highlight = false;
        }
    };

    Editable.prototype = {
        constructor: Editable,
        init: function () {
            var isValueByText = false,
                doAutotext, finalize;

            //name
            this.options.name = this.options.name || this.$element.attr('id');

            //create input of specified type. Input needed already here to convert value for initial display (e.g. show text by id for select)
            //also we set scope option to have access to element inside input specific callbacks (e. g. source as function)
            this.options.scope = this.$element[0];
            this.input = $.fn.editableutils.createInput(this.options);
            if (!this.input) {
                return;
            }

            //set value from settings or by element's text
            if (this.options.value === undefined || this.options.value === null) {
                this.value = this.input.html2value($.trim(this.$element.html()));
                isValueByText = true;
            } else {
                /*
                  value can be string when received from 'data-value' attribute
                  for complext objects value can be set as json string in data-value attribute, 
                  e.g. data-value="{city: 'Moscow', street: 'Lenina'}"
                */
                this.options.value = $.fn.editableutils.tryParseJson(this.options.value, true);
                if (typeof this.options.value === 'string') {
                    this.value = this.input.str2value(this.options.value);
                } else {
                    this.value = this.options.value;
                }
            }

            //add 'editable' class to every editable element
            this.$element.addClass('editable');

            //specifically for "textarea" add class .editable-pre-wrapped to keep linebreaks
            if (this.input.type === 'textarea') {
                this.$element.addClass('editable-pre-wrapped');
            }

            //attach handler activating editable. In disabled mode it just prevent default action (useful for links)
            if (this.options.toggle !== 'manual') {
                this.$element.addClass('editable-click');
                this.$element.on(this.options.toggle + '.editable', $.proxy(function (e) {
                    //prevent following link if editable enabled
                    if (!this.options.disabled) {
                        e.preventDefault();
                    }

                    //stop propagation not required because in document click handler it checks event target
                    //e.stopPropagation();

                    if (this.options.toggle === 'mouseenter') {
                        //for hover only show container
                        this.show();
                    } else {
                        //when toggle='click' we should not close all other containers as they will be closed automatically in document click listener
                        var closeAll = (this.options.toggle !== 'click');
                        this.toggle(closeAll);
                    }
                }, this));
            } else {
                this.$element.attr('tabindex', -1); //do not stop focus on element when toggled manually
            }

            //if display is function it's far more convinient to have autotext = always to render correctly on init
            //see https://github.com/vitalets/x-editable-yii/issues/34
            if (typeof this.options.display === 'function') {
                this.options.autotext = 'always';
            }

            //check conditions for autotext:
            switch (this.options.autotext) {
                case 'always':
                    doAutotext = true;
                    break;
                case 'auto':
                    //if element text is empty and value is defined and value not generated by text --> run autotext
                    doAutotext = !$.trim(this.$element.text()).length && this.value !== null && this.value !== undefined && !isValueByText;
                    break;
                default:
                    doAutotext = false;
            }

            //depending on autotext run render() or just finilize init
            $.when(doAutotext ? this.render() : true).then($.proxy(function () {
                if (this.options.disabled) {
                    this.disable();
                } else {
                    this.enable();
                }
                /**        
                Fired when element was initialized by `$().editable()` method. 
                Please note that you should setup `init` handler **before** applying `editable`. 
                               
                @event init 
                @param {Object} event event object
                @param {Object} editable editable instance (as here it cannot accessed via data('editable'))
                @since 1.2.0
                @example
                $('#username').on('init', function(e, editable) {
                    alert('initialized ' + editable.options.name);
                });
                $('#username').editable();
                **/
                this.$element.triggerHandler('init', this);
            }, this));
        },

        /*
         Initializes parent element for live editables 
        */
        initLive: function () {
            //store selector 
            var selector = this.options.selector;
            //modify options for child elements
            this.options.selector = false;
            this.options.autotext = 'never';
            //listen toggle events
            this.$element.on(this.options.toggle + '.editable', selector, $.proxy(function (e) {
                var $target = $(e.target);
                if (!$target.data('editable')) {
                    //if delegated element initially empty, we need to clear it's text (that was manually set to `empty` by user)
                    //see https://github.com/vitalets/x-editable/issues/137 
                    if ($target.hasClass(this.options.emptyclass)) {
                        $target.empty();
                    }
                    $target.editable(this.options).trigger(e);
                }
            }, this));
        },

        /*
        Renders value into element's text.
        Can call custom display method from options.
        Can return deferred object.
        @method render()
        @param {mixed} response server response (if exist) to pass into display function
        */
        render: function (response) {
            //do not display anything
            if (this.options.display === false) {
                return;
            }

            //if input has `value2htmlFinal` method, we pass callback in third param to be called when source is loaded
            if (this.input.value2htmlFinal) {
                return this.input.value2html(this.value, this.$element[0], this.options.display, response);
                //if display method defined --> use it    
            } else if (typeof this.options.display === 'function') {
                return this.options.display.call(this.$element[0], this.value, response);
                //else use input's original value2html() method    
            } else {
                return this.input.value2html(this.value, this.$element[0]);
            }
        },

        /**
        Enables editable
        @method enable()
        **/
        enable: function () {
            this.options.disabled = false;
            this.$element.removeClass('editable-disabled');
            this.handleEmpty(this.isEmpty);
            if (this.options.toggle !== 'manual') {
                if (this.$element.attr('tabindex') === '-1') {
                    this.$element.removeAttr('tabindex');
                }
            }
        },

        /**
        Disables editable
        @method disable()
        **/
        disable: function () {
            this.options.disabled = true;
            this.hide();
            this.$element.addClass('editable-disabled');
            this.handleEmpty(this.isEmpty);
            //do not stop focus on this element
            this.$element.attr('tabindex', -1);
        },

        /**
        Toggles enabled / disabled state of editable element
        @method toggleDisabled()
        **/
        toggleDisabled: function () {
            if (this.options.disabled) {
                this.enable();
            } else {
                this.disable();
            }
        },

        /**
        Sets new option
        
        @method option(key, value)
        @param {string|object} key option name or object with several options
        @param {mixed} value option new value
        @example
        $('.editable').editable('option', 'pk', 2);
        **/
        option: function (key, value) {
            //set option(s) by object
            if (key && typeof key === 'object') {
                $.each(key, $.proxy(function (k, v) {
                    this.option($.trim(k), v);
                }, this));
                return;
            }

            //set option by string             
            this.options[key] = value;

            //disabled
            if (key === 'disabled') {
                return value ? this.disable() : this.enable();
            }

            //value
            if (key === 'value') {
                this.setValue(value);
            }

            //transfer new option to container! 
            if (this.container) {
                this.container.option(key, value);
            }

            //pass option to input directly (as it points to the same in form)
            if (this.input.option) {
                this.input.option(key, value);
            }

        },

        /*
        * set emptytext if element is empty
        */
        handleEmpty: function (isEmpty) {
            //do not handle empty if we do not display anything
            if (this.options.display === false) {
                return;
            }

            /* 
            isEmpty may be set directly as param of method.
            It is required when we enable/disable field and can't rely on content 
            as node content is text: "Empty" that is not empty %)
            */
            if (isEmpty !== undefined) {
                this.isEmpty = isEmpty;
            } else {
                //detect empty
                //for some inputs we need more smart check
                //e.g. wysihtml5 may have <br>, <p></p>, <img>
                if (typeof (this.input.isEmpty) === 'function') {
                    this.isEmpty = this.input.isEmpty(this.$element);
                } else {
                    this.isEmpty = $.trim(this.$element.html()) === '';
                }
            }

            //emptytext shown only for enabled
            if (!this.options.disabled) {
                if (this.isEmpty) {
                    this.$element.html(this.options.emptytext);
                    if (this.options.emptyclass) {
                        this.$element.addClass(this.options.emptyclass);
                    }
                } else if (this.options.emptyclass) {
                    this.$element.removeClass(this.options.emptyclass);
                }
            } else {
                //below required if element disable property was changed
                if (this.isEmpty) {
                    this.$element.empty();
                    if (this.options.emptyclass) {
                        this.$element.removeClass(this.options.emptyclass);
                    }
                }
            }
        },

        /**
        Shows container with form
        @method show()
        @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true.
        **/
        show: function (closeAll) {
            if (this.options.disabled) {
                return;
            }

            //init editableContainer: popover, tooltip, inline, etc..
            if (!this.container) {
                var containerOptions = $.extend({}, this.options, {
                    value: this.value,
                    input: this.input //pass input to form (as it is already created)
                });
                this.$element.editableContainer(containerOptions);
                //listen `save` event 
                this.$element.on("save.internal", $.proxy(this.save, this));
                this.container = this.$element.data('editableContainer');
            } else if (this.container.tip().is(':visible')) {
                return;
            }

            //show container
            this.container.show(closeAll);
        },

        /**
        Hides container with form
        @method hide()
        **/
        hide: function () {
            if (this.container) {
                this.container.hide();
            }
        },

        /**
        Toggles container visibility (show / hide)
        @method toggle()
        @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true.
        **/
        toggle: function (closeAll) {
            if (this.container && this.container.tip().is(':visible')) {
                this.hide();
            } else {
                this.show(closeAll);
            }
        },

        /*
        * called when form was submitted
        */
        save: function (e, params) {
            //mark element with unsaved class if needed
            if (this.options.unsavedclass) {
                /*
                 Add unsaved css to element if:
                  - url is not user's function 
                  - value was not sent to server
                  - params.response === undefined, that means data was not sent
                  - value changed 
                */
                var sent = false;
                sent = sent || typeof this.options.url === 'function';
                sent = sent || this.options.display === false;
                sent = sent || params.response !== undefined;
                sent = sent || (this.options.savenochange && this.input.value2str(this.value) !== this.input.value2str(params.newValue));

                if (sent) {
                    this.$element.removeClass(this.options.unsavedclass);
                } else {
                    this.$element.addClass(this.options.unsavedclass);
                }
            }

            //highlight when saving
            if (this.options.highlight) {
                var $e = this.$element,
                    bgColor = $e.css('background-color');

                $e.css('background-color', this.options.highlight);
                setTimeout(function () {
                    if (bgColor === 'transparent') {
                        bgColor = '';
                    }
                    $e.css('background-color', bgColor);
                    $e.addClass('editable-bg-transition');
                    setTimeout(function () {
                        $e.removeClass('editable-bg-transition');
                    }, 1700);
                }, 10);
            }

            //set new value
            this.setValue(params.newValue, false, params.response);

            /**        
            Fired when new value was submitted. You can use <code>$(this).data('editable')</code> to access to editable instance
            
            @event save 
            @param {Object} event event object
            @param {Object} params additional params
            @param {mixed} params.newValue submitted value
            @param {Object} params.response ajax response
            @example
            $('#username').on('save', function(e, params) {
                alert('Saved value: ' + params.newValue);
            });
            **/
            //event itself is triggered by editableContainer. Description here is only for documentation              
        },

        validate: function () {
            if (typeof this.options.validate === 'function') {
                return this.options.validate.call(this, this.value);
            }
        },

        /**
        Sets new value of editable
        @method setValue(value, convertStr)
        @param {mixed} value new value 
        @param {boolean} convertStr whether to convert value from string to internal format
        **/
        setValue: function (value, convertStr, response) {
            if (convertStr) {
                this.value = this.input.str2value(value);
            } else {
                this.value = value;
            }
            if (this.container) {
                this.container.option('value', this.value);
            }
            $.when(this.render(response))
                .then($.proxy(function () {
                    this.handleEmpty();
                }, this));
        },

        /**
        Activates input of visible container (e.g. set focus)
        @method activate()
        **/
        activate: function () {
            if (this.container) {
                this.container.activate();
            }
        },

        /**
        Removes editable feature from element
        @method destroy()
        **/
        destroy: function () {
            this.disable();

            if (this.container) {
                this.container.destroy();
            }

            this.input.destroy();

            if (this.options.toggle !== 'manual') {
                this.$element.removeClass('editable-click');
                this.$element.off(this.options.toggle + '.editable');
            }

            this.$element.off("save.internal");

            this.$element.removeClass('editable editable-open editable-disabled');
            this.$element.removeData('editable');
        }
    };

    /* EDITABLE PLUGIN DEFINITION
    * ======================= */

    /**
    jQuery method to initialize editable element.
    
    @method $().editable(options)
    @params {Object} options
    @example
    $('#username').editable({
        type: 'text',
        url: '/post',
        pk: 1
    });
    **/
    $.fn.editable = function (option) {
        //special API methods returning non-jquery object
        var result = {}, args = arguments, datakey = 'editable';
        switch (option) {
            /**
            Runs client-side validation for all matched editables
            
            @method validate()
            @returns {Object} validation errors map
            @example
            $('#username, #fullname').editable('validate');
            // possible result:
            {
              username: "username is required",
              fullname: "fullname should be minimum 3 letters length"
            }
            **/
            case 'validate':
                this.each(function () {
                    var $this = $(this), data = $this.data(datakey), error;
                    if (data && (error = data.validate())) {
                        result[data.options.name] = error;
                    }
                });
                return result;

            /**
            Returns current values of editable elements.   
            Note that it returns an **object** with name-value pairs, not a value itself. It allows to get data from several elements.    
            If value of some editable is `null` or `undefined` it is excluded from result object.
            When param `isSingle` is set to **true** - it is supposed you have single element and will return value of editable instead of object.   
             
            @method getValue()
            @param {bool} isSingle whether to return just value of single element
            @returns {Object} object of element names and values
            @example
            $('#username, #fullname').editable('getValue');
            //result:
            {
            username: "superuser",
            fullname: "John"
            }
            //isSingle = true
            $('#username').editable('getValue', true);
            //result "superuser" 
            **/
            case 'getValue':
                if (arguments.length === 2 && arguments[1] === true) { //isSingle = true
                    result = this.eq(0).data(datakey).value;
                } else {
                    this.each(function () {
                        var $this = $(this), data = $this.data(datakey);
                        if (data && data.value !== undefined && data.value !== null) {
                            result[data.options.name] = data.input.value2submit(data.value);
                        }
                    });
                }
                return result;

            /**
            This method collects values from several editable elements and submit them all to server.   
            Internally it runs client-side validation for all fields and submits only in case of success.  
            See <a href="#newrecord">creating new records</a> for details.  
            Since 1.5.1 `submit` can be applied to single element to send data programmatically. In that case
            `url`, `success` and `error` is taken from initial options and you can just call `$('#username').editable('submit')`. 
            
            @method submit(options)
            @param {object} options 
            @param {object} options.url url to submit data 
            @param {object} options.data additional data to submit
            @param {object} options.ajaxOptions additional ajax options
            @param {function} options.error(obj) error handler 
            @param {function} options.success(obj,config) success handler
            @returns {Object} jQuery object
            **/
            case 'submit':  //collects value, validate and submit to server for creating new record
                var config = arguments[1] || {},
                    $elems = this,
                    errors = this.editable('validate');

                // validation ok
                if ($.isEmptyObject(errors)) {
                    var ajaxOptions = {};

                    // for single element use url, success etc from options
                    if ($elems.length === 1) {
                        var editable = $elems.data('editable');
                        //standard params
                        var params = {
                            name: editable.options.name || '',
                            value: editable.input.value2submit(editable.value),
                            pk: (typeof editable.options.pk === 'function') ?
                                editable.options.pk.call(editable.options.scope) :
                                editable.options.pk
                        };

                        //additional params
                        if (typeof editable.options.params === 'function') {
                            params = editable.options.params.call(editable.options.scope, params);
                        } else {
                            //try parse json in single quotes (from data-params attribute)
                            editable.options.params = $.fn.editableutils.tryParseJson(editable.options.params, true);
                            $.extend(params, editable.options.params);
                        }

                        ajaxOptions = {
                            url: editable.options.url,
                            data: params,
                            type: 'POST'
                        };

                        // use success / error from options 
                        config.success = config.success || editable.options.success;
                        config.error = config.error || editable.options.error;

                        // multiple elements
                    } else {
                        var values = this.editable('getValue');

                        ajaxOptions = {
                            url: config.url,
                            data: values,
                            type: 'POST'
                        };
                    }

                    // ajax success callabck (response 200 OK)
                    ajaxOptions.success = typeof config.success === 'function' ? function (response) {
                        config.success.call($elems, response, config);
                    } : $.noop;

                    // ajax error callabck
                    ajaxOptions.error = typeof config.error === 'function' ? function () {
                        config.error.apply($elems, arguments);
                    } : $.noop;

                    // extend ajaxOptions    
                    if (config.ajaxOptions) {
                        $.extend(ajaxOptions, config.ajaxOptions);
                    }

                    // extra data 
                    if (config.data) {
                        $.extend(ajaxOptions.data, config.data);
                    }

                    // perform ajax request
                    $.ajax(ajaxOptions);
                } else { //client-side validation error
                    if (typeof config.error === 'function') {
                        config.error.call($elems, errors);
                    }
                }
                return this;
        }

        //return jquery object
        return this.each(function () {
            var $this = $(this),
                data = $this.data(datakey),
                options = typeof option === 'object' && option;

            //for delegated targets do not store `editable` object for element
            //it's allows several different selectors.
            //see: https://github.com/vitalets/x-editable/issues/312    
            if (options && options.selector) {
                data = new Editable(this, options);
                return;
            }

            if (!data) {
                $this.data(datakey, (data = new Editable(this, options)));
            }

            if (typeof option === 'string') { //call method 
                data[option].apply(data, Array.prototype.slice.call(args, 1));
            }
        });
    };


    $.fn.editable.defaults = {
        /**
        Type of input. Can be <code>text|textarea|select|date|checklist</code> and more

        @property type 
        @type string
        @default 'text'
        **/
        type: 'text',
        /**
        Sets disabled state of editable

        @property disabled 
        @type boolean
        @default false
        **/
        disabled: false,
        /**
        How to toggle editable. Can be <code>click|dblclick|mouseenter|manual</code>.   
        When set to <code>manual</code> you should manually call <code>show/hide</code> methods of editable.    
        **Note**: if you call <code>show</code> or <code>toggle</code> inside **click** handler of some DOM element, 
        you need to apply <code>e.stopPropagation()</code> because containers are being closed on any click on document.
        
        @example
        $('#edit-button').click(function(e) {
            e.stopPropagation();
            $('#username').editable('toggle');
        });

        @property toggle 
        @type string
        @default 'click'
        **/
        toggle: 'click',
        /**
        Text shown when element is empty.

        @property emptytext 
        @type string
        @default 'Empty'
        **/
        emptytext: resourcesMessages.TextIsEmpty,
        /**
        Allows to automatically set element's text based on it's value. Can be <code>auto|always|never</code>. Useful for select and date.
        For example, if dropdown list is <code>{1: 'a', 2: 'b'}</code> and element's value set to <code>1</code>, it's html will be automatically set to <code>'a'</code>.  
        <code>auto</code> - text will be automatically set only if element is empty.  
        <code>always|never</code> - always(never) try to set element's text.

        @property autotext 
        @type string
        @default 'auto'
        **/
        autotext: 'auto',
        /**
        Initial value of input. If not set, taken from element's text.  
        Note, that if element's text is empty - text is automatically generated from value and can be customized (see `autotext` option).  
        For example, to display currency sign:
        @example
        <a id="price" data-type="text" data-value="100"></a>
        <script>
        $('#price').editable({
            ...
            display: function(value) {
              $(this).text(value + '$');
            } 
        }) 
        </script>
                
        @property value 
        @type mixed
        @default element's text
        **/
        value: null,
        /**
        Callback to perform custom displaying of value in element's text.  
        If `null`, default input's display used.  
        If `false`, no displaying methods will be called, element's text will never change.  
        Runs under element's scope.  
        _**Parameters:**_  
        
        * `value` current value to be displayed
        * `response` server response (if display called after ajax submit), since 1.4.0
         
        For _inputs with source_ (select, checklist) parameters are different:  
          
        * `value` current value to be displayed
        * `sourceData` array of items for current input (e.g. dropdown items) 
        * `response` server response (if display called after ajax submit), since 1.4.0
                  
        To get currently selected items use `$.fn.editableutils.itemsByValue(value, sourceData)`.
        
        @property display 
        @type function|boolean
        @default null
        @since 1.2.0
        @example
        display: function(value, sourceData) {
           //display checklist as comma-separated values
           var html = [],
               checked = $.fn.editableutils.itemsByValue(value, sourceData);
               
           if(checked.length) {
               $.each(checked, function(i, v) { html.push($.fn.editableutils.escape(v.text)); });
               $(this).html(html.join(', '));
           } else {
               $(this).empty(); 
           }
        }
        **/
        display: null,
        /**
        Css class applied when editable text is empty.

        @property emptyclass 
        @type string
        @since 1.4.1        
        @default editable-empty
        **/
        emptyclass: 'editable-empty',
        /**
        Css class applied when value was stored but not sent to server (`pk` is empty or `send = 'never'`).  
        You may set it to `null` if you work with editables locally and submit them together.  

        @property unsavedclass 
        @type string
        @since 1.4.1        
        @default editable-unsaved
        **/
        unsavedclass: 'editable-unsaved',
        /**
        If selector is provided, editable will be delegated to the specified targets.  
        Usefull for dynamically generated DOM elements.  
        **Please note**, that delegated targets can't be initialized with `emptytext` and `autotext` options, 
        as they actually become editable only after first click.  
        You should manually set class `editable-click` to these elements.  
        Also, if element originally empty you should add class `editable-empty`, set `data-value=""` and write emptytext into element:

        @property selector 
        @type string
        @since 1.4.1        
        @default null
        @example
        <div id="user">
          <!-- empty -->
          <a href="#" data-name="username" data-type="text" class="editable-click editable-empty" data-value="" title="Username">Empty</a>
          <!-- non-empty -->
          <a href="#" data-name="group" data-type="select" data-source="/groups" data-value="1" class="editable-click" title="Group">Operator</a>
        </div>     
        
        <script>
        $('#user').editable({
            selector: 'a',
            url: '/post',
            pk: 1
        });
        </script>
        **/
        selector: null,
        /**
        Color used to highlight element after update. Implemented via CSS3 transition, works in modern browsers.
        
        @property highlight 
        @type string|boolean
        @since 1.4.5        
        @default #FFFF80 
        **/
        highlight: '#FFFF80'
    };

}(window.jQuery));

/**
AbstractInput - base class for all editable inputs.
It defines interface to be implemented by any input type.
To create your own input you can inherit from this class.

@class abstractinput
**/
(function ($) {
    "use strict";

    //types
    $.fn.editabletypes = {};

    var AbstractInput = function () { };

    AbstractInput.prototype = {
        /**
         Initializes input
 
         @method init() 
         **/
        init: function (type, options, defaults) {
            this.type = type;
            this.options = $.extend({}, defaults, options);
        },

        /*
        this method called before render to init $tpl that is inserted in DOM
        */
        prerender: function () {
            this.$tpl = $(this.options.tpl); //whole tpl as jquery object    
            this.$input = this.$tpl;         //control itself, can be changed in render method
            this.$clear = null;              //clear button
            this.error = null;               //error message, if input cannot be rendered           
        },

        /**
         Renders input from tpl. Can return jQuery deferred object.
         Can be overwritten in child objects
 
         @method render()
        **/
        render: function () {

        },

        /**
         Sets element's html by value. 
 
         @method value2html(value, element)
         @param {mixed} value
         @param {DOMElement} element
        **/
        value2html: function (value, element) {
            $(element)[this.options.escape ? 'text' : 'html']($.trim(value));
        },

        /**
         Converts element's html to value
 
         @method html2value(html)
         @param {string} html
         @returns {mixed}
        **/
        html2value: function (html) {
            return $('<div>').html(html).text();
        },

        /**
         Converts value to string (for internal compare). For submitting to server used value2submit().
 
         @method value2str(value) 
         @param {mixed} value
         @returns {string}
        **/
        value2str: function (value) {
            return value;
        },

        /**
         Converts string received from server into value. Usually from `data-value` attribute.
 
         @method str2value(str)
         @param {string} str
         @returns {mixed}
        **/
        str2value: function (str) {
            return str;
        },

        /**
         Converts value for submitting to server. Result can be string or object.
 
         @method value2submit(value) 
         @param {mixed} value
         @returns {mixed}
        **/
        value2submit: function (value) {
            return value;
        },

        /**
         Sets value of input.
 
         @method value2input(value) 
         @param {mixed} value
        **/
        value2input: function (value) {
            this.$input.val(value);
        },

        /**
         Returns value of input. Value can be object (e.g. datepicker)
 
         @method input2value() 
        **/
        input2value: function () {
            return this.$input.val();
        },

        /**
         Activates input. For text it sets focus.
 
         @method activate() 
        **/
        activate: function () {
            if (this.$input.is(':visible')) {
                this.$input.focus();
            }
        },

        /**
         Creates input.
 
         @method clear() 
        **/
        clear: function () {
            this.$input.val(null);
        },

        /**
         method to escape html.
        **/
        escape: function (str) {
            return $('<div>').text(str).html();
        },

        /**
         attach handler to automatically submit form when value changed (useful when buttons not shown)
        **/
        autosubmit: function () {

        },

        /**
        Additional actions when destroying element 
        **/
        destroy: function () {
        },

        // -------- helper functions --------
        setClass: function () {
            if (this.options.inputclass) {
                this.$input.addClass(this.options.inputclass);
            }
        },

        setAttr: function (attr) {
            if (this.options[attr] !== undefined && this.options[attr] !== null) {
                this.$input.attr(attr, this.options[attr]);
            }
        },

        option: function (key, value) {
            this.options[key] = value;
        }

    };

    AbstractInput.defaults = {
        /**
        HTML template of input. Normally you should not change it.

        @property tpl 
        @type string
        @default ''
        **/
        tpl: '',
        /**
        CSS class automatically applied to input
        
        @property inputclass 
        @type string
        @default null
        **/
        inputclass: null,

        /**
        If `true` - html will be escaped in content of element via $.text() method.  
        If `false` - html will not be escaped, $.html() used.  
        When you use own `display` function, this option obviosly has no effect.
        
        @property escape 
        @type boolean
        @since 1.5.0
        @default true
        **/
        escape: true,

        //scope for external methods (e.g. source defined as function)
        //for internal use only
        scope: null,

        //need to re-declare showbuttons here to get it's value from common config (passed only options existing in defaults)
        showbuttons: true
    };

    $.extend($.fn.editabletypes, { abstractinput: AbstractInput });

}(window.jQuery));

/**
List - abstract class for inputs that have source option loaded from js array or via ajax

@class list
@extends abstractinput
**/
(function ($) {
    "use strict";

    var List = function (options) {

    };

    $.fn.editableutils.inherit(List, $.fn.editabletypes.abstractinput);

    $.extend(List.prototype, {
        render: function () {
            var deferred = $.Deferred();

            this.error = null;
            this.onSourceReady(function () {
                this.renderList();
                deferred.resolve();
            }, function () {
                this.error = this.options.sourceError;
                deferred.resolve();
            });

            return deferred.promise();
        },

        html2value: function (html) {
            return null; //can't set value by text
        },

        value2html: function (value, element, display, response) {
            var deferred = $.Deferred(),
                success = function () {
                    if (typeof display === 'function') {
                        //custom display method
                        display.call(element, value, this.sourceData, response);
                    } else {
                        this.value2htmlFinal(value, element);
                    }
                    deferred.resolve();
                };

            //for null value just call success without loading source
            if (value === null) {
                success.call(this);
            } else {
                this.onSourceReady(success, function () { deferred.resolve(); });
            }

            return deferred.promise();
        },

        // ------------- additional functions ------------

        onSourceReady: function (success, error) {
            //run source if it function
            var source;
            if ($.isFunction(this.options.source)) {
                source = this.options.source.call(this.options.scope);
                this.sourceData = null;
                //note: if function returns the same source as URL - sourceData will be taken from cahce and no extra request performed
            } else {
                source = this.options.source;
            }

            //if allready loaded just call success
            if (this.options.sourceCache && $.isArray(this.sourceData)) {
                success.call(this);
                return;
            }

            //try parse json in single quotes (for double quotes jquery does automatically)
            try {
                source = $.fn.editableutils.tryParseJson(source, false);
            } catch (e) {
                error.call(this);
                return;
            }

            //loading from url
            if (typeof source === 'string') {
                //try to get sourceData from cache
                if (this.options.sourceCache) {
                    var cacheID = source,
                        cache;

                    if (!$(document).data(cacheID)) {
                        $(document).data(cacheID, {});
                    }
                    cache = $(document).data(cacheID);

                    //check for cached data
                    if (cache.loading === false && cache.sourceData) { //take source from cache
                        this.sourceData = cache.sourceData;
                        this.doPrepend();
                        success.call(this);
                        return;
                    } else if (cache.loading === true) { //cache is loading, put callback in stack to be called later
                        cache.callbacks.push($.proxy(function () {
                            this.sourceData = cache.sourceData;
                            this.doPrepend();
                            success.call(this);
                        }, this));

                        //also collecting error callbacks
                        cache.err_callbacks.push($.proxy(error, this));
                        return;
                    } else { //no cache yet, activate it
                        cache.loading = true;
                        cache.callbacks = [];
                        cache.err_callbacks = [];
                    }
                }

                //ajaxOptions for source. Can be overwritten bt options.sourceOptions
                var ajaxOptions = $.extend({
                    url: source,
                    type: 'get',
                    cache: false,
                    dataType: 'json',
                    success: $.proxy(function (data) {
                        if (cache) {
                            cache.loading = false;
                        }
                        this.sourceData = this.makeArray(data);
                        if ($.isArray(this.sourceData)) {
                            if (cache) {
                                //store result in cache
                                cache.sourceData = this.sourceData;
                                //run success callbacks for other fields waiting for this source
                                $.each(cache.callbacks, function () { this.call(); });
                            }
                            this.doPrepend();
                            success.call(this);
                        } else {
                            error.call(this);
                            if (cache) {
                                //run error callbacks for other fields waiting for this source
                                $.each(cache.err_callbacks, function () { this.call(); });
                            }
                        }
                    }, this),
                    error: $.proxy(function () {
                        error.call(this);
                        if (cache) {
                            cache.loading = false;
                            //run error callbacks for other fields
                            $.each(cache.err_callbacks, function () { this.call(); });
                        }
                    }, this)
                }, this.options.sourceOptions);

                //loading sourceData from server
                $.ajax(ajaxOptions);

            } else { //options as json/array
                this.sourceData = this.makeArray(source);

                if ($.isArray(this.sourceData)) {
                    this.doPrepend();
                    success.call(this);
                } else {
                    error.call(this);
                }
            }
        },

        doPrepend: function () {
            if (this.options.prepend === null || this.options.prepend === undefined) {
                return;
            }

            if (!$.isArray(this.prependData)) {
                //run prepend if it is function (once)
                if ($.isFunction(this.options.prepend)) {
                    this.options.prepend = this.options.prepend.call(this.options.scope);
                }

                //try parse json in single quotes
                this.options.prepend = $.fn.editableutils.tryParseJson(this.options.prepend, true);

                //convert prepend from string to object
                if (typeof this.options.prepend === 'string') {
                    this.options.prepend = { '': this.options.prepend };
                }

                this.prependData = this.makeArray(this.options.prepend);
            }

            if ($.isArray(this.prependData) && $.isArray(this.sourceData)) {
                this.sourceData = this.prependData.concat(this.sourceData);
            }
        },

        /*
         renders input list
        */
        renderList: function () {
            // this method should be overwritten in child class
        },

        /*
        set element's html by value
       */
        value2htmlFinal: function (value, element) {
            // this method should be overwritten in child class
        },

        /**
        * convert data to array suitable for sourceData, e.g. [{value: 1, text: 'abc'}, {...}]
        */
        makeArray: function (data) {
            var count, obj, result = [], item, iterateItem;
            if (!data || typeof data === 'string') {
                return null;
            }

            if ($.isArray(data)) { //array
                /* 
                   function to iterate inside item of array if item is object.
                   Caclulates count of keys in item and store in obj. 
                */
                iterateItem = function (k, v) {
                    obj = { value: k, text: v };
                    if (count++ >= 2) {
                        return false;// exit from `each` if item has more than one key.
                    }
                };

                for (var i = 0; i < data.length; i++) {
                    item = data[i];
                    if (typeof item === 'object') {
                        count = 0; //count of keys inside item
                        $.each(item, iterateItem);
                        //case: [{val1: 'text1'}, {val2: 'text2} ...]
                        if (count === 1) {
                            result.push(obj);
                            //case: [{value: 1, text: 'text1'}, {value: 2, text: 'text2'}, ...]
                        } else if (count > 1) {
                            //removed check of existance: item.hasOwnProperty('value') && item.hasOwnProperty('text')
                            if (item.children) {
                                item.children = this.makeArray(item.children);
                            }
                            result.push(item);
                        }
                    } else {
                        //case: ['text1', 'text2' ...]
                        result.push({ value: item, text: item });
                    }
                }
            } else {  //case: {val1: 'text1', val2: 'text2, ...}
                $.each(data, function (k, v) {
                    result.push({ value: k, text: v });
                });
            }
            return result;
        },

        option: function (key, value) {
            this.options[key] = value;
            if (key === 'source') {
                this.sourceData = null;
            }
            if (key === 'prepend') {
                this.prependData = null;
            }
        }

    });

    List.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
        /**
        Source data for list.  
        If **array** - it should be in format: `[{value: 1, text: "text1"}, {value: 2, text: "text2"}, ...]`  
        For compability, object format is also supported: `{"1": "text1", "2": "text2" ...}` but it does not guarantee elements order.
        
        If **string** - considered ajax url to load items. In that case results will be cached for fields with the same source and name. See also `sourceCache` option.
          
        If **function**, it should return data in format above (since 1.4.0).
        
        Since 1.4.1 key `children` supported to render OPTGROUP (for **select** input only).  
        `[{text: "group1", children: [{value: 1, text: "text1"}, {value: 2, text: "text2"}]}, ...]` 

		
        @property source 
        @type string | array | object | function
        @default null
        **/
        source: null,
        /**
        Data automatically prepended to the beginning of dropdown list.
        
        @property prepend 
        @type string | array | object | function
        @default false
        **/
        prepend: false,
        /**
        Error message when list cannot be loaded (e.g. ajax error)
        
        @property sourceError 
        @type string
        @default Error when loading list
        **/
        sourceError: 'Error when loading list',
        /**
        if <code>true</code> and source is **string url** - results will be cached for fields with the same source.    
        Usefull for editable column in grid to prevent extra requests.
        
        @property sourceCache 
        @type boolean
        @default true
        @since 1.2.0
        **/
        sourceCache: true,
        /**
        Additional ajax options to be used in $.ajax() when loading list from server.
        Useful to send extra parameters (`data` key) or change request method (`type` key).
        
        @property sourceOptions 
        @type object|function
        @default null
        @since 1.5.0
        **/
        sourceOptions: null
    });

    $.fn.editabletypes.list = List;

}(window.jQuery));

/**
Text input

@class text
@extends abstractinput
@final
@example
<a href="#" id="username" data-type="text" data-pk="1">awesome</a>
<script>
$(function(){
    $('#username').editable({
        url: '/post',
        title: 'Enter username'
    });
});
</script>
**/
(function ($) {
    "use strict";

    var Text = function (options) {
        this.init('text', options, Text.defaults);
    };

    $.fn.editableutils.inherit(Text, $.fn.editabletypes.abstractinput);

    $.extend(Text.prototype, {
        render: function () {
            this.renderClear();
            this.setClass();
            this.setAttr('placeholder');
        },

        activate: function () {
            if (this.$input.is(':visible')) {
                this.$input.focus();
                $.fn.editableutils.setCursorPosition(this.$input.get(0), this.$input.val().length);
                if (this.toggleClear) {
                    this.toggleClear();
                }
            }
        },

        //render clear button
        renderClear: function () {
            if (this.options.clear) {
                this.$clear = $('<span class="editable-clear-x"></span>');
                this.$input.after(this.$clear)
                    .css('padding-right', 24)
                    .keyup($.proxy(function (e) {
                        //arrows, enter, tab, etc
                        if (~$.inArray(e.keyCode, [40, 38, 9, 13, 27])) {
                            return;
                        }

                        clearTimeout(this.t);
                        var that = this;
                        this.t = setTimeout(function () {
                            that.toggleClear(e);
                        }, 100);

                    }, this))
                    .parent().css('position', 'relative');

                this.$clear.click($.proxy(this.clear, this));
            }
        },

        postrender: function () {
            /*
            //now `clear` is positioned via css
            if(this.$clear) {
                //can position clear button only here, when form is shown and height can be calculated
//                var h = this.$input.outerHeight(true) || 20,
                var h = this.$clear.parent().height(),
                    delta = (h - this.$clear.height()) / 2;
                    
                //this.$clear.css({bottom: delta, right: delta});
            }
            */
        },

        //show / hide clear button
        toggleClear: function (e) {
            if (!this.$clear) {
                return;
            }

            var len = this.$input.val().length,
                visible = this.$clear.is(':visible');

            if (len && !visible) {
                this.$clear.show();
            }

            if (!len && visible) {
                this.$clear.hide();
            }
        },

        clear: function () {
            this.$clear.hide();
            this.$input.val('').focus();
        }
    });

    Text.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
        /**
        @property tpl 
        @default <input type="text">
        **/
        tpl: '<input type="text">',
        /**
        Placeholder attribute of input. Shown when input is empty.

        @property placeholder 
        @type string
        @default null
        **/
        placeholder: null,

        /**
        Whether to show `clear` button 
        
        @property clear 
        @type boolean
        @default true        
        **/
        clear: true
    });

    $.fn.editabletypes.text = Text;

}(window.jQuery));

/**
Textarea input

@class textarea
@extends abstractinput
@final
@example
<a href="#" id="comments" data-type="textarea" data-pk="1">awesome comment!</a>
<script>
$(function(){
    $('#comments').editable({
        url: '/post',
        title: 'Enter comments',
        rows: 10
    });
});
</script>
**/
(function ($) {
    "use strict";

    var Textarea = function (options) {
        this.init('textarea', options, Textarea.defaults);
    };

    $.fn.editableutils.inherit(Textarea, $.fn.editabletypes.abstractinput);

    $.extend(Textarea.prototype, {
        render: function () {
            this.setClass();
            this.setAttr('placeholder');
            this.setAttr('rows');

            //ctrl + enter
            this.$input.keydown(function (e) {
                if (e.ctrlKey && e.which === 13) {
                    $(this).closest('form').submit();
                }
            });
        },

        //using `white-space: pre-wrap` solves \n  <--> BR conversion very elegant!
        /* 
        value2html: function(value, element) {
             var html = '', lines;
             if(value) {
                 lines = value.split("\n");
                 for (var i = 0; i < lines.length; i++) {
                     lines[i] = $('<div>').text(lines[i]).html();
                 }
                 html = lines.join('<br>');
             }
             $(element).html(html);
         },
        
         html2value: function(html) {
             if(!html) {
                 return '';
             }
 
             var regex = new RegExp(String.fromCharCode(10), 'g');
             var lines = html.split(/<br\s*\/?>/i);
             for (var i = 0; i < lines.length; i++) {
                 var text = $('<div>').html(lines[i]).text();
 
                 // Remove newline characters (\n) to avoid them being converted by value2html() method
                 // thus adding extra <br> tags
                 text = text.replace(regex, '');
 
                 lines[i] = text;
             }
             return lines.join("\n");
         },
          */
        activate: function () {
            $.fn.editabletypes.text.prototype.activate.call(this);
        }
    });

    Textarea.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
        /**
        @property tpl
        @default <textarea></textarea>
        **/
        tpl: '<textarea></textarea>',
        /**
        @property inputclass
        @default input-large
        **/
        inputclass: 'input-large',
        /**
        Placeholder attribute of input. Shown when input is empty.

        @property placeholder
        @type string
        @default null
        **/
        placeholder: null,
        /**
        Number of rows in textarea

        @property rows
        @type integer
        @default 7
        **/
        rows: 7
    });

    $.fn.editabletypes.textarea = Textarea;

}(window.jQuery));

/**
Select (dropdown)

@class select
@extends list
@final
@example
<a href="#" id="status" data-type="select" data-pk="1" data-url="/post" data-title="Select status"></a>
<script>
$(function(){
    $('#status').editable({
        value: 2,    
        source: [
              {value: 1, text: 'Active'},
              {value: 2, text: 'Blocked'},
              {value: 3, text: 'Deleted'}
           ]
    });
});
</script>
**/
(function ($) {
    "use strict";

    var Select = function (options) {
        this.init('select', options, Select.defaults);
    };

    $.fn.editableutils.inherit(Select, $.fn.editabletypes.list);

    $.extend(Select.prototype, {
        renderList: function () {
            this.$input.empty();

            var fillItems = function ($el, data) {
                var attr;
                if ($.isArray(data)) {
                    for (var i = 0; i < data.length; i++) {
                        attr = {};
                        if (data[i].children) {
                            attr.label = data[i].text;
                            $el.append(fillItems($('<optgroup>', attr), data[i].children));
                        } else {
                            attr.value = data[i].value;
                            if (data[i].disabled) {
                                attr.disabled = true;
                            }
                            $el.append($('<option>', attr).text(data[i].text));
                        }
                    }
                }
                return $el;
            };

            fillItems(this.$input, this.sourceData);

            this.setClass();

            //enter submit
            this.$input.on('keydown.editable', function (e) {
                if (e.which === 13) {
                    $(this).closest('form').submit();
                }
            });
        },

        value2htmlFinal: function (value, element) {
            var text = '',
                items = $.fn.editableutils.itemsByValue(value, this.sourceData);

            if (items.length) {
                text = items[0].text;
            }

            //$(element).text(text);
            $.fn.editabletypes.abstractinput.prototype.value2html.call(this, text, element);
        },

        autosubmit: function () {
            this.$input.off('keydown.editable').on('change.editable', function () {
                $(this).closest('form').submit();
            });
        }
    });

    Select.defaults = $.extend({}, $.fn.editabletypes.list.defaults, {
        /**
        @property tpl 
        @default <select></select>
        **/
        tpl: '<select></select>'
    });

    $.fn.editabletypes.select = Select;

}(window.jQuery));

/**
List of checkboxes. 
Internally value stored as javascript array of values.

@class checklist
@extends list
@final
@example
<a href="#" id="options" data-type="checklist" data-pk="1" data-url="/post" data-title="Select options"></a>
<script>
$(function(){
    $('#options').editable({
        value: [2, 3],    
        source: [
              {value: 1, text: 'option1'},
              {value: 2, text: 'option2'},
              {value: 3, text: 'option3'}
           ]
    });
});
</script>
**/
(function ($) {
    "use strict";

    var Checklist = function (options) {
        this.init('checklist', options, Checklist.defaults);
    };

    $.fn.editableutils.inherit(Checklist, $.fn.editabletypes.list);

    $.extend(Checklist.prototype, {
        renderList: function () {
            var $label, $div;

            this.$tpl.empty();

            if (!$.isArray(this.sourceData)) {
                return;
            }

            for (var i = 0; i < this.sourceData.length; i++) {
                $label = $('<label>').append($('<input>', {
                    type: 'checkbox',
                    value: this.sourceData[i].value
                }))
                    .append($('<span>').text(' ' + this.sourceData[i].text));

                $('<div>').append($label).appendTo(this.$tpl);
            }

            this.$input = this.$tpl.find('input[type="checkbox"]');
            this.setClass();
        },

        value2str: function (value) {
            return $.isArray(value) ? value.sort().join($.trim(this.options.separator)) : '';
        },

        //parse separated string
        str2value: function (str) {
            var reg, value = null;
            if (typeof str === 'string' && str.length) {
                reg = new RegExp('\\s*' + $.trim(this.options.separator) + '\\s*');
                value = str.split(reg);
            } else if ($.isArray(str)) {
                value = str;
            } else {
                value = [str];
            }
            return value;
        },

        //set checked on required checkboxes
        value2input: function (value) {
            this.$input.prop('checked', false);
            if ($.isArray(value) && value.length) {
                this.$input.each(function (i, el) {
                    var $el = $(el);
                    // cannot use $.inArray as it performs strict comparison
                    $.each(value, function (j, val) {
                        /*jslint eqeq: true*/
                        if ($el.val() == val) {
                            /*jslint eqeq: false*/
                            $el.prop('checked', true);
                        }
                    });
                });
            }
        },

        input2value: function () {
            var checked = [];
            this.$input.filter(':checked').each(function (i, el) {
                checked.push($(el).val());
            });
            return checked;
        },

        //collect text of checked boxes
        value2htmlFinal: function (value, element) {
            var html = [],
                checked = $.fn.editableutils.itemsByValue(value, this.sourceData),
                escape = this.options.escape;

            if (checked.length) {
                $.each(checked, function (i, v) {
                    var text = escape ? $.fn.editableutils.escape(v.text) : v.text;
                    html.push(text);
                });
                $(element).html(html.join('<br>'));
            } else {
                $(element).empty();
            }
        },

        activate: function () {
            this.$input.first().focus();
        },

        autosubmit: function () {
            this.$input.on('keydown', function (e) {
                if (e.which === 13) {
                    $(this).closest('form').submit();
                }
            });
        }
    });

    Checklist.defaults = $.extend({}, $.fn.editabletypes.list.defaults, {
        /**
        @property tpl 
        @default <div></div>
        **/
        tpl: '<div class="editable-checklist"></div>',

        /**
        @property inputclass 
        @type string
        @default null
        **/
        inputclass: null,

        /**
        Separator of values when reading from `data-value` attribute

        @property separator 
        @type string
        @default ','
        **/
        separator: ','
    });

    $.fn.editabletypes.checklist = Checklist;

}(window.jQuery));

/**
HTML5 input types.
Following types are supported:

* password
* email
* url
* tel
* number
* range
* time

Learn more about html5 inputs:  
http://www.w3.org/wiki/HTML5_form_additions  
To check browser compatibility please see:  
https://developer.mozilla.org/en-US/docs/HTML/Element/Input
            
@class html5types 
@extends text
@final
@since 1.3.0
@example
<a href="#" id="email" data-type="email" data-pk="1">admin@example.com</a>
<script>
$(function(){
    $('#email').editable({
        url: '/post',
        title: 'Enter email'
    });
});
</script>
**/

/**
@property tpl 
@default depends on type
**/

/*
Password
*/
(function ($) {
    "use strict";

    var Password = function (options) {
        this.init('password', options, Password.defaults);
    };
    $.fn.editableutils.inherit(Password, $.fn.editabletypes.text);
    $.extend(Password.prototype, {
        //do not display password, show '[hidden]' instead
        value2html: function (value, element) {
            if (value) {
                $(element).text('[hidden]');
            } else {
                $(element).empty();
            }
        },
        //as password not displayed, should not set value by html
        html2value: function (html) {
            return null;
        }
    });
    Password.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
        tpl: '<input type="password">'
    });
    $.fn.editabletypes.password = Password;
}(window.jQuery));


/*
Email
*/
(function ($) {
    "use strict";

    var Email = function (options) {
        this.init('email', options, Email.defaults);
    };
    $.fn.editableutils.inherit(Email, $.fn.editabletypes.text);
    Email.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
        tpl: '<input type="email">'
    });
    $.fn.editabletypes.email = Email;
}(window.jQuery));


/*
Url
*/
(function ($) {
    "use strict";

    var Url = function (options) {
        this.init('url', options, Url.defaults);
    };
    $.fn.editableutils.inherit(Url, $.fn.editabletypes.text);
    Url.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
        tpl: '<input type="url">'
    });
    $.fn.editabletypes.url = Url;
}(window.jQuery));


/*
Tel
*/
(function ($) {
    "use strict";

    var Tel = function (options) {
        this.init('tel', options, Tel.defaults);
    };
    $.fn.editableutils.inherit(Tel, $.fn.editabletypes.text);
    Tel.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
        tpl: '<input type="tel">'
    });
    $.fn.editabletypes.tel = Tel;
}(window.jQuery));


/*
Number
*/
(function ($) {
    "use strict";

    var NumberInput = function (options) {
        this.init('number', options, NumberInput.defaults);
    };
    $.fn.editableutils.inherit(NumberInput, $.fn.editabletypes.text);
    $.extend(NumberInput.prototype, {
        render: function () {
            NumberInput.superclass.render.call(this);
            this.setAttr('min');
            this.setAttr('max');
            this.setAttr('step');
        },
        postrender: function () {
            if (this.$clear) {
                //increase right ffset  for up/down arrows
                this.$clear.css({ right: 24 });
                /*
                //can position clear button only here, when form is shown and height can be calculated
                var h = this.$input.outerHeight(true) || 20,
                    delta = (h - this.$clear.height()) / 2;
                
                //add 12px to offset right for up/down arrows    
                this.$clear.css({top: delta, right: delta + 16});
                */
            }
        }
    });
    NumberInput.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
        tpl: '<input type="number">',
        inputclass: 'input-mini',
        min: null,
        max: null,
        step: null
    });
    $.fn.editabletypes.number = NumberInput;
}(window.jQuery));


/*
Range (inherit from number)
*/
(function ($) {
    "use strict";

    var Range = function (options) {
        this.init('range', options, Range.defaults);
    };
    $.fn.editableutils.inherit(Range, $.fn.editabletypes.number);
    $.extend(Range.prototype, {
        render: function () {
            this.$input = this.$tpl.filter('input');

            this.setClass();
            this.setAttr('min');
            this.setAttr('max');
            this.setAttr('step');

            this.$input.on('input', function () {
                $(this).siblings('output').text($(this).val());
            });
        },
        activate: function () {
            this.$input.focus();
        }
    });
    Range.defaults = $.extend({}, $.fn.editabletypes.number.defaults, {
        tpl: '<input type="range"><output style="width: 30px; display: inline-block"></output>',
        inputclass: 'input-medium'
    });
    $.fn.editabletypes.range = Range;
}(window.jQuery));

/*
Time
*/
(function ($) {
    "use strict";

    var Time = function (options) {
        this.init('time', options, Time.defaults);
    };
    //inherit from abstract, as inheritance from text gives selection error.
    $.fn.editableutils.inherit(Time, $.fn.editabletypes.abstractinput);
    $.extend(Time.prototype, {
        render: function () {
            this.setClass();
        }
    });
    Time.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
        tpl: '<input type="time">'
    });
    $.fn.editabletypes.time = Time;
}(window.jQuery));

/**
Select2 input. Based on amazing work of Igor Vaynberg https://github.com/ivaynberg/select2.  
Please see [original select2 docs](http://ivaynberg.github.com/select2) for detailed description and options.  
 
You should manually download and include select2 distributive:  

    <link href="select2/select2.css" rel="stylesheet" type="text/css"></link>  
    <script src="select2/select2.js"></script>  
    
To make it **bootstrap-styled** you can use css from [here](https://github.com/t0m/select2-bootstrap-css): 

    <link href="select2-bootstrap.css" rel="stylesheet" type="text/css"></link>    
    
**Note:** currently `autotext` feature does not work for select2 with `ajax` remote source.    
You need initially put both `data-value` and element's text youself:    

    <a href="#" data-type="select2" data-value="1">Text1</a>
    
    
@class select2
@extends abstractinput
@since 1.4.1
@final
@example
<a href="#" id="country" data-type="select2" data-pk="1" data-value="ru" data-url="/post" data-title="Select country"></a>
<script>
$(function(){
    //local source
    $('#country').editable({
        source: [
              {id: 'gb', text: 'Great Britain'},
              {id: 'us', text: 'United States'},
              {id: 'ru', text: 'Russia'}
           ],
        select2: {
           multiple: true
        }
    });
    //remote source (simple)
    $('#country').editable({
        source: '/getCountries',
        select2: {
            placeholder: 'Select Country',
            minimumInputLength: 1
        }
    });
    //remote source (advanced)
    $('#country').editable({
        select2: {
            placeholder: 'Select Country',
            allowClear: true,
            minimumInputLength: 3,
            id: function (item) {
                return item.CountryId;
            },
            ajax: {
                url: '/getCountries',
                dataType: 'json',
                data: function (term, page) {
                    return { query: term };
                },
                results: function (data, page) {
                    return { results: data };
                }
            },
            formatResult: function (item) {
                return item.CountryName;
            },
            formatSelection: function (item) {
                return item.CountryName;
            },
            initSelection: function (element, callback) {
                return $.get('/getCountryById', { query: element.val() }, function (data) {
                    callback(data);
                });
            } 
        }  
    });
});
</script>
**/
(function ($) {
    "use strict";

    var Constructor = function (options) {
        this.init('select2', options, Constructor.defaults);

        options.select2 = options.select2 || {};

        this.sourceData = null;

        //placeholder
        if (options.placeholder) {
            options.select2.placeholder = options.placeholder;
        }

        //if not `tags` mode, use source
        if (!options.select2.tags && options.source) {
            var source = options.source;
            //if source is function, call it (once!)
            if ($.isFunction(options.source)) {
                source = options.source.call(options.scope);
            }

            if (typeof source === 'string') {
                options.select2.ajax = options.select2.ajax || {};
                //some default ajax params
                if (!options.select2.ajax.data) {
                    options.select2.ajax.data = function (term) { return { query: term }; };
                }
                if (!options.select2.ajax.results) {
                    options.select2.ajax.results = function (data) { return { results: data }; };
                }
                options.select2.ajax.url = source;
            } else {
                //check format and convert x-editable format to select2 format (if needed)
                this.sourceData = this.convertSource(source);
                options.select2.data = this.sourceData;
            }
        }

        //overriding objects in config (as by default jQuery extend() is not recursive)
        this.options.select2 = $.extend({}, Constructor.defaults.select2, options.select2);

        //detect whether it is multi-valued
        this.isMultiple = this.options.select2.tags || this.options.select2.multiple;
        this.isRemote = ('ajax' in this.options.select2);

        //store function returning ID of item
        //should be here as used inautotext for local source
        this.idFunc = this.options.select2.id;
        if (typeof (this.idFunc) !== "function") {
            var idKey = this.idFunc || 'id';
            this.idFunc = function (e) { return e[idKey]; };
        }

        //store function that renders text in select2
        this.formatSelection = this.options.select2.formatSelection;
        if (typeof (this.formatSelection) !== "function") {
            this.formatSelection = function (e) { return e.text; };
        }
    };

    $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput);

    $.extend(Constructor.prototype, {
        render: function () {
            this.setClass();

            //can not apply select2 here as it calls initSelection 
            //over input that does not have correct value yet.
            //apply select2 only in value2input
            //this.$input.select2(this.options.select2);

            //when data is loaded via ajax, we need to know when it's done to populate listData
            if (this.isRemote) {
                //listen to loaded event to populate data
                this.$input.on('select2-loaded', $.proxy(function (e) {
                    this.sourceData = e.items.results;
                }, this));
            }

            //trigger resize of editableform to re-position container in multi-valued mode
            if (this.isMultiple) {
                this.$input.on('change', function () {
                    $(this).closest('form').parent().triggerHandler('resize');
                });
            }
        },

        value2html: function (value, element) {
            var text = '', data,
                that = this;

            if (this.options.select2.tags) { //in tags mode just assign value
                data = value;
                //data = $.fn.editableutils.itemsByValue(value, this.options.select2.tags, this.idFunc);
            } else if (this.sourceData) {
                data = $.fn.editableutils.itemsByValue(value, this.sourceData, this.idFunc);
            } else {
                //can not get list of possible values 
                //(e.g. autotext for select2 with ajax source)
            }

            //data may be array (when multiple values allowed)
            if ($.isArray(data)) {
                //collect selected data and show with separator
                text = [];
                $.each(data, function (k, v) {
                    text.push(v && typeof v === 'object' ? that.formatSelection(v) : v);
                });
            } else if (data) {
                text = that.formatSelection(data);
            }

            text = $.isArray(text) ? text.join(this.options.viewseparator) : text;

            //$(element).text(text);
            Constructor.superclass.value2html.call(this, text, element);
        },

        html2value: function (html) {
            return this.options.select2.tags ? this.str2value(html, this.options.viewseparator) : null;
        },

        value2input: function (value) {
            // if value array => join it anyway
            if ($.isArray(value)) {
                value = value.join(this.getSeparator());
            }

            //for remote source just set value, text is updated by initSelection
            if (!this.$input.data('select2')) {
                this.$input.val(value);
                this.$input.select2(this.options.select2);
            } else {
                //second argument needed to separate initial change from user's click (for autosubmit)   
                this.$input.val(value).trigger('change', true);

                //Uncaught Error: cannot call val() if initSelection() is not defined
                //this.$input.select2('val', value);
            }

            // if defined remote source AND no multiple mode AND no user's initSelection provided --> 
            // we should somehow get text for provided id.
            // The solution is to use element's text as text for that id (exclude empty)
            if (this.isRemote && !this.isMultiple && !this.options.select2.initSelection) {
                // customId and customText are methods to extract `id` and `text` from data object
                // we can use this workaround only if user did not define these methods
                // otherwise we cant construct data object
                var customId = this.options.select2.id,
                    customText = this.options.select2.formatSelection;

                if (!customId && !customText) {
                    var $el = $(this.options.scope);
                    if (!$el.data('editable').isEmpty) {
                        var data = { id: value, text: $el.text() };
                        this.$input.select2('data', data);
                    }
                }
            }
        },

        input2value: function () {
            return this.$input.select2('val');
        },

        str2value: function (str, separator) {
            if (typeof str !== 'string' || !this.isMultiple) {
                return str;
            }

            separator = separator || this.getSeparator();

            var val, i, l;

            if (str === null || str.length < 1) {
                return null;
            }
            val = str.split(separator);
            for (i = 0, l = val.length; i < l; i = i + 1) {
                val[i] = $.trim(val[i]);
            }

            return val;
        },

        autosubmit: function () {
            this.$input.on('change', function (e, isInitial) {
                if (!isInitial) {
                    $(this).closest('form').submit();
                }
            });
        },

        getSeparator: function () {
            return this.options.select2.separator || $.fn.select2.defaults.separator;
        },

        /*
        Converts source from x-editable format: {value: 1, text: "1"} to
        select2 format: {id: 1, text: "1"}
        */
        convertSource: function (source) {
            if ($.isArray(source) && source.length && source[0].value !== undefined) {
                for (var i = 0; i < source.length; i++) {
                    if (source[i].value !== undefined) {
                        source[i].id = source[i].value;
                        delete source[i].value;
                    }
                }
            }
            return source;
        },

        destroy: function () {
            if (this.$input.data('select2')) {
                this.$input.select2('destroy');
            }
        }

    });

    Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
        /**
        @property tpl 
        @default <input type="hidden">
        **/
        tpl: '<input type="hidden">',
        /**
        Configuration of select2. [Full list of options](http://ivaynberg.github.com/select2).

        @property select2 
        @type object
        @default null
        **/
        select2: null,
        /**
        Placeholder attribute of select

        @property placeholder 
        @type string
        @default null
        **/
        placeholder: null,
        /**
        Source data for select. It will be assigned to select2 `data` property and kept here just for convenience.
        Please note, that format is different from simple `select` input: use 'id' instead of 'value'.
        E.g. `[{id: 1, text: "text1"}, {id: 2, text: "text2"}, ...]`.

        @property source 
        @type array|string|function
        @default null        
        **/
        source: null,
        /**
        Separator used to display tags.

        @property viewseparator 
        @type string
        @default ', '        
        **/
        viewseparator: ', '
    });

    $.fn.editabletypes.select2 = Constructor;

}(window.jQuery));

/**
* Combodate - 1.0.5
* Dropdown date and time picker.
* Converts text input into dropdowns to pick day, month, year, hour, minute and second.
* Uses momentjs as datetime library http://momentjs.com.
* For i18n include corresponding file from https://github.com/timrwood/moment/tree/master/lang 
*
* Confusion at noon and midnight - see http://en.wikipedia.org/wiki/12-hour_clock#Confusion_at_noon_and_midnight
* In combodate: 
* 12:00 pm --> 12:00 (24-h format, midday)
* 12:00 am --> 00:00 (24-h format, midnight, start of day)
* 
* Differs from momentjs parse rules:
* 00:00 pm, 12:00 pm --> 12:00 (24-h format, day not change)
* 00:00 am, 12:00 am --> 00:00 (24-h format, day not change)
* 
* 
* Author: Vitaliy Potapov
* Project page: http://github.com/vitalets/combodate
* Copyright (c) 2012 Vitaliy Potapov. Released under MIT License.
**/
(function ($) {

    var Combodate = function (element, options) {
        this.$element = $(element);
        if (!this.$element.is('input')) {
            $.error('Combodate should be applied to INPUT element');
            return;
        }
        this.options = $.extend({}, $.fn.combodate.defaults, options, this.$element.data());
        this.init();
    };

    Combodate.prototype = {
        constructor: Combodate,
        init: function () {
            this.map = {
                //key   regexp    moment.method
                day: ['D', 'date'],
                month: ['M', 'month'],
                year: ['Y', 'year'],
                hour: ['[Hh]', 'hours'],
                minute: ['m', 'minutes'],
                second: ['s', 'seconds'],
                ampm: ['[Aa]', '']
            };

            this.$widget = $('<span class="combodate"></span>').html(this.getTemplate());

            this.initCombos();

            //update original input on change 
            this.$widget.on('change', 'select', $.proxy(function (e) {
                this.$element.val(this.getValue()).change();
                // update days count if month or year changes
                if (this.options.smartDays) {
                    if ($(e.target).is('.month') || $(e.target).is('.year')) {
                        this.fillCombo('day');
                    }
                }
            }, this));

            this.$widget.find('select').css('width', 'auto');

            // hide original input and insert widget                                       
            this.$element.hide().after(this.$widget);

            // set initial value
            this.setValue(this.$element.val() || this.options.value);
        },

        /*
         Replace tokens in template with <select> elements 
        */
        getTemplate: function () {
            var tpl = this.options.template;

            //first pass
            $.each(this.map, function (k, v) {
                v = v[0];
                var r = new RegExp(v + '+'),
                    token = v.length > 1 ? v.substring(1, 2) : v;

                tpl = tpl.replace(r, '{' + token + '}');
            });

            //replace spaces with &nbsp;
            tpl = tpl.replace(/ /g, '&nbsp;');

            //second pass
            $.each(this.map, function (k, v) {
                v = v[0];
                var token = v.length > 1 ? v.substring(1, 2) : v;

                tpl = tpl.replace('{' + token + '}', '<select class="' + k + '"></select>');
            });

            return tpl;
        },

        /*
         Initialize combos that presents in template 
        */
        initCombos: function () {
            for (var k in this.map) {
                var $c = this.$widget.find('.' + k);
                // set properties like this.$day, this.$month etc.
                this['$' + k] = $c.length ? $c : null;
                // fill with items
                this.fillCombo(k);
            }
        },

        /*
         Fill combo with items 
        */
        fillCombo: function (k) {
            var $combo = this['$' + k];
            if (!$combo) {
                return;
            }

            // define method name to fill items, e.g `fillDays`
            var f = 'fill' + k.charAt(0).toUpperCase() + k.slice(1);
            var items = this[f]();
            var value = $combo.val();

            $combo.empty();
            for (var i = 0; i < items.length; i++) {
                $combo.append('<option value="' + items[i][0] + '">' + items[i][1] + '</option>');
            }

            $combo.val(value);
        },

        /*
         Initialize items of combos. Handles `firstItem` option 
        */
        fillCommon: function (key) {
            var values = [],
                relTime;

            if (this.options.firstItem === 'name') {
                //need both to support moment ver < 2 and  >= 2
                relTime = moment.relativeTime || moment.langData()._relativeTime;
                var header = typeof relTime[key] === 'function' ? relTime[key](1, true, key, false) : relTime[key];
                //take last entry (see momentjs lang files structure) 
                header = header.split(' ').reverse()[0];
                values.push(['', header]);
            } else if (this.options.firstItem === 'empty') {
                values.push(['', '']);
            }
            return values;
        },


        /*
        fill day
        */
        fillDay: function () {
            var items = this.fillCommon('d'), name, i,
                twoDigit = this.options.template.indexOf('DD') !== -1,
                daysCount = 31;

            // detect days count (depends on month and year)
            // originally https://github.com/vitalets/combodate/pull/7
            if (this.options.smartDays && this.$month && this.$year) {
                var month = parseInt(this.$month.val(), 10);
                var year = parseInt(this.$year.val(), 10);

                if (!isNaN(month) && !isNaN(year)) {
                    daysCount = moment([year, month]).daysInMonth();
                }
            }

            for (i = 1; i <= daysCount; i++) {
                name = twoDigit ? this.leadZero(i) : i;
                items.push([i, name]);
            }
            return items;
        },

        /*
        fill month
        */
        fillMonth: function () {
            var items = this.fillCommon('M'), name, i,
                longNames = this.options.template.indexOf('MMMM') !== -1,
                shortNames = this.options.template.indexOf('MMM') !== -1,
                twoDigit = this.options.template.indexOf('MM') !== -1;

            for (i = 0; i <= 11; i++) {
                if (longNames) {
                    //see https://github.com/timrwood/momentjs.com/pull/36
                    name = moment().date(1).month(i).format('MMMM');
                } else if (shortNames) {
                    name = moment().date(1).month(i).format('MMM');
                } else if (twoDigit) {
                    name = this.leadZero(i + 1);
                } else {
                    name = i + 1;
                }
                items.push([i, name]);
            }
            return items;
        },

        /*
        fill year
        */
        fillYear: function () {
            var items = [], name, i,
                longNames = this.options.template.indexOf('YYYY') !== -1;

            for (i = this.options.maxYear; i >= this.options.minYear; i--) {
                name = longNames ? i : (i + '').substring(2);
                items[this.options.yearDescending ? 'push' : 'unshift']([i, name]);
            }

            items = this.fillCommon('y').concat(items);

            return items;
        },

        /*
        fill hour
        */
        fillHour: function () {
            var items = this.fillCommon('h'), name, i,
                h12 = this.options.template.indexOf('h') !== -1,
                h24 = this.options.template.indexOf('H') !== -1,
                twoDigit = this.options.template.toLowerCase().indexOf('hh') !== -1,
                min = h12 ? 1 : 0,
                max = h12 ? 12 : 23;

            for (i = min; i <= max; i++) {
                name = twoDigit ? this.leadZero(i) : i;
                items.push([i, name]);
            }
            return items;
        },

        /*
        fill minute
        */
        fillMinute: function () {
            var items = this.fillCommon('m'), name, i,
                twoDigit = this.options.template.indexOf('mm') !== -1;

            for (i = 0; i <= 59; i += this.options.minuteStep) {
                name = twoDigit ? this.leadZero(i) : i;
                items.push([i, name]);
            }
            return items;
        },

        /*
        fill second
        */
        fillSecond: function () {
            var items = this.fillCommon('s'), name, i,
                twoDigit = this.options.template.indexOf('ss') !== -1;

            for (i = 0; i <= 59; i += this.options.secondStep) {
                name = twoDigit ? this.leadZero(i) : i;
                items.push([i, name]);
            }
            return items;
        },

        /*
        fill ampm
        */
        fillAmpm: function () {
            var ampmL = this.options.template.indexOf('a') !== -1,
                ampmU = this.options.template.indexOf('A') !== -1,
                items = [
                    ['am', ampmL ? 'am' : 'AM'],
                    ['pm', ampmL ? 'pm' : 'PM']
                ];
            return items;
        },

        /*
         Returns current date value from combos. 
         If format not specified - `options.format` used.
         If format = `null` - Moment object returned.
        */
        getValue: function (format) {
            var dt, values = {},
                that = this,
                notSelected = false;

            //getting selected values    
            $.each(this.map, function (k, v) {
                if (k === 'ampm') {
                    return;
                }
                var def = k === 'day' ? 1 : 0;

                values[k] = that['$' + k] ? parseInt(that['$' + k].val(), 10) : def;

                if (isNaN(values[k])) {
                    notSelected = true;
                    return false;
                }
            });

            //if at least one visible combo not selected - return empty string
            if (notSelected) {
                return '';
            }

            //convert hours 12h --> 24h 
            if (this.$ampm) {
                //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day)
                if (values.hour === 12) {
                    values.hour = this.$ampm.val() === 'am' ? 0 : 12;
                } else {
                    values.hour = this.$ampm.val() === 'am' ? values.hour : values.hour + 12;
                }
            }

            dt = moment([values.year, values.month, values.day, values.hour, values.minute, values.second]);

            //highlight invalid date
            this.highlight(dt);

            format = format === undefined ? this.options.format : format;
            if (format === null) {
                return dt.isValid() ? dt : null;
            } else {
                return dt.isValid() ? dt.format(format) : '';
            }
        },

        setValue: function (value) {
            if (!value) {
                return;
            }

            var dt = typeof value === 'string' ? moment(value, this.options.format) : moment(value),
                that = this,
                values = {};

            //function to find nearest value in select options
            function getNearest($select, value) {
                var delta = {};
                $select.children('option').each(function (i, opt) {
                    var optValue = $(opt).attr('value'),
                        distance;

                    if (optValue === '') return;
                    distance = Math.abs(optValue - value);
                    if (typeof delta.distance === 'undefined' || distance < delta.distance) {
                        delta = { value: optValue, distance: distance };
                    }
                });
                return delta.value;
            }

            if (dt.isValid()) {
                //read values from date object
                $.each(this.map, function (k, v) {
                    if (k === 'ampm') {
                        return;
                    }
                    values[k] = dt[v[1]]();
                });

                if (this.$ampm) {
                    //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day)
                    if (values.hour >= 12) {
                        values.ampm = 'pm';
                        if (values.hour > 12) {
                            values.hour -= 12;
                        }
                    } else {
                        values.ampm = 'am';
                        if (values.hour === 0) {
                            values.hour = 12;
                        }
                    }
                }

                $.each(values, function (k, v) {
                    //call val() for each existing combo, e.g. this.$hour.val()
                    if (that['$' + k]) {

                        if (k === 'minute' && that.options.minuteStep > 1 && that.options.roundTime) {
                            v = getNearest(that['$' + k], v);
                        }

                        if (k === 'second' && that.options.secondStep > 1 && that.options.roundTime) {
                            v = getNearest(that['$' + k], v);
                        }

                        that['$' + k].val(v);
                    }
                });

                // update days count
                if (this.options.smartDays) {
                    this.fillCombo('day');
                }

                this.$element.val(dt.format(this.options.format)).change();
            }
        },

        /*
         highlight combos if date is invalid
        */
        highlight: function (dt) {
            if (!dt.isValid()) {
                if (this.options.errorClass) {
                    this.$widget.addClass(this.options.errorClass);
                } else {
                    //store original border color
                    if (!this.borderColor) {
                        this.borderColor = this.$widget.find('select').css('border-color');
                    }
                    this.$widget.find('select').css('border-color', 'red');
                }
            } else {
                if (this.options.errorClass) {
                    this.$widget.removeClass(this.options.errorClass);
                } else {
                    this.$widget.find('select').css('border-color', this.borderColor);
                }
            }
        },

        leadZero: function (v) {
            return v <= 9 ? '0' + v : v;
        },

        destroy: function () {
            this.$widget.remove();
            this.$element.removeData('combodate').show();
        }

        //todo: clear method        
    };

    $.fn.combodate = function (option) {
        var d, args = Array.apply(null, arguments);
        args.shift();

        //getValue returns date as string / object (not jQuery object)
        if (option === 'getValue' && this.length && (d = this.eq(0).data('combodate'))) {
            return d.getValue.apply(d, args);
        }

        return this.each(function () {
            var $this = $(this),
                data = $this.data('combodate'),
                options = typeof option == 'object' && option;
            if (!data) {
                $this.data('combodate', (data = new Combodate(this, options)));
            }
            if (typeof option == 'string' && typeof data[option] == 'function') {
                data[option].apply(data, args);
            }
        });
    };

    $.fn.combodate.defaults = {
        //in this format value stored in original input
        format: 'DD-MM-YYYY HH:mm',
        //in this format items in dropdowns are displayed
        template: 'D / MMM / YYYY   H : mm',
        //initial value, can be `new Date()`    
        value: null,
        minYear: 1970,
        maxYear: 2015,
        yearDescending: true,
        minuteStep: 5,
        secondStep: 1,
        firstItem: 'empty', //'name', 'empty', 'none'
        errorClass: null,
        roundTime: true, // whether to round minutes and seconds if step > 1
        smartDays: false // whether days in combo depend on selected month: 31, 30, 28
    };

}(window.jQuery));
/**
Combodate input - dropdown date and time picker.    
Based on [combodate](http://vitalets.github.com/combodate) plugin (included). To use it you should manually include [momentjs](http://momentjs.com).

    <script src="js/moment.min.js"></script>
   
Allows to input:

* only date
* only time 
* both date and time  

Please note, that format is taken from momentjs and **not compatible** with bootstrap-datepicker / jquery UI datepicker.  
Internally value stored as `momentjs` object. 

@class combodate
@extends abstractinput
@final
@since 1.4.0
@example
<a href="#" id="dob" data-type="combodate" data-pk="1" data-url="/post" data-value="1984-05-15" data-title="Select date"></a>
<script>
$(function(){
    $('#dob').editable({
        format: 'YYYY-MM-DD',    
        viewformat: 'DD.MM.YYYY',    
        template: 'D / MMMM / YYYY',    
        combodate: {
                minYear: 2000,
                maxYear: 2015,
                minuteStep: 1
           }
        }
    });
});
</script>
**/

/*global moment*/

(function ($) {
    "use strict";

    var Constructor = function (options) {
        this.init('combodate', options, Constructor.defaults);

        //by default viewformat equals to format
        if (!this.options.viewformat) {
            this.options.viewformat = this.options.format;
        }

        //try parse combodate config defined as json string in data-combodate
        options.combodate = $.fn.editableutils.tryParseJson(options.combodate, true);

        //overriding combodate config (as by default jQuery extend() is not recursive)
        this.options.combodate = $.extend({}, Constructor.defaults.combodate, options.combodate, {
            format: this.options.format,
            template: this.options.template
        });
    };

    $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput);

    $.extend(Constructor.prototype, {
        render: function () {
            this.$input.combodate(this.options.combodate);

            if ($.fn.editableform.engine === 'bs3') {
                this.$input.siblings().find('select').addClass('form-control');
            }

            if (this.options.inputclass) {
                this.$input.siblings().find('select').addClass(this.options.inputclass);
            }
            //"clear" link
            /*
            if(this.options.clear) {
                this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){
                    e.preventDefault();
                    e.stopPropagation();
                    this.clear();
                }, this));
                
                this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear));  
            } 
            */
        },

        value2html: function (value, element) {
            var text = value ? value.format(this.options.viewformat) : '';
            //$(element).text(text);
            Constructor.superclass.value2html.call(this, text, element);
        },

        html2value: function (html) {
            return html ? moment(html, this.options.viewformat) : null;
        },

        value2str: function (value) {
            return value ? value.format(this.options.format) : '';
        },

        str2value: function (str) {
            return str ? moment(str, this.options.format) : null;
        },

        value2submit: function (value) {
            return this.value2str(value);
        },

        value2input: function (value) {
            this.$input.combodate('setValue', value);
        },

        input2value: function () {
            return this.$input.combodate('getValue', null);
        },

        activate: function () {
            this.$input.siblings('.combodate').find('select').eq(0).focus();
        },

        /*
        clear:  function() {
           this.$input.data('datepicker').date = null;
           this.$input.find('.active').removeClass('active');
        },
        */

        autosubmit: function () {

        }

    });

    Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
        /**
        @property tpl 
        @default <input type="text">
        **/
        tpl: '<input type="text">',
        /**
        @property inputclass 
        @default null
        **/
        inputclass: null,
        /**
        Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br>
        See list of tokens in [momentjs docs](http://momentjs.com/docs/#/parsing/string-format)  
        
        @property format 
        @type string
        @default YYYY-MM-DD
        **/
        format: 'YYYY-MM-DD',
        /**
        Format used for displaying date. Also applied when converting date from element's text on init.   
        If not specified equals to `format`.
        
        @property viewformat 
        @type string
        @default null
        **/
        viewformat: null,
        /**
        Template used for displaying dropdowns.
        
        @property template 
        @type string
        @default D / MMM / YYYY
        **/
        template: 'D / MMM / YYYY',
        /**
        Configuration of combodate.
        Full list of options: http://vitalets.github.com/combodate/#docs
        
        @property combodate 
        @type object
        @default null
        **/
        combodate: null

        /*
        (not implemented yet)
        Text shown as clear date button. 
        If <code>false</code> clear button will not be rendered.
        
        @property clear 
        @type boolean|string
        @default 'x clear'         
        */
        //clear: '&times; clear'
    });

    $.fn.editabletypes.combodate = Constructor;

}(window.jQuery));

/*
Editableform based on Twitter Bootstrap 3
*/
(function ($) {
    "use strict";

    //store parent methods
    var pInitInput = $.fn.editableform.Constructor.prototype.initInput;

    $.extend($.fn.editableform.Constructor.prototype, {
        initTemplate: function () {
            this.$form = $($.fn.editableform.template);
            this.$form.find('.control-group').addClass('form-group');
            this.$form.find('.editable-error-block').addClass('help-block');
        },
        initInput: function () {
            pInitInput.apply(this);

            //for bs3 set default class `input-sm` to standard inputs
            var emptyInputClass = this.input.options.inputclass === null || this.input.options.inputclass === false;
            var defaultClass = 'input-sm';

            //bs3 add `form-control` class to standard inputs
            var stdtypes = 'text,select,textarea,password,email,url,tel,number,range,time,typeaheadjs'.split(',');
            if (~$.inArray(this.input.type, stdtypes)) {
                this.input.$input.addClass('form-control');
                if (emptyInputClass) {
                    this.input.options.inputclass = defaultClass;
                    this.input.$input.addClass(defaultClass);
                }
            }

            //apply bs3 size class also to buttons (to fit size of control)
            var $btn = this.$form.find('.editable-buttons');
            var classes = emptyInputClass ? [defaultClass] : this.input.options.inputclass.split(' ');
            for (var i = 0; i < classes.length; i++) {
                // `btn-sm` is default now
                /*
                if(classes[i].toLowerCase() === 'input-sm') { 
                    $btn.find('button').addClass('btn-sm');  
                }
                */
                if (classes[i].toLowerCase() === 'input-lg') {
                    $btn.find('button').removeClass('btn-sm').addClass('btn-lg');
                }
            }
        }
    });

    //buttons
    $.fn.editableform.buttons =
        '<button type="submit" class="btn btn-primary btn-sm editable-submit">' +
        '<i class="glyphicon glyphicon-ok"></i>' +
        '</button>' +
        '<button type="button" class="btn btn-default btn-sm editable-cancel">' +
        '<i class="glyphicon glyphicon-remove"></i>' +
        '</button>';

    //error classes
    $.fn.editableform.errorGroupClass = 'has-error';
    $.fn.editableform.errorBlockClass = null;
    //engine
    $.fn.editableform.engine = 'bs3';
}(window.jQuery));
/**
* Editable Popover3 (for Bootstrap 3) 
* ---------------------
* requires bootstrap-popover.js
*/
(function ($) {
    "use strict";

    //extend methods
    $.extend($.fn.editableContainer.Popup.prototype, {
        containerName: 'popover',
        containerDataName: 'bs.popover',
        innerCss: '.popover-content',
        defaults: $.fn.popover.Constructor.DEFAULTS,

        initContainer: function () {
            $.extend(this.containerOptions, {
                trigger: 'manual',
                selector: false,
                content: ' ',
                template: this.defaults.template
            });

            //as template property is used in inputs, hide it from popover
            var t;
            if (this.$element.data('template')) {
                t = this.$element.data('template');
                this.$element.removeData('template');
            }

            this.call(this.containerOptions);

            if (t) {
                //restore data('template')
                this.$element.data('template', t);
            }
        },

        /* show */
        innerShow: function () {
            this.call('show');
        },

        /* hide */
        innerHide: function () {
            this.call('hide');
        },

        /* destroy */
        innerDestroy: function () {
            this.call('destroy');
        },

        setContainerOption: function (key, value) {
            this.container().options[key] = value;
        },

        /**
        * move popover to new position. This function mainly copied from bootstrap-popover.
        */
        /*jshint laxcomma: true, eqeqeq: false*/
        setPosition: function () {

            (function () {
                /*    
                    var $tip = this.tip()
                    , inside
                    , pos
                    , actualWidth
                    , actualHeight
                    , placement
                    , tp
                    , tpt
                    , tpb
                    , tpl
                    , tpr;
    
                    placement = typeof this.options.placement === 'function' ?
                    this.options.placement.call(this, $tip[0], this.$element[0]) :
                    this.options.placement;
    
                    inside = /in/.test(placement);
                   
                    $tip
                  //  .detach()
                  //vitalets: remove any placement class because otherwise they dont influence on re-positioning of visible popover
                    .removeClass('top right bottom left')
                    .css({ top: 0, left: 0, display: 'block' });
                  //  .insertAfter(this.$element);
                   
                    pos = this.getPosition(inside);
    
                    actualWidth = $tip[0].offsetWidth;
                    actualHeight = $tip[0].offsetHeight;
    
                    placement = inside ? placement.split(' ')[1] : placement;
    
                    tpb = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2};
                    tpt = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2};
                    tpl = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth};
                    tpr = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width};
    
                    switch (placement) {
                        case 'bottom':
                            if ((tpb.top + actualHeight) > ($(window).scrollTop() + $(window).height())) {
                                if (tpt.top > $(window).scrollTop()) {
                                    placement = 'top';
                                } else if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) {
                                    placement = 'right';
                                } else if (tpl.left > $(window).scrollLeft()) {
                                    placement = 'left';
                                } else {
                                    placement = 'right';
                                }
                            }
                            break;
                        case 'top':
                            if (tpt.top < $(window).scrollTop()) {
                                if ((tpb.top + actualHeight) < ($(window).scrollTop() + $(window).height())) {
                                    placement = 'bottom';
                                } else if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) {
                                    placement = 'right';
                                } else if (tpl.left > $(window).scrollLeft()) {
                                    placement = 'left';
                                } else {
                                    placement = 'right';
                                }
                            }
                            break;
                        case 'left':
                            if (tpl.left < $(window).scrollLeft()) {
                                if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) {
                                    placement = 'right';
                                } else if (tpt.top > $(window).scrollTop()) {
                                    placement = 'top';
                                } else if (tpt.top > $(window).scrollTop()) {
                                    placement = 'bottom';
                                } else {
                                    placement = 'right';
                                }
                            }
                            break;
                        case 'right':
                            if ((tpr.left + actualWidth) > ($(window).scrollLeft() + $(window).width())) {
                                if (tpl.left > $(window).scrollLeft()) {
                                    placement = 'left';
                                } else if (tpt.top > $(window).scrollTop()) {
                                    placement = 'top';
                                } else if (tpt.top > $(window).scrollTop()) {
                                    placement = 'bottom';
                                }
                            }
                            break;
                    }
    
                    switch (placement) {
                        case 'bottom':
                            tp = tpb;
                            break;
                        case 'top':
                            tp = tpt;
                            break;
                        case 'left':
                            tp = tpl;
                            break;
                        case 'right':
                            tp = tpr;
                            break;
                    }
    
                    $tip
                    .offset(tp)
                    .addClass(placement)
                    .addClass('in');
               */


                var $tip = this.tip();

                var placement = typeof this.options.placement == 'function' ?
                    this.options.placement.call(this, $tip[0], this.$element[0]) :
                    this.options.placement;

                var autoToken = /\s?auto?\s?/i;
                var autoPlace = autoToken.test(placement);
                if (autoPlace) {
                    placement = placement.replace(autoToken, '') || 'top';
                }


                var pos = this.getPosition();
                var actualWidth = $tip[0].offsetWidth;
                var actualHeight = $tip[0].offsetHeight;

                if (autoPlace) {
                    var $parent = this.$element.parent();

                    var orgPlacement = placement;
                    var docScroll = document.documentElement.scrollTop || document.body.scrollTop;
                    var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth();
                    var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight();
                    var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left;

                    placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' :
                        placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' :
                            placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' :
                                placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' :
                                    placement;

                    $tip
                        .removeClass(orgPlacement)
                        .addClass(placement);
                }


                var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight);

                this.applyPlacement(calculatedOffset, placement);


            }).call(this.container());
            /*jshint laxcomma: false, eqeqeq: true*/
        }
    });

}(window.jQuery));

/* =========================================================
 * bootstrap-datepicker.js
 * http://www.eyecon.ro/bootstrap-datepicker
 * =========================================================
 * Copyright 2012 Stefan Petre
 * Improvements by Andrew Rowls
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================= */

(function ($) {

    function UTCDate() {
        return new Date(Date.UTC.apply(Date, arguments));
    }
    function UTCToday() {
        var today = new Date();
        return UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());
    }

    // Picker object

    var Datepicker = function (element, options) {
        var that = this;

        this._process_options(options);

        this.element = $(element);
        this.isInline = false;
        this.isInput = this.element.is('input');
        this.component = this.element.is('.date') ? this.element.find('.add-on, .btn') : false;
        this.hasInput = this.component && this.element.find('input').length;
        if (this.component && this.component.length === 0)
            this.component = false;

        this.picker = $(DPGlobal.template);
        this._buildEvents();
        this._attachEvents();

        if (this.isInline) {
            this.picker.addClass('datepicker-inline').appendTo(this.element);
        } else {
            this.picker.addClass('datepicker-dropdown dropdown-menu');
        }

        if (this.o.rtl) {
            this.picker.addClass('datepicker-rtl');
            this.picker.find('.prev i, .next i')
                .toggleClass('icon-arrow-left icon-arrow-right');
        }


        this.viewMode = this.o.startView;

        if (this.o.calendarWeeks)
            this.picker.find('tfoot th.today')
                .attr('colspan', function (i, val) {
                    return parseInt(val) + 1;
                });

        this._allow_update = false;

        this.setStartDate(this.o.startDate);
        this.setEndDate(this.o.endDate);
        this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled);

        this.fillDow();
        this.fillMonths();

        this._allow_update = true;

        this.update();
        this.showMode();

        if (this.isInline) {
            this.show();
        }
    };

    Datepicker.prototype = {
        constructor: Datepicker,

        _process_options: function (opts) {
            // Store raw options for reference
            this._o = $.extend({}, this._o, opts);
            // Processed options
            var o = this.o = $.extend({}, this._o);

            // Check if "de-DE" style date is available, if not language should
            // fallback to 2 letter code eg "de"
            var lang = o.language;
            if (!dates[lang]) {
                lang = lang.split('-')[0];
                if (!dates[lang])
                    lang = defaults.language;
            }
            o.language = lang;

            switch (o.startView) {
                case 2:
                case 'decade':
                    o.startView = 2;
                    break;
                case 1:
                case 'year':
                    o.startView = 1;
                    break;
                default:
                    o.startView = 0;
            }

            switch (o.minViewMode) {
                case 1:
                case 'months':
                    o.minViewMode = 1;
                    break;
                case 2:
                case 'years':
                    o.minViewMode = 2;
                    break;
                default:
                    o.minViewMode = 0;
            }

            o.startView = Math.max(o.startView, o.minViewMode);

            o.weekStart %= 7;
            o.weekEnd = ((o.weekStart + 6) % 7);

            var format = DPGlobal.parseFormat(o.format)
            if (o.startDate !== -Infinity) {
                o.startDate = DPGlobal.parseDate(o.startDate, format, o.language);
            }
            if (o.endDate !== Infinity) {
                o.endDate = DPGlobal.parseDate(o.endDate, format, o.language);
            }

            o.daysOfWeekDisabled = o.daysOfWeekDisabled || [];
            if (!$.isArray(o.daysOfWeekDisabled))
                o.daysOfWeekDisabled = o.daysOfWeekDisabled.split(/[,\s]*/);
            o.daysOfWeekDisabled = $.map(o.daysOfWeekDisabled, function (d) {
                return parseInt(d, 10);
            });
        },
        _events: [],
        _secondaryEvents: [],
        _applyEvents: function (evs) {
            for (var i = 0, el, ev; i < evs.length; i++) {
                el = evs[i][0];
                ev = evs[i][1];
                el.on(ev);
            }
        },
        _unapplyEvents: function (evs) {
            for (var i = 0, el, ev; i < evs.length; i++) {
                el = evs[i][0];
                ev = evs[i][1];
                el.off(ev);
            }
        },
        _buildEvents: function () {
            if (this.isInput) { // single input
                this._events = [
                    [this.element, {
                        focus: $.proxy(this.show, this),
                        keyup: $.proxy(this.update, this),
                        keydown: $.proxy(this.keydown, this)
                    }]
                ];
            }
            else if (this.component && this.hasInput) { // component: input + button
                this._events = [
                    // For components that are not readonly, allow keyboard nav
                    [this.element.find('input'), {
                        focus: $.proxy(this.show, this),
                        keyup: $.proxy(this.update, this),
                        keydown: $.proxy(this.keydown, this)
                    }],
                    [this.component, {
                        click: $.proxy(this.show, this)
                    }]
                ];
            }
            else if (this.element.is('div')) {  // inline datepicker
                this.isInline = true;
            }
            else {
                this._events = [
                    [this.element, {
                        click: $.proxy(this.show, this)
                    }]
                ];
            }

            this._secondaryEvents = [
                [this.picker, {
                    click: $.proxy(this.click, this)
                }],
                [$(window), {
                    resize: $.proxy(this.place, this)
                }],
                [$(document), {
                    mousedown: $.proxy(function (e) {
                        // Clicked outside the datepicker, hide it
                        if (!(
                            this.element.is(e.target) ||
                            this.element.find(e.target).size() ||
                            this.picker.is(e.target) ||
                            this.picker.find(e.target).size()
                        )) {
                            this.hide();
                        }
                    }, this)
                }]
            ];
        },
        _attachEvents: function () {
            this._detachEvents();
            this._applyEvents(this._events);
        },
        _detachEvents: function () {
            this._unapplyEvents(this._events);
        },
        _attachSecondaryEvents: function () {
            this._detachSecondaryEvents();
            this._applyEvents(this._secondaryEvents);
        },
        _detachSecondaryEvents: function () {
            this._unapplyEvents(this._secondaryEvents);
        },
        _trigger: function (event, altdate) {
            var date = altdate || this.date,
                local_date = new Date(date.getTime() + (date.getTimezoneOffset() * 60000));

            this.element.trigger({
                type: event,
                date: local_date,
                format: $.proxy(function (altformat) {
                    var format = altformat || this.o.format;
                    return DPGlobal.formatDate(date, format, this.o.language);
                }, this)
            });
        },

        show: function (e) {
            if (!this.isInline)
                this.picker.appendTo('body');
            this.picker.show();
            this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
            this.place();
            this._attachSecondaryEvents();
            if (e) {
                e.preventDefault();
            }
            this._trigger('show');
        },

        hide: function (e) {
            if (this.isInline) return;
            if (!this.picker.is(':visible')) return;
            this.picker.hide().detach();
            this._detachSecondaryEvents();
            this.viewMode = this.o.startView;
            this.showMode();

            if (
                this.o.forceParse &&
                (
                    this.isInput && this.element.val() ||
                    this.hasInput && this.element.find('input').val()
                )
            )
                this.setValue();
            this._trigger('hide');
        },

        remove: function () {
            this.hide();
            this._detachEvents();
            this._detachSecondaryEvents();
            this.picker.remove();
            delete this.element.data().datepicker;
            if (!this.isInput) {
                delete this.element.data().date;
            }
        },

        getDate: function () {
            var d = this.getUTCDate();
            return new Date(d.getTime() + (d.getTimezoneOffset() * 60000));
        },

        getUTCDate: function () {
            return this.date;
        },

        setDate: function (d) {
            this.setUTCDate(new Date(d.getTime() - (d.getTimezoneOffset() * 60000)));
        },

        setUTCDate: function (d) {
            this.date = d;
            this.setValue();
        },

        setValue: function () {
            var formatted = this.getFormattedDate();
            if (!this.isInput) {
                if (this.component) {
                    this.element.find('input').val(formatted);
                }
            } else {
                this.element.val(formatted);
            }
        },

        getFormattedDate: function (format) {
            if (format === undefined)
                format = this.o.format;
            return DPGlobal.formatDate(this.date, format, this.o.language);
        },

        setStartDate: function (startDate) {
            this._process_options({ startDate: startDate });
            this.update();
            this.updateNavArrows();
        },

        setEndDate: function (endDate) {
            this._process_options({ endDate: endDate });
            this.update();
            this.updateNavArrows();
        },

        setDaysOfWeekDisabled: function (daysOfWeekDisabled) {
            this._process_options({ daysOfWeekDisabled: daysOfWeekDisabled });
            this.update();
            this.updateNavArrows();
        },

        place: function () {
            if (this.isInline) return;
            var zIndex = parseInt(this.element.parents().filter(function () {
                return $(this).css('z-index') != 'auto';
            }).first().css('z-index')) + 10;
            var offset = this.component ? this.component.parent().offset() : this.element.offset();
            var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(true);
            this.picker.css({
                top: offset.top + height,
                left: offset.left,
                zIndex: zIndex
            });
        },

        _allow_update: true,
        update: function () {
            if (!this._allow_update) return;

            var date, fromArgs = false;
            if (arguments && arguments.length && (typeof arguments[0] === 'string' || arguments[0] instanceof Date)) {
                date = arguments[0];
                fromArgs = true;
            } else {
                date = this.isInput ? this.element.val() : this.element.data('date') || this.element.find('input').val();
                delete this.element.data().date;
            }

            this.date = DPGlobal.parseDate(date, this.o.format, this.o.language);

            if (fromArgs) this.setValue();

            if (this.date < this.o.startDate) {
                this.viewDate = new Date(this.o.startDate);
            } else if (this.date > this.o.endDate) {
                this.viewDate = new Date(this.o.endDate);
            } else {
                this.viewDate = new Date(this.date);
            }
            this.fill();
        },

        fillDow: function () {
            var dowCnt = this.o.weekStart,
                html = '<tr>';
            if (this.o.calendarWeeks) {
                var cell = '<th class="cw">&nbsp;</th>';
                html += cell;
                this.picker.find('.datepicker-days thead tr:first-child').prepend(cell);
            }
            while (dowCnt < this.o.weekStart + 7) {
                html += '<th class="dow">' + dates[this.o.language].daysMin[(dowCnt++) % 7] + '</th>';
            }
            html += '</tr>';
            this.picker.find('.datepicker-days thead').append(html);
        },

        fillMonths: function () {
            var html = '',
                i = 0;
            while (i < 12) {
                html += '<span class="month">' + dates[this.o.language].monthsShort[i++] + '</span>';
            }
            this.picker.find('.datepicker-months td').html(html);
        },

        setRange: function (range) {
            if (!range || !range.length)
                delete this.range;
            else
                this.range = $.map(range, function (d) { return d.valueOf(); });
            this.fill();
        },

        getClassNames: function (date) {
            var cls = [],
                year = this.viewDate.getUTCFullYear(),
                month = this.viewDate.getUTCMonth(),
                currentDate = this.date.valueOf(),
                today = new Date();
            if (date.getUTCFullYear() < year || (date.getUTCFullYear() == year && date.getUTCMonth() < month)) {
                cls.push('old');
            } else if (date.getUTCFullYear() > year || (date.getUTCFullYear() == year && date.getUTCMonth() > month)) {
                cls.push('new');
            }
            // Compare internal UTC date with local today, not UTC today
            if (this.o.todayHighlight &&
                date.getUTCFullYear() == today.getFullYear() &&
                date.getUTCMonth() == today.getMonth() &&
                date.getUTCDate() == today.getDate()) {
                cls.push('today');
            }
            if (currentDate && date.valueOf() == currentDate) {
                cls.push('active');
            }
            if (date.valueOf() < this.o.startDate || date.valueOf() > this.o.endDate ||
                $.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1) {
                cls.push('disabled');
            }
            if (this.range) {
                if (date > this.range[0] && date < this.range[this.range.length - 1]) {
                    cls.push('range');
                }
                if ($.inArray(date.valueOf(), this.range) != -1) {
                    cls.push('selected');
                }
            }
            return cls;
        },

        fill: function () {
            var d = new Date(this.viewDate),
                year = d.getUTCFullYear(),
                month = d.getUTCMonth(),
                startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity,
                startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity,
                endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity,
                endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity,
                currentDate = this.date && this.date.valueOf(),
                tooltip;
            this.picker.find('.datepicker-days thead th.datepicker-switch')
                .text(dates[this.o.language].months[month] + ' ' + year);
            this.picker.find('tfoot th.today')
                .text(dates[this.o.language].today)
                .toggle(this.o.todayBtn !== false);
            this.picker.find('tfoot th.clear')
                .text(dates[this.o.language].clear)
                .toggle(this.o.clearBtn !== false);
            this.updateNavArrows();
            this.fillMonths();
            var prevMonth = UTCDate(year, month - 1, 28, 0, 0, 0, 0),
                day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
            prevMonth.setUTCDate(day);
            prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7) % 7);
            var nextMonth = new Date(prevMonth);
            nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
            nextMonth = nextMonth.valueOf();
            var html = [];
            var clsName;
            while (prevMonth.valueOf() < nextMonth) {
                if (prevMonth.getUTCDay() == this.o.weekStart) {
                    html.push('<tr>');
                    if (this.o.calendarWeeks) {
                        // ISO 8601: First week contains first thursday.
                        // ISO also states week starts on Monday, but we can be more abstract here.
                        var
                            // Start of current week: based on weekstart/current date
                            ws = new Date(+prevMonth + (this.o.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5),
                            // Thursday of this week
                            th = new Date(+ws + (7 + 4 - ws.getUTCDay()) % 7 * 864e5),
                            // First Thursday of year, year from thursday
                            yth = new Date(+(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay()) % 7 * 864e5),
                            // Calendar week: ms between thursdays, div ms per day, div 7 days
                            calWeek = (th - yth) / 864e5 / 7 + 1;
                        html.push('<td class="cw">' + calWeek + '</td>');

                    }
                }
                clsName = this.getClassNames(prevMonth);
                clsName.push('day');

                var before = this.o.beforeShowDay(prevMonth);
                if (before === undefined)
                    before = {};
                else if (typeof (before) === 'boolean')
                    before = { enabled: before };
                else if (typeof (before) === 'string')
                    before = { classes: before };
                if (before.enabled === false)
                    clsName.push('disabled');
                if (before.classes)
                    clsName = clsName.concat(before.classes.split(/\s+/));
                if (before.tooltip)
                    tooltip = before.tooltip;

                clsName = $.unique(clsName);
                html.push('<td class="' + clsName.join(' ') + '"' + (tooltip ? ' title="' + tooltip + '"' : '') + '>' + prevMonth.getUTCDate() + '</td>');
                if (prevMonth.getUTCDay() == this.o.weekEnd) {
                    html.push('</tr>');
                }
                prevMonth.setUTCDate(prevMonth.getUTCDate() + 1);
            }
            this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
            var currentYear = this.date && this.date.getUTCFullYear();

            var months = this.picker.find('.datepicker-months')
                .find('th:eq(1)')
                .text(year)
                .end()
                .find('span').removeClass('active');
            if (currentYear && currentYear == year) {
                months.eq(this.date.getUTCMonth()).addClass('active');
            }
            if (year < startYear || year > endYear) {
                months.addClass('disabled');
            }
            if (year == startYear) {
                months.slice(0, startMonth).addClass('disabled');
            }
            if (year == endYear) {
                months.slice(endMonth + 1).addClass('disabled');
            }

            html = '';
            year = parseInt(year / 10, 10) * 10;
            var yearCont = this.picker.find('.datepicker-years')
                .find('th:eq(1)')
                .text(year + '-' + (year + 9))
                .end()
                .find('td');
            year -= 1;
            for (var i = -1; i < 11; i++) {
                html += '<span class="year' + (i == -1 ? ' old' : i == 10 ? ' new' : '') + (currentYear == year ? ' active' : '') + (year < startYear || year > endYear ? ' disabled' : '') + '">' + year + '</span>';
                year += 1;
            }
            yearCont.html(html);
        },

        updateNavArrows: function () {
            if (!this._allow_update) return;

            var d = new Date(this.viewDate),
                year = d.getUTCFullYear(),
                month = d.getUTCMonth();
            switch (this.viewMode) {
                case 0:
                    if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear() && month <= this.o.startDate.getUTCMonth()) {
                        this.picker.find('.prev').css({ visibility: 'hidden' });
                    } else {
                        this.picker.find('.prev').css({ visibility: 'visible' });
                    }
                    if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear() && month >= this.o.endDate.getUTCMonth()) {
                        this.picker.find('.next').css({ visibility: 'hidden' });
                    } else {
                        this.picker.find('.next').css({ visibility: 'visible' });
                    }
                    break;
                case 1:
                case 2:
                    if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear()) {
                        this.picker.find('.prev').css({ visibility: 'hidden' });
                    } else {
                        this.picker.find('.prev').css({ visibility: 'visible' });
                    }
                    if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear()) {
                        this.picker.find('.next').css({ visibility: 'hidden' });
                    } else {
                        this.picker.find('.next').css({ visibility: 'visible' });
                    }
                    break;
            }
        },

        click: function (e) {
            e.preventDefault();
            var target = $(e.target).closest('span, td, th');
            if (target.length == 1) {
                switch (target[0].nodeName.toLowerCase()) {
                    case 'th':
                        switch (target[0].className) {
                            case 'datepicker-switch':
                                this.showMode(1);
                                break;
                            case 'prev':
                            case 'next':
                                var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className == 'prev' ? -1 : 1);
                                switch (this.viewMode) {
                                    case 0:
                                        this.viewDate = this.moveMonth(this.viewDate, dir);
                                        break;
                                    case 1:
                                    case 2:
                                        this.viewDate = this.moveYear(this.viewDate, dir);
                                        break;
                                }
                                this.fill();
                                break;
                            case 'today':
                                var date = new Date();
                                date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);

                                this.showMode(-2);
                                var which = this.o.todayBtn == 'linked' ? null : 'view';
                                this._setDate(date, which);
                                break;
                            case 'clear':
                                var element;
                                if (this.isInput)
                                    element = this.element;
                                else if (this.component)
                                    element = this.element.find('input');
                                if (element)
                                    element.val("").change();
                                this._trigger('changeDate');
                                this.update();
                                if (this.o.autoclose)
                                    this.hide();
                                break;
                        }
                        break;
                    case 'span':
                        if (!target.is('.disabled')) {
                            this.viewDate.setUTCDate(1);
                            if (target.is('.month')) {
                                var day = 1;
                                var month = target.parent().find('span').index(target);
                                var year = this.viewDate.getUTCFullYear();
                                this.viewDate.setUTCMonth(month);
                                this._trigger('changeMonth', this.viewDate);
                                if (this.o.minViewMode === 1) {
                                    this._setDate(UTCDate(year, month, day, 0, 0, 0, 0));
                                }
                            } else {
                                var year = parseInt(target.text(), 10) || 0;
                                var day = 1;
                                var month = 0;
                                this.viewDate.setUTCFullYear(year);
                                this._trigger('changeYear', this.viewDate);
                                if (this.o.minViewMode === 2) {
                                    this._setDate(UTCDate(year, month, day, 0, 0, 0, 0));
                                }
                            }
                            this.showMode(-1);
                            this.fill();
                        }
                        break;
                    case 'td':
                        if (target.is('.day') && !target.is('.disabled')) {
                            var day = parseInt(target.text(), 10) || 1;
                            var year = this.viewDate.getUTCFullYear(),
                                month = this.viewDate.getUTCMonth();
                            if (target.is('.old')) {
                                if (month === 0) {
                                    month = 11;
                                    year -= 1;
                                } else {
                                    month -= 1;
                                }
                            } else if (target.is('.new')) {
                                if (month == 11) {
                                    month = 0;
                                    year += 1;
                                } else {
                                    month += 1;
                                }
                            }
                            this._setDate(UTCDate(year, month, day, 0, 0, 0, 0));
                        }
                        break;
                }
            }
        },

        _setDate: function (date, which) {
            if (!which || which == 'date')
                this.date = new Date(date);
            if (!which || which == 'view')
                this.viewDate = new Date(date);
            this.fill();
            this.setValue();
            this._trigger('changeDate');
            var element;
            if (this.isInput) {
                element = this.element;
            } else if (this.component) {
                element = this.element.find('input');
            }
            if (element) {
                element.change();
                if (this.o.autoclose && (!which || which == 'date')) {
                    this.hide();
                }
            }
        },

        moveMonth: function (date, dir) {
            if (!dir) return date;
            var new_date = new Date(date.valueOf()),
                day = new_date.getUTCDate(),
                month = new_date.getUTCMonth(),
                mag = Math.abs(dir),
                new_month, test;
            dir = dir > 0 ? 1 : -1;
            if (mag == 1) {
                test = dir == -1
                    // If going back one month, make sure month is not current month
                    // (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
                    ? function () { return new_date.getUTCMonth() == month; }
                    // If going forward one month, make sure month is as expected
                    // (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
                    : function () { return new_date.getUTCMonth() != new_month; };
                new_month = month + dir;
                new_date.setUTCMonth(new_month);
                // Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
                if (new_month < 0 || new_month > 11)
                    new_month = (new_month + 12) % 12;
            } else {
                // For magnitudes >1, move one month at a time...
                for (var i = 0; i < mag; i++)
                    // ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
                    new_date = this.moveMonth(new_date, dir);
                // ...then reset the day, keeping it in the new month
                new_month = new_date.getUTCMonth();
                new_date.setUTCDate(day);
                test = function () { return new_month != new_date.getUTCMonth(); };
            }
            // Common date-resetting loop -- if date is beyond end of month, make it
            // end of month
            while (test()) {
                new_date.setUTCDate(--day);
                new_date.setUTCMonth(new_month);
            }
            return new_date;
        },

        moveYear: function (date, dir) {
            return this.moveMonth(date, dir * 12);
        },

        dateWithinRange: function (date) {
            return date >= this.o.startDate && date <= this.o.endDate;
        },

        keydown: function (e) {
            if (this.picker.is(':not(:visible)')) {
                if (e.keyCode == 27) // allow escape to hide and re-show picker
                    this.show();
                return;
            }
            var dateChanged = false,
                dir, day, month,
                newDate, newViewDate;
            switch (e.keyCode) {
                case 27: // escape
                    this.hide();
                    e.preventDefault();
                    break;
                case 37: // left
                case 39: // right
                    if (!this.o.keyboardNavigation) break;
                    dir = e.keyCode == 37 ? -1 : 1;
                    if (e.ctrlKey) {
                        newDate = this.moveYear(this.date, dir);
                        newViewDate = this.moveYear(this.viewDate, dir);
                    } else if (e.shiftKey) {
                        newDate = this.moveMonth(this.date, dir);
                        newViewDate = this.moveMonth(this.viewDate, dir);
                    } else {
                        newDate = new Date(this.date);
                        newDate.setUTCDate(this.date.getUTCDate() + dir);
                        newViewDate = new Date(this.viewDate);
                        newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir);
                    }
                    if (this.dateWithinRange(newDate)) {
                        this.date = newDate;
                        this.viewDate = newViewDate;
                        this.setValue();
                        this.update();
                        e.preventDefault();
                        dateChanged = true;
                    }
                    break;
                case 38: // up
                case 40: // down
                    if (!this.o.keyboardNavigation) break;
                    dir = e.keyCode == 38 ? -1 : 1;
                    if (e.ctrlKey) {
                        newDate = this.moveYear(this.date, dir);
                        newViewDate = this.moveYear(this.viewDate, dir);
                    } else if (e.shiftKey) {
                        newDate = this.moveMonth(this.date, dir);
                        newViewDate = this.moveMonth(this.viewDate, dir);
                    } else {
                        newDate = new Date(this.date);
                        newDate.setUTCDate(this.date.getUTCDate() + dir * 7);
                        newViewDate = new Date(this.viewDate);
                        newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7);
                    }
                    if (this.dateWithinRange(newDate)) {
                        this.date = newDate;
                        this.viewDate = newViewDate;
                        this.setValue();
                        this.update();
                        e.preventDefault();
                        dateChanged = true;
                    }
                    break;
                case 13: // enter
                    this.hide();
                    e.preventDefault();
                    break;
                case 9: // tab
                    this.hide();
                    break;
            }
            if (dateChanged) {
                this._trigger('changeDate');
                var element;
                if (this.isInput) {
                    element = this.element;
                } else if (this.component) {
                    element = this.element.find('input');
                }
                if (element) {
                    element.change();
                }
            }
        },

        showMode: function (dir) {
            if (dir) {
                this.viewMode = Math.max(this.o.minViewMode, Math.min(2, this.viewMode + dir));
            }
			/*
				vitalets: fixing bug of very special conditions:
				jquery 1.7.1 + webkit + show inline datepicker in bootstrap popover.
				Method show() does not set display css correctly and datepicker is not shown.
				Changed to .css('display', 'block') solve the problem.
				See https://github.com/vitalets/x-editable/issues/37

				In jquery 1.7.2+ everything works fine.
			*/
            //this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
            this.picker.find('>div').hide().filter('.datepicker-' + DPGlobal.modes[this.viewMode].clsName).css('display', 'block');
            this.updateNavArrows();
        }
    };

    var DateRangePicker = function (element, options) {
        this.element = $(element);
        this.inputs = $.map(options.inputs, function (i) { return i.jquery ? i[0] : i; });
        delete options.inputs;

        $(this.inputs)
            .datepicker(options)
            .bind('changeDate', $.proxy(this.dateUpdated, this));

        this.pickers = $.map(this.inputs, function (i) { return $(i).data('datepicker'); });
        this.updateDates();
    };
    DateRangePicker.prototype = {
        updateDates: function () {
            this.dates = $.map(this.pickers, function (i) { return i.date; });
            this.updateRanges();
        },
        updateRanges: function () {
            var range = $.map(this.dates, function (d) { return d.valueOf(); });
            $.each(this.pickers, function (i, p) {
                p.setRange(range);
            });
        },
        dateUpdated: function (e) {
            var dp = $(e.target).data('datepicker'),
                new_date = dp.getUTCDate(),
                i = $.inArray(e.target, this.inputs),
                l = this.inputs.length;
            if (i == -1) return;

            if (new_date < this.dates[i]) {
                // Date being moved earlier/left
                while (i >= 0 && new_date < this.dates[i]) {
                    this.pickers[i--].setUTCDate(new_date);
                }
            }
            else if (new_date > this.dates[i]) {
                // Date being moved later/right
                while (i < l && new_date > this.dates[i]) {
                    this.pickers[i++].setUTCDate(new_date);
                }
            }
            this.updateDates();
        },
        remove: function () {
            $.map(this.pickers, function (p) { p.remove(); });
            delete this.element.data().datepicker;
        }
    };

    function opts_from_el(el, prefix) {
        // Derive options from element data-attrs
        var data = $(el).data(),
            out = {}, inkey,
            replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])'),
            prefix = new RegExp('^' + prefix.toLowerCase());
        for (var key in data)
            if (prefix.test(key)) {
                inkey = key.replace(replace, function (_, a) { return a.toLowerCase(); });
                out[inkey] = data[key];
            }
        return out;
    }

    function opts_from_locale(lang) {
        // Derive options from locale plugins
        var out = {};
        // Check if "de-DE" style date is available, if not language should
        // fallback to 2 letter code eg "de"
        if (!dates[lang]) {
            lang = lang.split('-')[0]
            if (!dates[lang])
                return;
        }
        var d = dates[lang];
        $.each(locale_opts, function (i, k) {
            if (k in d)
                out[k] = d[k];
        });
        return out;
    }

    var old = $.fn.datepicker;
    var datepicker = $.fn.datepicker = function (option) {
        var args = Array.apply(null, arguments);
        args.shift();
        var internal_return,
            this_return;
        this.each(function () {
            var $this = $(this),
                data = $this.data('datepicker'),
                options = typeof option == 'object' && option;
            if (!data) {
                var elopts = opts_from_el(this, 'date'),
                    // Preliminary otions
                    xopts = $.extend({}, defaults, elopts, options),
                    locopts = opts_from_locale(xopts.language),
                    // Options priority: js args, data-attrs, locales, defaults
                    opts = $.extend({}, defaults, locopts, elopts, options);
                if ($this.is('.input-daterange') || opts.inputs) {
                    var ropts = {
                        inputs: opts.inputs || $this.find('input').toArray()
                    };
                    $this.data('datepicker', (data = new DateRangePicker(this, $.extend(opts, ropts))));
                }
                else {
                    $this.data('datepicker', (data = new Datepicker(this, opts)));
                }
            }
            if (typeof option == 'string' && typeof data[option] == 'function') {
                internal_return = data[option].apply(data, args);
                if (internal_return !== undefined)
                    return false;
            }
        });
        if (internal_return !== undefined)
            return internal_return;
        else
            return this;
    };

    var defaults = $.fn.datepicker.defaults = {
        autoclose: false,
        beforeShowDay: $.noop,
        calendarWeeks: false,
        clearBtn: false,
        daysOfWeekDisabled: [],
        endDate: Infinity,
        forceParse: true,
        format: 'mm/dd/yyyy',
        keyboardNavigation: true,
        language: 'en',
        minViewMode: 0,
        rtl: false,
        startDate: -Infinity,
        startView: 0,
        todayBtn: false,
        todayHighlight: false,
        weekStart: 0
    };
    var locale_opts = $.fn.datepicker.locale_opts = [
        'format',
        'rtl',
        'weekStart'
    ];
    $.fn.datepicker.Constructor = Datepicker;
    var dates = $.fn.datepicker.dates = {
        en: {
            days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
            daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
            daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
            months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
            monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
            today: "Today",
            clear: "Clear"
        }
    };

    var DPGlobal = {
        modes: [
            {
                clsName: 'days',
                navFnc: 'Month',
                navStep: 1
            },
            {
                clsName: 'months',
                navFnc: 'FullYear',
                navStep: 1
            },
            {
                clsName: 'years',
                navFnc: 'FullYear',
                navStep: 10
            }],
        isLeapYear: function (year) {
            return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
        },
        getDaysInMonth: function (year, month) {
            return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
        },
        validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
        nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,
        parseFormat: function (format) {
            // IE treats \0 as a string end in inputs (truncating the value),
            // so it's a bad format delimiter, anyway
            var separators = format.replace(this.validParts, '\0').split('\0'),
                parts = format.match(this.validParts);
            if (!separators || !separators.length || !parts || parts.length === 0) {
                throw new Error("Invalid date format.");
            }
            return { separators: separators, parts: parts };
        },
        parseDate: function (date, format, language) {
            if (date instanceof Date) return date;
            if (typeof format === 'string')
                format = DPGlobal.parseFormat(format);
            if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)) {
                var part_re = /([\-+]\d+)([dmwy])/,
                    parts = date.match(/([\-+]\d+)([dmwy])/g),
                    part, dir;
                date = new Date();
                for (var i = 0; i < parts.length; i++) {
                    part = part_re.exec(parts[i]);
                    dir = parseInt(part[1]);
                    switch (part[2]) {
                        case 'd':
                            date.setUTCDate(date.getUTCDate() + dir);
                            break;
                        case 'm':
                            date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir);
                            break;
                        case 'w':
                            date.setUTCDate(date.getUTCDate() + dir * 7);
                            break;
                        case 'y':
                            date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir);
                            break;
                    }
                }
                return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0);
            }
            var parts = date && date.match(this.nonpunctuation) || [],
                date = new Date(),
                parsed = {},
                setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'],
                setters_map = {
                    yyyy: function (d, v) { return d.setUTCFullYear(v); },
                    yy: function (d, v) { return d.setUTCFullYear(2000 + v); },
                    m: function (d, v) {
                        v -= 1;
                        while (v < 0) v += 12;
                        v %= 12;
                        d.setUTCMonth(v);
                        while (d.getUTCMonth() != v)
                            d.setUTCDate(d.getUTCDate() - 1);
                        return d;
                    },
                    d: function (d, v) { return d.setUTCDate(v); }
                },
                val, filtered, part;
            setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
            setters_map['dd'] = setters_map['d'];
            date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
            var fparts = format.parts.slice();
            // Remove noop parts
            if (parts.length != fparts.length) {
                fparts = $(fparts).filter(function (i, p) {
                    return $.inArray(p, setters_order) !== -1;
                }).toArray();
            }
            // Process remainder
            if (parts.length == fparts.length) {
                for (var i = 0, cnt = fparts.length; i < cnt; i++) {
                    val = parseInt(parts[i], 10);
                    part = fparts[i];
                    if (isNaN(val)) {
                        switch (part) {
                            case 'MM':
                                filtered = $(dates[language].months).filter(function () {
                                    var m = this.slice(0, parts[i].length),
                                        p = parts[i].slice(0, m.length);
                                    return m == p;
                                });
                                val = $.inArray(filtered[0], dates[language].months) + 1;
                                break;
                            case 'M':
                                filtered = $(dates[language].monthsShort).filter(function () {
                                    var m = this.slice(0, parts[i].length),
                                        p = parts[i].slice(0, m.length);
                                    return m == p;
                                });
                                val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
                                break;
                        }
                    }
                    parsed[part] = val;
                }
                for (var i = 0, s; i < setters_order.length; i++) {
                    s = setters_order[i];
                    if (s in parsed && !isNaN(parsed[s]))
                        setters_map[s](date, parsed[s]);
                }
            }
            return date;
        },
        formatDate: function (date, format, language) {
            if (typeof format === 'string')
                format = DPGlobal.parseFormat(format);
            var val = {
                d: date.getUTCDate(),
                D: dates[language].daysShort[date.getUTCDay()],
                DD: dates[language].days[date.getUTCDay()],
                m: date.getUTCMonth() + 1,
                M: dates[language].monthsShort[date.getUTCMonth()],
                MM: dates[language].months[date.getUTCMonth()],
                yy: date.getUTCFullYear().toString().substring(2),
                yyyy: date.getUTCFullYear()
            };
            val.dd = (val.d < 10 ? '0' : '') + val.d;
            val.mm = (val.m < 10 ? '0' : '') + val.m;
            var date = [],
                seps = $.extend([], format.separators);
            for (var i = 0, cnt = format.parts.length; i <= cnt; i++) {
                if (seps.length)
                    date.push(seps.shift());
                date.push(val[format.parts[i]]);
            }
            return date.join('');
        },
        headTemplate: '<thead>' +
            '<tr>' +
            '<th class="prev"><i class="icon-arrow-left"/></th>' +
            '<th colspan="5" class="datepicker-switch"></th>' +
            '<th class="next"><i class="icon-arrow-right"/></th>' +
            '</tr>' +
            '</thead>',
        contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
        footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr><tr><th colspan="7" class="clear"></th></tr></tfoot>'
    };
    DPGlobal.template = '<div class="datepicker">' +
        '<div class="datepicker-days">' +
        '<table class=" table-condensed">' +
        DPGlobal.headTemplate +
        '<tbody></tbody>' +
        DPGlobal.footTemplate +
        '</table>' +
        '</div>' +
        '<div class="datepicker-months">' +
        '<table class="table-condensed">' +
        DPGlobal.headTemplate +
        DPGlobal.contTemplate +
        DPGlobal.footTemplate +
        '</table>' +
        '</div>' +
        '<div class="datepicker-years">' +
        '<table class="table-condensed">' +
        DPGlobal.headTemplate +
        DPGlobal.contTemplate +
        DPGlobal.footTemplate +
        '</table>' +
        '</div>' +
        '</div>';

    $.fn.datepicker.DPGlobal = DPGlobal;


	/* DATEPICKER NO CONFLICT
	* =================== */

    $.fn.datepicker.noConflict = function () {
        $.fn.datepicker = old;
        return this;
    };


	/* DATEPICKER DATA-API
	* ================== */

    $(document).on(
        'focus.datepicker.data-api click.datepicker.data-api',
        '[data-provide="datepicker"]',
        function (e) {
            var $this = $(this);
            if ($this.data('datepicker')) return;
            e.preventDefault();
            // component click requires us to explicitly show it
            datepicker.call($this, 'show');
        }
    );
    $(function () {
        //$('[data-provide="datepicker-inline"]').datepicker();
        //vit: changed to support noConflict()
        datepicker.call($('[data-provide="datepicker-inline"]'));
    });

}(window.jQuery));

/**
Bootstrap-datepicker.  
Description and examples: https://github.com/eternicode/bootstrap-datepicker.  
For **i18n** you should include js file from here: https://github.com/eternicode/bootstrap-datepicker/tree/master/js/locales
and set `language` option.  
Since 1.4.0 date has different appearance in **popup** and **inline** modes. 

@class date
@extends abstractinput
@final
@example
<a href="#" id="dob" data-type="date" data-pk="1" data-url="/post" data-title="Select date">15/05/1984</a>
<script>
$(function(){
    $('#dob').editable({
        format: 'yyyy-mm-dd',    
        viewformat: 'dd/mm/yyyy',    
        datepicker: {
                weekStart: 1
           }
        }
    });
});
</script>
**/
(function ($) {
    "use strict";

    //store bootstrap-datepicker as bdateicker to exclude conflict with jQuery UI one
    $.fn.bdatepicker = $.fn.datepicker.noConflict();
    if (!$.fn.datepicker) { //if there were no other datepickers, keep also original name
        $.fn.datepicker = $.fn.bdatepicker;
    }

    var Date = function (options) {
        this.init('date', options, Date.defaults);
        this.initPicker(options, Date.defaults);
    };

    $.fn.editableutils.inherit(Date, $.fn.editabletypes.abstractinput);

    $.extend(Date.prototype, {
        initPicker: function (options, defaults) {
            //'format' is set directly from settings or data-* attributes

            //by default viewformat equals to format
            if (!this.options.viewformat) {
                this.options.viewformat = this.options.format;
            }

            //try parse datepicker config defined as json string in data-datepicker
            options.datepicker = $.fn.editableutils.tryParseJson(options.datepicker, true);

            //overriding datepicker config (as by default jQuery extend() is not recursive)
            //since 1.4 datepicker internally uses viewformat instead of format. Format is for submit only
            this.options.datepicker = $.extend({}, defaults.datepicker, options.datepicker, {
                format: this.options.viewformat
            });

            //language
            this.options.datepicker.language = this.options.datepicker.language || 'en';

            //store DPglobal
            this.dpg = $.fn.bdatepicker.DPGlobal;

            //store parsed formats
            this.parsedFormat = this.dpg.parseFormat(this.options.format);
            this.parsedViewFormat = this.dpg.parseFormat(this.options.viewformat);
        },

        render: function () {
            this.$input.bdatepicker(this.options.datepicker);

            //"clear" link
            if (this.options.clear) {
                this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    this.clear();
                }, this));

                this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear));
            }
        },

        value2html: function (value, element) {
            var text = value ? this.dpg.formatDate(value, this.parsedViewFormat, this.options.datepicker.language) : '';
            Date.superclass.value2html.call(this, text, element);
        },

        html2value: function (html) {
            return this.parseDate(html, this.parsedViewFormat);
        },

        value2str: function (value) {
            return value ? this.dpg.formatDate(value, this.parsedFormat, this.options.datepicker.language) : '';
        },

        str2value: function (str) {
            return this.parseDate(str, this.parsedFormat);
        },

        value2submit: function (value) {
            return this.value2str(value);
        },

        value2input: function (value) {
            this.$input.bdatepicker('update', value);
        },

        input2value: function () {
            return this.$input.data('datepicker').date;
        },

        activate: function () {
        },

        clear: function () {
            this.$input.data('datepicker').date = null;
            this.$input.find('.active').removeClass('active');
            if (!this.options.showbuttons) {
                this.$input.closest('form').submit();
            }
        },

        autosubmit: function () {
            this.$input.on('mouseup', '.day', function (e) {
                if ($(e.currentTarget).is('.old') || $(e.currentTarget).is('.new')) {
                    return;
                }
                var $form = $(this).closest('form');
                setTimeout(function () {
                    $form.submit();
                }, 200);
            });
            //changedate is not suitable as it triggered when showing datepicker. see #149
            /*
            this.$input.on('changeDate', function(e){
                var $form = $(this).closest('form');
                setTimeout(function() {
                    $form.submit();
                }, 200);
            });
            */
        },

        /*
         For incorrect date bootstrap-datepicker returns current date that is not suitable
         for datefield.
         This function returns null for incorrect date.  
        */
        parseDate: function (str, format) {
            var date = null, formattedBack;
            if (str) {
                date = this.dpg.parseDate(str, format, this.options.datepicker.language);
                if (typeof str === 'string') {
                    formattedBack = this.dpg.formatDate(date, format, this.options.datepicker.language);
                    if (str !== formattedBack) {
                        date = null;
                    }
                }
            }
            return date;
        }

    });

    Date.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
        /**
        @property tpl 
        @default <div></div>
        **/
        tpl: '<div class="editable-date well"></div>',
        /**
        @property inputclass 
        @default null
        **/
        inputclass: null,
        /**
        Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br>
        Possible tokens are: <code>d, dd, m, mm, yy, yyyy</code>  

        @property format 
        @type string
        @default yyyy-mm-dd
        **/
        format: 'yyyy-mm-dd',
        /**
        Format used for displaying date. Also applied when converting date from element's text on init.   
        If not specified equals to <code>format</code>

        @property viewformat 
        @type string
        @default null
        **/
        viewformat: null,
        /**
        Configuration of datepicker.
        Full list of options: http://bootstrap-datepicker.readthedocs.org/en/latest/options.html

        @property datepicker 
        @type object
        @default {
            weekStart: 0,
            startView: 0,
            minViewMode: 0,
            autoclose: false
        }
        **/
        datepicker: {
            weekStart: 0,
            startView: 0,
            minViewMode: 0,
            autoclose: false
        },
        /**
        Text shown as clear date button. 
        If <code>false</code> clear button will not be rendered.

        @property clear 
        @type boolean|string
        @default 'x clear'
        **/
        clear: '&times; clear'
    });

    $.fn.editabletypes.date = Date;

}(window.jQuery));

/**
Bootstrap datefield input - modification for inline mode.
Shows normal <input type="text"> and binds popup datepicker.  
Automatically shown in inline mode.

@class datefield
@extends date

@since 1.4.0
**/
(function ($) {
    "use strict";

    var DateField = function (options) {
        this.init('datefield', options, DateField.defaults);
        this.initPicker(options, DateField.defaults);
    };

    $.fn.editableutils.inherit(DateField, $.fn.editabletypes.date);

    $.extend(DateField.prototype, {
        render: function () {
            this.$input = this.$tpl.find('input');
            this.setClass();
            this.setAttr('placeholder');

            //bootstrap-datepicker is set `bdateicker` to exclude conflict with jQuery UI one. (in date.js)        
            this.$tpl.bdatepicker(this.options.datepicker);

            //need to disable original event handlers
            this.$input.off('focus keydown');

            //update value of datepicker
            this.$input.keyup($.proxy(function () {
                this.$tpl.removeData('date');
                this.$tpl.bdatepicker('update');
            }, this));

        },

        value2input: function (value) {
            this.$input.val(value ? this.dpg.formatDate(value, this.parsedViewFormat, this.options.datepicker.language) : '');
            this.$tpl.bdatepicker('update');
        },

        input2value: function () {
            return this.html2value(this.$input.val());
        },

        activate: function () {
            $.fn.editabletypes.text.prototype.activate.call(this);
        },

        autosubmit: function () {
            //reset autosubmit to empty  
        }
    });

    DateField.defaults = $.extend({}, $.fn.editabletypes.date.defaults, {
        /**
        @property tpl 
        **/
        tpl: '<div class="input-append date"><input type="text"/><span class="add-on"><i class="icon-th"></i></span></div>',
        /**
        @property inputclass 
        @default 'input-small'
        **/
        inputclass: 'input-small',

        /* datepicker config */
        datepicker: {
            weekStart: 0,
            startView: 0,
            minViewMode: 0,
            autoclose: true
        }
    });

    $.fn.editabletypes.datefield = DateField;

}(window.jQuery));
/**
Bootstrap-datetimepicker.  
Based on [smalot bootstrap-datetimepicker plugin](https://github.com/smalot/bootstrap-datetimepicker). 
Before usage you should manually include dependent js and css:

    <link href="css/datetimepicker.css" rel="stylesheet" type="text/css"></link> 
    <script src="js/bootstrap-datetimepicker.js"></script>

For **i18n** you should include js file from here: https://github.com/smalot/bootstrap-datetimepicker/tree/master/js/locales
and set `language` option.  

@class datetime
@extends abstractinput
@final
@since 1.4.4
@example
<a href="#" id="last_seen" data-type="datetime" data-pk="1" data-url="/post" title="Select date & time">15/03/2013 12:45</a>
<script>
$(function(){
    $('#last_seen').editable({
        format: 'yyyy-mm-dd hh:ii',    
        viewformat: 'dd/mm/yyyy hh:ii',    
        datetimepicker: {
                weekStart: 1
           }
        }
    });
});
</script>
**/
(function ($) {
    "use strict";

    var DateTime = function (options) {
        this.init('datetime', options, DateTime.defaults);
        this.initPicker(options, DateTime.defaults);
    };

    $.fn.editableutils.inherit(DateTime, $.fn.editabletypes.abstractinput);

    $.extend(DateTime.prototype, {
        initPicker: function (options, defaults) {
            //'format' is set directly from settings or data-* attributes

            //by default viewformat equals to format
            if (!this.options.viewformat) {
                this.options.viewformat = this.options.format;
            }

            //try parse datetimepicker config defined as json string in data-datetimepicker
            options.datetimepicker = $.fn.editableutils.tryParseJson(options.datetimepicker, true);

            //overriding datetimepicker config (as by default jQuery extend() is not recursive)
            //since 1.4 datetimepicker internally uses viewformat instead of format. Format is for submit only
            this.options.datetimepicker = $.extend({}, defaults.datetimepicker, options.datetimepicker, {
                format: this.options.viewformat
            });

            //language
            this.options.datetimepicker.language = this.options.datetimepicker.language || 'en';

            //store DPglobal
            this.dpg = $.fn.datetimepicker.DPGlobal;

            //store parsed formats
            this.parsedFormat = this.dpg.parseFormat(this.options.format, this.options.formatType);
            this.parsedViewFormat = this.dpg.parseFormat(this.options.viewformat, this.options.formatType);
        },

        render: function () {
            this.$input.datetimepicker(this.options.datetimepicker);

            //adjust container position when viewMode changes
            //see https://github.com/smalot/bootstrap-datetimepicker/pull/80
            this.$input.on('changeMode', function (e) {
                var f = $(this).closest('form').parent();
                //timeout here, otherwise container changes position before form has new size
                setTimeout(function () {
                    f.triggerHandler('resize');
                }, 0);
            });

            //"clear" link
            if (this.options.clear) {
                this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    this.clear();
                }, this));

                this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear));
            }
        },

        value2html: function (value, element) {
            //formatDate works with UTCDate!
            var text = value ? this.dpg.formatDate(this.toUTC(value), this.parsedViewFormat, this.options.datetimepicker.language, this.options.formatType) : '';
            if (element) {
                DateTime.superclass.value2html.call(this, text, element);
            } else {
                return text;
            }
        },

        html2value: function (html) {
            //parseDate return utc date!
            var value = this.parseDate(html, this.parsedViewFormat);
            return value ? this.fromUTC(value) : null;
        },

        value2str: function (value) {
            //formatDate works with UTCDate!
            return value ? this.dpg.formatDate(this.toUTC(value), this.parsedFormat, this.options.datetimepicker.language, this.options.formatType) : '';
        },

        str2value: function (str) {
            //parseDate return utc date!
            var value = this.parseDate(str, this.parsedFormat);
            return value ? this.fromUTC(value) : null;
        },

        value2submit: function (value) {
            return this.value2str(value);
        },

        value2input: function (value) {
            if (value) {
                this.$input.data('datetimepicker').setDate(value);
            }
        },

        input2value: function () {
            //date may be cleared, in that case getDate() triggers error
            var dt = this.$input.data('datetimepicker');
            return dt.date ? dt.getDate() : null;
        },

        activate: function () {
        },

        clear: function () {
            this.$input.data('datetimepicker').date = null;
            this.$input.find('.active').removeClass('active');
            if (!this.options.showbuttons) {
                this.$input.closest('form').submit();
            }
        },

        autosubmit: function () {
            this.$input.on('mouseup', '.minute', function (e) {
                var $form = $(this).closest('form');
                setTimeout(function () {
                    $form.submit();
                }, 200);
            });
        },

        //convert date from local to utc
        toUTC: function (value) {
            return value ? new Date(value.valueOf() - value.getTimezoneOffset() * 60000) : value;
        },

        //convert date from utc to local
        fromUTC: function (value) {
            return value ? new Date(value.valueOf() + value.getTimezoneOffset() * 60000) : value;
        },

        /*
         For incorrect date bootstrap-datetimepicker returns current date that is not suitable
         for datetimefield.
         This function returns null for incorrect date.  
        */
        parseDate: function (str, format) {
            var date = null, formattedBack;
            if (str) {
                date = this.dpg.parseDate(str, format, this.options.datetimepicker.language, this.options.formatType);
                if (typeof str === 'string') {
                    formattedBack = this.dpg.formatDate(date, format, this.options.datetimepicker.language, this.options.formatType);
                    if (str !== formattedBack) {
                        date = null;
                    }
                }
            }
            return date;
        }

    });

    DateTime.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
        /**
        @property tpl 
        @default <div></div>
        **/
        tpl: '<div class="editable-date well"></div>',
        /**
        @property inputclass 
        @default null
        **/
        inputclass: null,
        /**
        Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br>
        Possible tokens are: <code>d, dd, m, mm, yy, yyyy, h, i</code>  
        
        @property format 
        @type string
        @default yyyy-mm-dd hh:ii
        **/
        format: 'yyyy-mm-dd hh:ii',
        formatType: 'standard',
        /**
        Format used for displaying date. Also applied when converting date from element's text on init.   
        If not specified equals to <code>format</code>
        
        @property viewformat 
        @type string
        @default null
        **/
        viewformat: null,
        /**
        Configuration of datetimepicker.
        Full list of options: https://github.com/smalot/bootstrap-datetimepicker

        @property datetimepicker 
        @type object
        @default { }
        **/
        datetimepicker: {
            todayHighlight: false,
            autoclose: false
        },
        /**
        Text shown as clear date button. 
        If <code>false</code> clear button will not be rendered.

        @property clear 
        @type boolean|string
        @default 'x clear'
        **/
        clear: '&times; clear'
    });

    $.fn.editabletypes.datetime = DateTime;

}(window.jQuery));
/**
Bootstrap datetimefield input - datetime input for inline mode.
Shows normal <input type="text"> and binds popup datetimepicker.  
Automatically shown in inline mode.

@class datetimefield
@extends datetime

**/
(function ($) {
    "use strict";

    var DateTimeField = function (options) {
        this.init('datetimefield', options, DateTimeField.defaults);
        this.initPicker(options, DateTimeField.defaults);
    };

    $.fn.editableutils.inherit(DateTimeField, $.fn.editabletypes.datetime);

    $.extend(DateTimeField.prototype, {
        render: function () {
            this.$input = this.$tpl.find('input');
            this.setClass();
            this.setAttr('placeholder');

            this.$tpl.datetimepicker(this.options.datetimepicker);

            //need to disable original event handlers
            this.$input.off('focus keydown');

            //update value of datepicker
            this.$input.keyup($.proxy(function () {
                this.$tpl.removeData('date');
                this.$tpl.datetimepicker('update');
            }, this));

        },

        value2input: function (value) {
            this.$input.val(this.value2html(value));
            this.$tpl.datetimepicker('update');
        },

        input2value: function () {
            return this.html2value(this.$input.val());
        },

        activate: function () {
            $.fn.editabletypes.text.prototype.activate.call(this);
        },

        autosubmit: function () {
            //reset autosubmit to empty  
        }
    });

    DateTimeField.defaults = $.extend({}, $.fn.editabletypes.datetime.defaults, {
        /**
        @property tpl 
        **/
        tpl: '<div class="input-append date"><input type="text"/><span class="add-on"><i class="icon-th"></i></span></div>',
        /**
        @property inputclass 
        @default 'input-medium'
        **/
        inputclass: 'input-medium',

        /* datetimepicker config */
        datetimepicker: {
            todayHighlight: false,
            autoclose: true
        }
    });

    $.fn.editabletypes.datetimefield = DateTimeField;

}(window.jQuery));;
/**
Bootstrap wysihtml5 editor. Based on [bootstrap-wysihtml5](https://github.com/jhollingworth/bootstrap-wysihtml5).  
You should include **manually** distributives of `wysihtml5` and `bootstrap-wysihtml5`:

    <link href="js/inputs-ext/wysihtml5/bootstrap-wysihtml5-0.0.2/bootstrap-wysihtml5-0.0.2.css" rel="stylesheet" type="text/css"></link>  
    <script src="js/inputs-ext/wysihtml5/bootstrap-wysihtml5-0.0.2/wysihtml5-0.3.0.min.js"></script>  
    <script src="js/inputs-ext/wysihtml5/bootstrap-wysihtml5-0.0.2/bootstrap-wysihtml5-0.0.2.min.js"></script>
    
And also include `wysihtml5.js` from `inputs-ext` directory of x-editable:
      
    <script src="js/inputs-ext/wysihtml5/wysihtml5.js"></script>  

**Note:** It's better to use fresh bootstrap-wysihtml5 from it's [master branch](https://github.com/jhollingworth/bootstrap-wysihtml5/tree/master/src) as there is update for correct image insertion.    
    
@class wysihtml5
@extends abstractinput
@final
@since 1.4.0
@example
<div id="comments" data-type="wysihtml5" data-pk="1"><h2>awesome</h2> comment!</div>
<script>
$(function(){
    $('#comments').editable({
        url: '/post',
        title: 'Enter comments'
    });
});
</script>
**/
(function ($) {
    "use strict";

    var Wysihtml5 = function (options) {
        this.init('wysihtml5', options, Wysihtml5.defaults);

        //extend wysihtml5 manually as $.extend not recursive 
        this.options.wysihtml5 = $.extend({}, Wysihtml5.defaults.wysihtml5, options.wysihtml5);
    };

    $.fn.editableutils.inherit(Wysihtml5, $.fn.editabletypes.abstractinput);

    $.extend(Wysihtml5.prototype, {
        render: function () {
            var deferred = $.Deferred(),
                msieOld;

            //generate unique id as it required for wysihtml5
            this.$input.attr('id', 'textarea_' + (new Date()).getTime());

            this.setClass();
            this.setAttr('placeholder');

            //resolve deffered when widget loaded
            $.extend(this.options.wysihtml5, {
                events: {
                    load: function () {
                        deferred.resolve();
                    }
                }
            });


            this.$input.wysihtml5(this.options.wysihtml5);

            /*
             In IE8 wysihtml5 iframe stays on the same line with buttons toolbar (inside popover).
             The only solution I found is to add <br>. If you fine better way, please send PR.   
            */
            msieOld = /msie\s*(8|7|6)/.test(navigator.userAgent.toLowerCase());
            if (msieOld) {
                this.$input.before('<br><br>');
            }

            return deferred.promise();
        },

        value2html: function (value, element) {
            $(element).html(value);
        },

        html2value: function (html) {
            return html;
        },

        value2input: function (value) {
            this.$input.data("wysihtml5").editor.setValue(value, true);
        },

        activate: function () {
            this.$input.data("wysihtml5").editor.focus();
        },

        isEmpty: function ($element) {
            if ($.trim($element.html()) === '') {
                return true;
            } else if ($.trim($element.text()) !== '') {
                return false;
            } else {
                //e.g. '<img>', '<br>', '<p></p>'
                return !$element.height() || !$element.width();
            }
        }
    });

    Wysihtml5.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
        /**
        @property tpl
        @default <textarea></textarea>
        **/
        tpl: '<textarea></textarea>',
        /**
        @property inputclass
        @default editable-wysihtml5
        **/
        inputclass: 'editable-wysihtml5',
        /**
        Placeholder attribute of input. Shown when input is empty.

        @property placeholder
        @type string
        @default null
        **/
        placeholder: null,
        /**
        Wysihtml5 default options.  
        See https://github.com/jhollingworth/bootstrap-wysihtml5#options

        @property wysihtml5
        @type object
        @default {stylesheets: false}
        **/
        wysihtml5: {
            stylesheets: false //see https://github.com/jhollingworth/bootstrap-wysihtml5/issues/183
        }
    });

    $.fn.editabletypes.wysihtml5 = Wysihtml5;

}(window.jQuery));;
/*
 wysihtml5 v0.3.0
 https://github.com/xing/wysihtml5

 Author: Christopher Blum (https://github.com/tiff)

 Copyright (C) 2012 XING AG
 Licensed under the MIT license (MIT)

 Rangy, a cross-browser JavaScript range and selection library
 http://code.google.com/p/rangy/

 Copyright 2011, Tim Down
 Licensed under the MIT license.
 Version: 1.2.2
 Build date: 13 November 2011
*/
var wysihtml5 = { version: "0.3.0", commands: {}, dom: {}, quirks: {}, toolbar: {}, lang: {}, selection: {}, views: {}, INVISIBLE_SPACE: "\ufeff", EMPTY_FUNCTION: function () { }, ELEMENT_NODE: 1, TEXT_NODE: 3, BACKSPACE_KEY: 8, ENTER_KEY: 13, ESCAPE_KEY: 27, SPACE_KEY: 32, DELETE_KEY: 46 };
window.rangy = function () {
    function b(a, b) { var c = typeof a[b]; return c == k || !!(c == h && a[b]) || "unknown" == c } function c(a, b) { return !!(typeof a[b] == h && a[b]) } function a(a, b) { return typeof a[b] != j } function d(a) { return function (b, c) { for (var d = c.length; d--;)if (!a(b, c[d])) return !1; return !0 } } function e(a) { return a && m(a, r) && x(a, q) } function f(a) { window.alert("Rangy not supported in your browser. Reason: " + a); o.initialized = !0; o.supported = !1 } function g() {
        if (!o.initialized) {
            var a, d = !1, h = !1; b(document, "createRange") &&
                (a = document.createRange(), m(a, p) && x(a, n) && (d = !0), a.detach()); if ((a = c(document, "body") ? document.body : document.getElementsByTagName("body")[0]) && b(a, "createTextRange")) a = a.createTextRange(), e(a) && (h = !0); !d && !h && f("Neither Range nor TextRange are implemented"); o.initialized = !0; o.features = { implementsDomRange: d, implementsTextRange: h }; d = w.concat(z); h = 0; for (a = d.length; h < a; ++h)try { d[h](o) } catch (j) {
                c(window, "console") && b(window.console, "log") && window.console.log("Init listener threw an exception. Continuing.",
                    j)
                }
        }
    } function i(a) { this.name = a; this.supported = this.initialized = !1 } var h = "object", k = "function", j = "undefined", n = "startContainer startOffset endContainer endOffset collapsed commonAncestorContainer START_TO_START START_TO_END END_TO_START END_TO_END".split(" "), p = "setStart setStartBefore setStartAfter setEnd setEndBefore setEndAfter collapse selectNode selectNodeContents compareBoundaryPoints deleteContents extractContents cloneContents insertNode surroundContents cloneRange toString detach".split(" "),
        q = "boundingHeight boundingLeft boundingTop boundingWidth htmlText text".split(" "), r = "collapse compareEndPoints duplicate getBookmark moveToBookmark moveToElementText parentElement pasteHTML select setEndPoint getBoundingClientRect".split(" "), m = d(b), s = d(c), x = d(a), o = { version: "1.2.2", initialized: !1, supported: !0, util: { isHostMethod: b, isHostObject: c, isHostProperty: a, areHostMethods: m, areHostObjects: s, areHostProperties: x, isTextRange: e }, features: {}, modules: {}, config: { alertOnWarn: !1, preferTextRange: !1 } };
    o.fail = f; o.warn = function (a) { a = "Rangy warning: " + a; o.config.alertOnWarn ? window.alert(a) : typeof window.console != j && typeof window.console.log != j && window.console.log(a) }; ({}).hasOwnProperty ? o.util.extend = function (a, b) { for (var c in b) b.hasOwnProperty(c) && (a[c] = b[c]) } : f("hasOwnProperty not supported"); var z = [], w = []; o.init = g; o.addInitListener = function (a) { o.initialized ? a(o) : z.push(a) }; var y = []; o.addCreateMissingNativeApiListener = function (a) { y.push(a) }; o.createMissingNativeApi = function (a) {
        a = a || window; g();
        for (var b = 0, c = y.length; b < c; ++b)y[b](a)
    }; i.prototype.fail = function (a) { this.initialized = !0; this.supported = !1; throw Error("Module '" + this.name + "' failed to load: " + a); }; i.prototype.warn = function (a) { o.warn("Module " + this.name + ": " + a) }; i.prototype.createError = function (a) { return Error("Error in Rangy " + this.name + " module: " + a) }; o.createModule = function (a, b) { var c = new i(a); o.modules[a] = c; w.push(function (a) { b(a, c); c.initialized = !0; c.supported = !0 }) }; o.requireModules = function (a) {
        for (var b = 0, c = a.length, d, h; b <
            c; ++b) { h = a[b]; d = o.modules[h]; if (!d || !(d instanceof i)) throw Error("Module '" + h + "' not found"); if (!d.supported) throw Error("Module '" + h + "' not supported"); }
    }; var A = !1, s = function () { A || (A = !0, o.initialized || g()) }; if (typeof window == j) f("No window found"); else if (typeof document == j) f("No document found"); else return b(document, "addEventListener") && document.addEventListener("DOMContentLoaded", s, !1), b(window, "addEventListener") ? window.addEventListener("load", s, !1) : b(window, "attachEvent") ? window.attachEvent("onload",
        s) : f("Window does not have required addEventListener or attachEvent method"), o
}();
rangy.createModule("DomUtil", function (b, c) {
    function a(a) { for (var b = 0; a = a.previousSibling;)b++; return b } function d(a, b) { var c = [], d; for (d = a; d; d = d.parentNode)c.push(d); for (d = b; d; d = d.parentNode)if (m(c, d)) return d; return null } function e(a, b, c) { for (c = c ? a : a.parentNode; c;) { a = c.parentNode; if (a === b) return c; c = a } return null } function f(a) { a = a.nodeType; return 3 == a || 4 == a || 8 == a } function g(a, b) { var c = b.nextSibling, d = b.parentNode; c ? d.insertBefore(a, c) : d.appendChild(a); return a } function i(a) {
        if (9 == a.nodeType) return a;
        if (typeof a.ownerDocument != p) return a.ownerDocument; if (typeof a.document != p) return a.document; if (a.parentNode) return i(a.parentNode); throw Error("getDocument: no document found for node");
    } function h(a) { return !a ? "[No node]" : f(a) ? '"' + a.data + '"' : 1 == a.nodeType ? "<" + a.nodeName + (a.id ? ' id="' + a.id + '"' : "") + ">[" + a.childNodes.length + "]" : a.nodeName } function k(a) { this._next = this.root = a } function j(a, b) { this.node = a; this.offset = b } function n(a) { this.code = this[a]; this.codeName = a; this.message = "DOMException: " + this.codeName }
    var p = "undefined", q = b.util; q.areHostMethods(document, ["createDocumentFragment", "createElement", "createTextNode"]) || c.fail("document missing a Node creation method"); q.isHostMethod(document, "getElementsByTagName") || c.fail("document missing getElementsByTagName method"); var r = document.createElement("div"); q.areHostMethods(r, ["insertBefore", "appendChild", "cloneNode"]) || c.fail("Incomplete Element implementation"); q.isHostProperty(r, "innerHTML") || c.fail("Element is missing innerHTML property"); r = document.createTextNode("test");
    q.areHostMethods(r, ["splitText", "deleteData", "insertData", "appendData", "cloneNode"]) || c.fail("Incomplete Text Node implementation"); var m = function (a, b) { for (var c = a.length; c--;)if (a[c] === b) return !0; return !1 }; k.prototype = {
        _current: null, hasNext: function () { return !!this._next }, next: function () { var a = this._current = this._next, b; if (this._current) { b = a.firstChild; if (!b) for (b = null; a !== this.root && !(b = a.nextSibling);)a = a.parentNode; this._next = b } return this._current }, detach: function () {
        this._current = this._next = this.root =
            null
        }
    }; j.prototype = { equals: function (a) { return this.node === a.node & this.offset == a.offset }, inspect: function () { return "[DomPosition(" + h(this.node) + ":" + this.offset + ")]" } }; n.prototype = { INDEX_SIZE_ERR: 1, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, NO_MODIFICATION_ALLOWED_ERR: 7, NOT_FOUND_ERR: 8, NOT_SUPPORTED_ERR: 9, INVALID_STATE_ERR: 11 }; n.prototype.toString = function () { return this.message }; b.dom = {
        arrayContains: m, isHtmlNamespace: function (a) {
            var b; return typeof a.namespaceURI == p || null === (b = a.namespaceURI) || "http://www.w3.org/1999/xhtml" ==
                b
        }, parentElement: function (a) { a = a.parentNode; return 1 == a.nodeType ? a : null }, getNodeIndex: a, getNodeLength: function (a) { var b; return f(a) ? a.length : (b = a.childNodes) ? b.length : 0 }, getCommonAncestor: d, isAncestorOf: function (a, b, c) { for (b = c ? b : b.parentNode; b;) { if (b === a) return !0; b = b.parentNode } return !1 }, getClosestAncestorIn: e, isCharacterDataNode: f, insertAfter: g, splitDataNode: function (a, b) { var c = a.cloneNode(!1); c.deleteData(0, b); a.deleteData(b, a.length - b); g(c, a); return c }, getDocument: i, getWindow: function (a) {
            a = i(a);
            if (typeof a.defaultView != p) return a.defaultView; if (typeof a.parentWindow != p) return a.parentWindow; throw Error("Cannot get a window object for node");
        }, getIframeWindow: function (a) { if (typeof a.contentWindow != p) return a.contentWindow; if (typeof a.contentDocument != p) return a.contentDocument.defaultView; throw Error("getIframeWindow: No Window object found for iframe element"); }, getIframeDocument: function (a) {
            if (typeof a.contentDocument != p) return a.contentDocument; if (typeof a.contentWindow != p) return a.contentWindow.document;
            throw Error("getIframeWindow: No Document object found for iframe element");
        }, getBody: function (a) { return q.isHostObject(a, "body") ? a.body : a.getElementsByTagName("body")[0] }, getRootContainer: function (a) { for (var b; b = a.parentNode;)a = b; return a }, comparePoints: function (b, c, h, j) {
            var k; if (b == h) return c === j ? 0 : c < j ? -1 : 1; if (k = e(h, b, !0)) return c <= a(k) ? -1 : 1; if (k = e(b, h, !0)) return a(k) < j ? -1 : 1; c = d(b, h); b = b === c ? c : e(b, c, !0); h = h === c ? c : e(h, c, !0); if (b === h) throw Error("comparePoints got to case 4 and childA and childB are the same!");
            for (c = c.firstChild; c;) { if (c === b) return -1; if (c === h) return 1; c = c.nextSibling } throw Error("Should not be here!");
        }, inspectNode: h, fragmentFromNodeChildren: function (a) { for (var b = i(a).createDocumentFragment(), c; c = a.firstChild;)b.appendChild(c); return b }, createIterator: function (a) { return new k(a) }, DomPosition: j
    }; b.DOMException = n
});
rangy.createModule("DomRange", function (b) {
    function c(a, b) { return 3 != a.nodeType && (l.isAncestorOf(a, b.startContainer, !0) || l.isAncestorOf(a, b.endContainer, !0)) } function a(a) { return l.getDocument(a.startContainer) } function d(a, b, c) { if (b = a._listeners[b]) for (var d = 0, h = b.length; d < h; ++d)b[d].call(a, { target: a, args: c }) } function e(a) { return new u(a.parentNode, l.getNodeIndex(a)) } function f(a) { return new u(a.parentNode, l.getNodeIndex(a) + 1) } function g(a, b, c) {
        var d = 11 == a.nodeType ? a.firstChild : a; l.isCharacterDataNode(b) ?
            c == b.length ? l.insertAfter(a, b) : b.parentNode.insertBefore(a, 0 == c ? b : l.splitDataNode(b, c)) : c >= b.childNodes.length ? b.appendChild(a) : b.insertBefore(a, b.childNodes[c]); return d
    } function i(b) { for (var c, d, h = a(b.range).createDocumentFragment(); d = b.next();) { c = b.isPartiallySelectedSubtree(); d = d.cloneNode(!c); c && (c = b.getSubtreeIterator(), d.appendChild(i(c)), c.detach(!0)); if (10 == d.nodeType) throw new B("HIERARCHY_REQUEST_ERR"); h.appendChild(d) } return h } function h(a, b, c) {
        for (var d, e, c = c || { stop: !1 }; d = a.next();)if (a.isPartiallySelectedSubtree()) if (!1 ===
            b(d)) { c.stop = !0; break } else { if (d = a.getSubtreeIterator(), h(d, b, c), d.detach(!0), c.stop) break } else for (d = l.createIterator(d); e = d.next();)if (!1 === b(e)) { c.stop = !0; return }
    } function k(a) { for (var b; a.next();)a.isPartiallySelectedSubtree() ? (b = a.getSubtreeIterator(), k(b), b.detach(!0)) : a.remove() } function j(b) {
        for (var c, d = a(b.range).createDocumentFragment(), h; c = b.next();) {
            b.isPartiallySelectedSubtree() ? (c = c.cloneNode(!1), h = b.getSubtreeIterator(), c.appendChild(j(h)), h.detach(!0)) : b.remove(); if (10 == c.nodeType) throw new B("HIERARCHY_REQUEST_ERR");
            d.appendChild(c)
        } return d
    } function n(a, b, c) { var d = !(!b || !b.length), e, j = !!c; d && (e = RegExp("^(" + b.join("|") + ")$")); var k = []; h(new q(a, !1), function (a) { (!d || e.test(a.nodeType)) && (!j || c(a)) && k.push(a) }); return k } function p(a) { return "[" + ("undefined" == typeof a.getName ? "Range" : a.getName()) + "(" + l.inspectNode(a.startContainer) + ":" + a.startOffset + ", " + l.inspectNode(a.endContainer) + ":" + a.endOffset + ")]" } function q(a, b) {
    this.range = a; this.clonePartiallySelectedTextNodes = b; if (!a.collapsed) {
    this.sc = a.startContainer;
        this.so = a.startOffset; this.ec = a.endContainer; this.eo = a.endOffset; var c = a.commonAncestorContainer; this.sc === this.ec && l.isCharacterDataNode(this.sc) ? (this.isSingleCharacterDataNode = !0, this._first = this._last = this._next = this.sc) : (this._first = this._next = this.sc === c && !l.isCharacterDataNode(this.sc) ? this.sc.childNodes[this.so] : l.getClosestAncestorIn(this.sc, c, !0), this._last = this.ec === c && !l.isCharacterDataNode(this.ec) ? this.ec.childNodes[this.eo - 1] : l.getClosestAncestorIn(this.ec, c, !0))
    }
    } function r(a) {
    this.code =
        this[a]; this.codeName = a; this.message = "RangeException: " + this.codeName
    } function m(a, b, c) { this.nodes = n(a, b, c); this._next = this.nodes[0]; this._position = 0 } function s(a) { return function (b, c) { for (var d, h = c ? b : b.parentNode; h;) { d = h.nodeType; if (l.arrayContains(a, d)) return h; h = h.parentNode } return null } } function x(a, b) { if ($(a, b)) throw new r("INVALID_NODE_TYPE_ERR"); } function o(a) { if (!a.startContainer) throw new B("INVALID_STATE_ERR"); } function z(a, b) {
        if (!l.arrayContains(b, a.nodeType)) throw new r("INVALID_NODE_TYPE_ERR");
    } function w(a, b) { if (0 > b || b > (l.isCharacterDataNode(a) ? a.length : a.childNodes.length)) throw new B("INDEX_SIZE_ERR"); } function y(a, b) { if (O(a, !0) !== O(b, !0)) throw new B("WRONG_DOCUMENT_ERR"); } function A(a) { if (aa(a, !0)) throw new B("NO_MODIFICATION_ALLOWED_ERR"); } function t(a, b) { if (!a) throw new B(b); } function v(a) {
        o(a); if (!l.arrayContains(G, a.startContainer.nodeType) && !O(a.startContainer, !0) || !l.arrayContains(G, a.endContainer.nodeType) && !O(a.endContainer, !0) || !(a.startOffset <= (l.isCharacterDataNode(a.startContainer) ?
            a.startContainer.length : a.startContainer.childNodes.length)) || !(a.endOffset <= (l.isCharacterDataNode(a.endContainer) ? a.endContainer.length : a.endContainer.childNodes.length))) throw Error("Range error: Range is no longer valid after DOM mutation (" + a.inspect() + ")");
    } function D() { } function K(a) { a.START_TO_START = Q; a.START_TO_END = U; a.END_TO_END = ba; a.END_TO_START = V; a.NODE_BEFORE = W; a.NODE_AFTER = X; a.NODE_BEFORE_AND_AFTER = Y; a.NODE_INSIDE = R } function F(a) { K(a); K(a.prototype) } function E(a, b) {
        return function () {
            v(this);
            var c = this.startContainer, d = this.startOffset, e = this.commonAncestorContainer, j = new q(this, !0); c !== e && (c = l.getClosestAncestorIn(c, e, !0), d = f(c), c = d.node, d = d.offset); h(j, A); j.reset(); e = a(j); j.detach(); b(this, c, d, c, d); return e
        }
    } function I(a, d, h) {
        function g(a, b) { return function (c) { o(this); z(c, L); z(M(c), G); c = (a ? e : f)(c); (b ? i : n)(this, c.node, c.offset) } } function i(a, b, c) {
            var h = a.endContainer, e = a.endOffset; if (b !== a.startContainer || c !== a.startOffset) {
                if (M(b) != M(h) || 1 == l.comparePoints(b, c, h, e)) h = b, e = c; d(a, b, c,
                    h, e)
            }
        } function n(a, b, c) { var h = a.startContainer, e = a.startOffset; if (b !== a.endContainer || c !== a.endOffset) { if (M(b) != M(h) || -1 == l.comparePoints(b, c, h, e)) h = b, e = c; d(a, h, e, b, c) } } a.prototype = new D; b.util.extend(a.prototype, {
            setStart: function (a, b) { o(this); x(a, !0); w(a, b); i(this, a, b) }, setEnd: function (a, b) { o(this); x(a, !0); w(a, b); n(this, a, b) }, setStartBefore: g(!0, !0), setStartAfter: g(!1, !0), setEndBefore: g(!0, !1), setEndAfter: g(!1, !1), collapse: function (a) {
                v(this); a ? d(this, this.startContainer, this.startOffset, this.startContainer,
                    this.startOffset) : d(this, this.endContainer, this.endOffset, this.endContainer, this.endOffset)
            }, selectNodeContents: function (a) { o(this); x(a, !0); d(this, a, 0, a, l.getNodeLength(a)) }, selectNode: function (a) { o(this); x(a, !1); z(a, L); var b = e(a), a = f(a); d(this, b.node, b.offset, a.node, a.offset) }, extractContents: E(j, d), deleteContents: E(k, d), canSurroundContents: function () { v(this); A(this.startContainer); A(this.endContainer); var a = new q(this, !0), b = a._first && c(a._first, this) || a._last && c(a._last, this); a.detach(); return !b },
            detach: function () { h(this) }, splitBoundaries: function () { v(this); var a = this.startContainer, b = this.startOffset, c = this.endContainer, h = this.endOffset, e = a === c; l.isCharacterDataNode(c) && (0 < h && h < c.length) && l.splitDataNode(c, h); l.isCharacterDataNode(a) && (0 < b && b < a.length) && (a = l.splitDataNode(a, b), e ? (h -= b, c = a) : c == a.parentNode && h >= l.getNodeIndex(a) && h++ , b = 0); d(this, a, b, c, h) }, normalizeBoundaries: function () {
                v(this); var a = this.startContainer, b = this.startOffset, c = this.endContainer, h = this.endOffset, e = function (a) {
                    var b =
                        a.nextSibling; b && b.nodeType == a.nodeType && (c = a, h = a.length, a.appendData(b.data), b.parentNode.removeChild(b))
                }, j = function (d) { var e = d.previousSibling; if (e && e.nodeType == d.nodeType) { a = d; var j = d.length; b = e.length; d.insertData(0, e.data); e.parentNode.removeChild(e); a == c ? (h += b, c = a) : c == d.parentNode && (e = l.getNodeIndex(d), h == e ? (c = d, h = j) : h > e && h--) } }, k = !0; l.isCharacterDataNode(c) ? c.length == h && e(c) : (0 < h && (k = c.childNodes[h - 1]) && l.isCharacterDataNode(k) && e(k), k = !this.collapsed); k ? l.isCharacterDataNode(a) ? 0 == b && j(a) :
                    b < a.childNodes.length && (e = a.childNodes[b]) && l.isCharacterDataNode(e) && j(e) : (a = c, b = h); d(this, a, b, c, h)
            }, collapseToPoint: function (a, b) { o(this); x(a, !0); w(a, b); (a !== this.startContainer || b !== this.startOffset || a !== this.endContainer || b !== this.endOffset) && d(this, a, b, a, b) }
        }); F(a)
    } function N(a) { a.collapsed = a.startContainer === a.endContainer && a.startOffset === a.endOffset; a.commonAncestorContainer = a.collapsed ? a.startContainer : l.getCommonAncestor(a.startContainer, a.endContainer) } function J(a, b, c, h, e) {
        var j = a.startContainer !==
            b || a.startOffset !== c, k = a.endContainer !== h || a.endOffset !== e; a.startContainer = b; a.startOffset = c; a.endContainer = h; a.endOffset = e; N(a); d(a, "boundarychange", { startMoved: j, endMoved: k })
    } function C(a) { this.startContainer = a; this.startOffset = 0; this.endContainer = a; this.endOffset = 0; this._listeners = { boundarychange: [], detach: [] }; N(this) } b.requireModules(["DomUtil"]); var l = b.dom, u = l.DomPosition, B = b.DOMException; q.prototype = {
        _current: null, _next: null, _first: null, _last: null, isSingleCharacterDataNode: !1, reset: function () {
        this._current =
            null; this._next = this._first
        }, hasNext: function () { return !!this._next }, next: function () { var a = this._current = this._next; a && (this._next = a !== this._last ? a.nextSibling : null, l.isCharacterDataNode(a) && this.clonePartiallySelectedTextNodes && (a === this.ec && (a = a.cloneNode(!0)).deleteData(this.eo, a.length - this.eo), this._current === this.sc && (a = a.cloneNode(!0)).deleteData(0, this.so))); return a }, remove: function () {
            var a = this._current, b, c; l.isCharacterDataNode(a) && (a === this.sc || a === this.ec) ? (b = a === this.sc ? this.so : 0, c = a ===
                this.ec ? this.eo : a.length, b != c && a.deleteData(b, c - b)) : a.parentNode && a.parentNode.removeChild(a)
        }, isPartiallySelectedSubtree: function () { return c(this._current, this.range) }, getSubtreeIterator: function () { var b; if (this.isSingleCharacterDataNode) b = this.range.cloneRange(), b.collapse(); else { b = new C(a(this.range)); var c = this._current, d = c, h = 0, e = c, j = l.getNodeLength(c); l.isAncestorOf(c, this.sc, !0) && (d = this.sc, h = this.so); l.isAncestorOf(c, this.ec, !0) && (e = this.ec, j = this.eo); J(b, d, h, e, j) } return new q(b, this.clonePartiallySelectedTextNodes) },
        detach: function (a) { a && this.range.detach(); this.range = this._current = this._next = this._first = this._last = this.sc = this.so = this.ec = this.eo = null }
    }; r.prototype = { BAD_BOUNDARYPOINTS_ERR: 1, INVALID_NODE_TYPE_ERR: 2 }; r.prototype.toString = function () { return this.message }; m.prototype = { _current: null, hasNext: function () { return !!this._next }, next: function () { this._current = this._next; this._next = this.nodes[++this._position]; return this._current }, detach: function () { this._current = this._next = this.nodes = null } }; var L = [1, 3, 4, 5,
        7, 8, 10], G = [2, 9, 11], P = [1, 3, 4, 5, 7, 8, 10, 11], H = [1, 3, 4, 5, 7, 8], M = l.getRootContainer, O = s([9, 11]), aa = s([5, 6, 10, 12]), $ = s([6, 10, 12]), Z = document.createElement("style"), S = !1; try { Z.innerHTML = "<b>x</b>", S = 3 == Z.firstChild.nodeType } catch (ca) { } b.features.htmlParsingConforms = S; var T = "startContainer startOffset endContainer endOffset collapsed commonAncestorContainer".split(" "), Q = 0, U = 1, ba = 2, V = 3, W = 0, X = 1, Y = 2, R = 3; D.prototype = {
            attachListener: function (a, b) { this._listeners[a].push(b) }, compareBoundaryPoints: function (a, b) {
                v(this);
                y(this.startContainer, b.startContainer); var c = a == V || a == Q ? "start" : "end", d = a == U || a == Q ? "start" : "end"; return l.comparePoints(this[c + "Container"], this[c + "Offset"], b[d + "Container"], b[d + "Offset"])
            }, insertNode: function (a) { v(this); z(a, P); A(this.startContainer); if (l.isAncestorOf(a, this.startContainer, !0)) throw new B("HIERARCHY_REQUEST_ERR"); this.setStartBefore(g(a, this.startContainer, this.startOffset)) }, cloneContents: function () {
                v(this); var b, c; if (this.collapsed) return a(this).createDocumentFragment(); if (this.startContainer ===
                    this.endContainer && l.isCharacterDataNode(this.startContainer)) return b = this.startContainer.cloneNode(!0), b.data = b.data.slice(this.startOffset, this.endOffset), c = a(this).createDocumentFragment(), c.appendChild(b), c; c = new q(this, !0); b = i(c); c.detach(); return b
            }, canSurroundContents: function () { v(this); A(this.startContainer); A(this.endContainer); var a = new q(this, !0), b = a._first && c(a._first, this) || a._last && c(a._last, this); a.detach(); return !b }, surroundContents: function (a) {
                z(a, H); if (!this.canSurroundContents()) throw new r("BAD_BOUNDARYPOINTS_ERR");
                var b = this.extractContents(); if (a.hasChildNodes()) for (; a.lastChild;)a.removeChild(a.lastChild); g(a, this.startContainer, this.startOffset); a.appendChild(b); this.selectNode(a)
            }, cloneRange: function () { v(this); for (var b = new C(a(this)), c = T.length, d; c--;)d = T[c], b[d] = this[d]; return b }, toString: function () {
                v(this); var a = this.startContainer; if (a === this.endContainer && l.isCharacterDataNode(a)) return 3 == a.nodeType || 4 == a.nodeType ? a.data.slice(this.startOffset, this.endOffset) : ""; var b = [], a = new q(this, !0); h(a, function (a) {
                (3 ==
                    a.nodeType || 4 == a.nodeType) && b.push(a.data)
                }); a.detach(); return b.join("")
            }, compareNode: function (a) { v(this); var b = a.parentNode, c = l.getNodeIndex(a); if (!b) throw new B("NOT_FOUND_ERR"); a = this.comparePoint(b, c); b = this.comparePoint(b, c + 1); return 0 > a ? 0 < b ? Y : W : 0 < b ? X : R }, comparePoint: function (a, b) { v(this); t(a, "HIERARCHY_REQUEST_ERR"); y(a, this.startContainer); return 0 > l.comparePoints(a, b, this.startContainer, this.startOffset) ? -1 : 0 < l.comparePoints(a, b, this.endContainer, this.endOffset) ? 1 : 0 }, createContextualFragment: S ?
                function (a) { var b = this.startContainer, c = l.getDocument(b); if (!b) throw new B("INVALID_STATE_ERR"); var d = null; 1 == b.nodeType ? d = b : l.isCharacterDataNode(b) && (d = l.parentElement(b)); d = null === d || "HTML" == d.nodeName && l.isHtmlNamespace(l.getDocument(d).documentElement) && l.isHtmlNamespace(d) ? c.createElement("body") : d.cloneNode(!1); d.innerHTML = a; return l.fragmentFromNodeChildren(d) } : function (b) { o(this); var c = a(this).createElement("body"); c.innerHTML = b; return l.fragmentFromNodeChildren(c) }, toHtml: function () {
                    v(this);
                    var b = a(this).createElement("div"); b.appendChild(this.cloneContents()); return b.innerHTML
                }, intersectsNode: function (b, c) { v(this); t(b, "NOT_FOUND_ERR"); if (l.getDocument(b) !== a(this)) return !1; var d = b.parentNode, h = l.getNodeIndex(b); t(d, "NOT_FOUND_ERR"); var e = l.comparePoints(d, h, this.endContainer, this.endOffset), d = l.comparePoints(d, h + 1, this.startContainer, this.startOffset); return c ? 0 >= e && 0 <= d : 0 > e && 0 < d }, isPointInRange: function (a, b) {
                    v(this); t(a, "HIERARCHY_REQUEST_ERR"); y(a, this.startContainer); return 0 <=
                        l.comparePoints(a, b, this.startContainer, this.startOffset) && 0 >= l.comparePoints(a, b, this.endContainer, this.endOffset)
                }, intersectsRange: function (b, c) { v(this); if (a(b) != a(this)) throw new B("WRONG_DOCUMENT_ERR"); var d = l.comparePoints(this.startContainer, this.startOffset, b.endContainer, b.endOffset), h = l.comparePoints(this.endContainer, this.endOffset, b.startContainer, b.startOffset); return c ? 0 >= d && 0 <= h : 0 > d && 0 < h }, intersection: function (a) {
                    if (this.intersectsRange(a)) {
                        var b = l.comparePoints(this.startContainer,
                            this.startOffset, a.startContainer, a.startOffset), c = l.comparePoints(this.endContainer, this.endOffset, a.endContainer, a.endOffset), d = this.cloneRange(); -1 == b && d.setStart(a.startContainer, a.startOffset); 1 == c && d.setEnd(a.endContainer, a.endOffset); return d
                    } return null
                }, union: function (a) {
                    if (this.intersectsRange(a, !0)) {
                        var b = this.cloneRange(); -1 == l.comparePoints(a.startContainer, a.startOffset, this.startContainer, this.startOffset) && b.setStart(a.startContainer, a.startOffset); 1 == l.comparePoints(a.endContainer,
                            a.endOffset, this.endContainer, this.endOffset) && b.setEnd(a.endContainer, a.endOffset); return b
                    } throw new r("Ranges do not intersect");
                }, containsNode: function (a, b) { return b ? this.intersectsNode(a, !1) : this.compareNode(a) == R }, containsNodeContents: function (a) { return 0 <= this.comparePoint(a, 0) && 0 >= this.comparePoint(a, l.getNodeLength(a)) }, containsRange: function (a) { return this.intersection(a).equals(a) }, containsNodeText: function (a) {
                    var b = this.cloneRange(); b.selectNode(a); var c = b.getNodes([3]); return 0 < c.length ?
                        (b.setStart(c[0], 0), a = c.pop(), b.setEnd(a, a.length), a = this.containsRange(b), b.detach(), a) : this.containsNodeContents(a)
                }, createNodeIterator: function (a, b) { v(this); return new m(this, a, b) }, getNodes: function (a, b) { v(this); return n(this, a, b) }, getDocument: function () { return a(this) }, collapseBefore: function (a) { o(this); this.setEndBefore(a); this.collapse(!1) }, collapseAfter: function (a) { o(this); this.setStartAfter(a); this.collapse(!0) }, getName: function () { return "DomRange" }, equals: function (a) {
                    return C.rangesEqual(this,
                        a)
                }, inspect: function () { return p(this) }
        }; I(C, J, function (a) { o(a); a.startContainer = a.startOffset = a.endContainer = a.endOffset = null; a.collapsed = a.commonAncestorContainer = null; d(a, "detach", null); a._listeners = null }); b.rangePrototype = D.prototype; C.rangeProperties = T; C.RangeIterator = q; C.copyComparisonConstants = F; C.createPrototypeRange = I; C.inspect = p; C.getRangeDocument = a; C.rangesEqual = function (a, b) {
            return a.startContainer === b.startContainer && a.startOffset === b.startOffset && a.endContainer === b.endContainer && a.endOffset ===
                b.endOffset
        }; b.DomRange = C; b.RangeException = r
});
rangy.createModule("WrappedRange", function (b) {
    function c(a, b, c, d) {
        var g = a.duplicate(); g.collapse(c); var i = g.parentElement(); e.isAncestorOf(b, i, !0) || (i = b); if (!i.canHaveHTML) return new f(i.parentNode, e.getNodeIndex(i)); var b = e.getDocument(i).createElement("span"), r, m = c ? "StartToStart" : "StartToEnd"; do i.insertBefore(b, b.previousSibling), g.moveToElementText(b); while (0 < (r = g.compareEndPoints(m, a)) && b.previousSibling); m = b.nextSibling; if (-1 == r && m && e.isCharacterDataNode(m)) {
            g.setEndPoint(c ? "EndToStart" : "EndToEnd",
                a); if (/[\r\n]/.test(m.data)) { i = g.duplicate(); c = i.text.replace(/\r\n/g, "\r").length; for (c = i.moveStart("character", c); -1 == i.compareEndPoints("StartToEnd", i);)c++ , i.moveStart("character", 1) } else c = g.text.length; i = new f(m, c)
        } else m = (d || !c) && b.previousSibling, i = (c = (d || c) && b.nextSibling) && e.isCharacterDataNode(c) ? new f(c, 0) : m && e.isCharacterDataNode(m) ? new f(m, m.length) : new f(i, e.getNodeIndex(b)); b.parentNode.removeChild(b); return i
    } function a(a, b) {
        var c, d, f = a.offset, g = e.getDocument(a.node), i = g.body.createTextRange(),
        m = e.isCharacterDataNode(a.node); m ? (c = a.node, d = c.parentNode) : (c = a.node.childNodes, c = f < c.length ? c[f] : null, d = a.node); g = g.createElement("span"); g.innerHTML = "&#feff;"; c ? d.insertBefore(g, c) : d.appendChild(g); i.moveToElementText(g); i.collapse(!b); d.removeChild(g); if (m) i[b ? "moveStart" : "moveEnd"]("character", f); return i
    } b.requireModules(["DomUtil", "DomRange"]); var d, e = b.dom, f = e.DomPosition, g = b.DomRange; if (b.features.implementsDomRange && (!b.features.implementsTextRange || !b.config.preferTextRange)) (function () {
        function a(b) {
            for (var c =
                j.length, d; c--;)d = j[c], b[d] = b.nativeRange[d]
        } var c, j = g.rangeProperties, f; d = function (b) { if (!b) throw Error("Range must be specified"); this.nativeRange = b; a(this) }; g.createPrototypeRange(d, function (a, b, c, d, h) { var e = a.endContainer !== d || a.endOffset != h; if (a.startContainer !== b || a.startOffset != c || e) a.setEnd(d, h), a.setStart(b, c) }, function (a) { a.nativeRange.detach(); a.detached = !0; for (var b = j.length, c; b--;)c = j[b], a[c] = null }); c = d.prototype; c.selectNode = function (b) { this.nativeRange.selectNode(b); a(this) }; c.deleteContents =
            function () { this.nativeRange.deleteContents(); a(this) }; c.extractContents = function () { var b = this.nativeRange.extractContents(); a(this); return b }; c.cloneContents = function () { return this.nativeRange.cloneContents() }; c.surroundContents = function (b) { this.nativeRange.surroundContents(b); a(this) }; c.collapse = function (b) { this.nativeRange.collapse(b); a(this) }; c.cloneRange = function () { return new d(this.nativeRange.cloneRange()) }; c.refresh = function () { a(this) }; c.toString = function () { return this.nativeRange.toString() };
        var i = document.createTextNode("test"); e.getBody(document).appendChild(i); var q = document.createRange(); q.setStart(i, 0); q.setEnd(i, 0); try { q.setStart(i, 1), c.setStart = function (b, c) { this.nativeRange.setStart(b, c); a(this) }, c.setEnd = function (b, c) { this.nativeRange.setEnd(b, c); a(this) }, f = function (b) { return function (c) { this.nativeRange[b](c); a(this) } } } catch (r) {
        c.setStart = function (b, c) { try { this.nativeRange.setStart(b, c) } catch (d) { this.nativeRange.setEnd(b, c), this.nativeRange.setStart(b, c) } a(this) }, c.setEnd = function (b,
            c) { try { this.nativeRange.setEnd(b, c) } catch (d) { this.nativeRange.setStart(b, c), this.nativeRange.setEnd(b, c) } a(this) }, f = function (b, c) { return function (d) { try { this.nativeRange[b](d) } catch (e) { this.nativeRange[c](d), this.nativeRange[b](d) } a(this) } }
        } c.setStartBefore = f("setStartBefore", "setEndBefore"); c.setStartAfter = f("setStartAfter", "setEndAfter"); c.setEndBefore = f("setEndBefore", "setStartBefore"); c.setEndAfter = f("setEndAfter", "setStartAfter"); q.selectNodeContents(i); c.selectNodeContents = q.startContainer ==
            i && q.endContainer == i && 0 == q.startOffset && q.endOffset == i.length ? function (b) { this.nativeRange.selectNodeContents(b); a(this) } : function (a) { this.setStart(a, 0); this.setEnd(a, g.getEndOffset(a)) }; q.selectNodeContents(i); q.setEnd(i, 3); f = document.createRange(); f.selectNodeContents(i); f.setEnd(i, 4); f.setStart(i, 2); c.compareBoundaryPoints = -1 == q.compareBoundaryPoints(q.START_TO_END, f) & 1 == q.compareBoundaryPoints(q.END_TO_START, f) ? function (a, b) {
                b = b.nativeRange || b; a == b.START_TO_END ? a = b.END_TO_START : a == b.END_TO_START &&
                    (a = b.START_TO_END); return this.nativeRange.compareBoundaryPoints(a, b)
            } : function (a, b) { return this.nativeRange.compareBoundaryPoints(a, b.nativeRange || b) }; b.util.isHostMethod(q, "createContextualFragment") && (c.createContextualFragment = function (a) { return this.nativeRange.createContextualFragment(a) }); e.getBody(document).removeChild(i); q.detach(); f.detach()
    })(), b.createNativeRange = function (a) { a = a || document; return a.createRange() }; else if (b.features.implementsTextRange) {
        d = function (a) { this.textRange = a; this.refresh() };
        d.prototype = new g(document); d.prototype.refresh = function () { var a, b, d = this.textRange; a = d.parentElement(); var f = d.duplicate(); f.collapse(!0); b = f.parentElement(); f = d.duplicate(); f.collapse(!1); d = f.parentElement(); b = b == d ? b : e.getCommonAncestor(b, d); b = b == a ? b : e.getCommonAncestor(a, b); 0 == this.textRange.compareEndPoints("StartToEnd", this.textRange) ? b = a = c(this.textRange, b, !0, !0) : (a = c(this.textRange, b, !0, !1), b = c(this.textRange, b, !1, !1)); this.setStart(a.node, a.offset); this.setEnd(b.node, b.offset) }; g.copyComparisonConstants(d);
        var i = function () { return this }(); "undefined" == typeof i.Range && (i.Range = d); b.createNativeRange = function (a) { a = a || document; return a.body.createTextRange() }
    } b.features.implementsTextRange && (d.rangeToTextRange = function (b) { if (b.collapsed) return a(new f(b.startContainer, b.startOffset), !0); var c = a(new f(b.startContainer, b.startOffset), !0), d = a(new f(b.endContainer, b.endOffset), !1), b = e.getDocument(b.startContainer).body.createTextRange(); b.setEndPoint("StartToStart", c); b.setEndPoint("EndToEnd", d); return b });
    d.prototype.getName = function () { return "WrappedRange" }; b.WrappedRange = d; b.createRange = function (a) { a = a || document; return new d(b.createNativeRange(a)) }; b.createRangyRange = function (a) { a = a || document; return new g(a) }; b.createIframeRange = function (a) { return b.createRange(e.getIframeDocument(a)) }; b.createIframeRangyRange = function (a) { return b.createRangyRange(e.getIframeDocument(a)) }; b.addCreateMissingNativeApiListener(function (a) {
        a = a.document; if (typeof a.createRange == "undefined") a.createRange = function () { return b.createRange(this) };
        a = a = null
    })
});
rangy.createModule("WrappedSelection", function (b, c) {
    function a(a) { return (a || window).getSelection() } function d(a) { return (a || window).document.selection } function e(a, b, c) { var d = c ? "end" : "start", c = c ? "start" : "end"; a.anchorNode = b[d + "Container"]; a.anchorOffset = b[d + "Offset"]; a.focusNode = b[c + "Container"]; a.focusOffset = b[c + "Offset"] } function f(a) { a.anchorNode = a.focusNode = null; a.anchorOffset = a.focusOffset = 0; a.rangeCount = 0; a.isCollapsed = !0; a._ranges.length = 0 } function g(a) {
        var c; a instanceof x ? (c = a._selectionNativeRange,
            c || (c = b.createNativeRange(m.getDocument(a.startContainer)), c.setEnd(a.endContainer, a.endOffset), c.setStart(a.startContainer, a.startOffset), a._selectionNativeRange = c, a.attachListener("detach", function () { this._selectionNativeRange = null }))) : a instanceof o ? c = a.nativeRange : b.features.implementsDomRange && a instanceof m.getWindow(a.startContainer).Range && (c = a); return c
    } function i(a) {
        var b = a.getNodes(), c; a: if (!b.length || 1 != b[0].nodeType) c = !1; else {
            c = 1; for (var d = b.length; c < d; ++c)if (!m.isAncestorOf(b[0], b[c])) {
                c =
                !1; break a
            } c = !0
        } if (!c) throw Error("getSingleElementFromRange: range " + a.inspect() + " did not consist of a single element"); return b[0]
    } function h(a, b) { var c = new o(b); a._ranges = [c]; e(a, c, !1); a.rangeCount = 1; a.isCollapsed = c.collapsed } function k(a) {
        a._ranges.length = 0; if ("None" == a.docSelection.type) f(a); else {
            var c = a.docSelection.createRange(); if (c && "undefined" != typeof c.text) h(a, c); else {
            a.rangeCount = c.length; for (var d, j = m.getDocument(c.item(0)), k = 0; k < a.rangeCount; ++k)d = b.createRange(j), d.selectNode(c.item(k)),
                a._ranges.push(d); a.isCollapsed = 1 == a.rangeCount && a._ranges[0].collapsed; e(a, a._ranges[a.rangeCount - 1], !1)
            }
        }
    } function j(a, b) { for (var c = a.docSelection.createRange(), d = i(b), e = m.getDocument(c.item(0)), e = m.getBody(e).createControlRange(), h = 0, j = c.length; h < j; ++h)e.add(c.item(h)); try { e.add(d) } catch (f) { throw Error("addRange(): Element within the specified Range could not be added to control selection (does it have layout?)"); } e.select(); k(a) } function n(a, b, c) {
    this.nativeSelection = a; this.docSelection = b; this._ranges =
        []; this.win = c; this.refresh()
    } function p(a, b) { for (var c = m.getDocument(b[0].startContainer), c = m.getBody(c).createControlRange(), d = 0, e; d < rangeCount; ++d) { e = i(b[d]); try { c.add(e) } catch (h) { throw Error("setRanges(): Element within the one of the specified Ranges could not be added to control selection (does it have layout?)"); } } c.select(); k(a) } function q(a, b) { if (a.anchorNode && m.getDocument(a.anchorNode) !== m.getDocument(b)) throw new z("WRONG_DOCUMENT_ERR"); } function r(a) {
        var b = [], c = new w(a.anchorNode, a.anchorOffset),
        d = new w(a.focusNode, a.focusOffset), e = "function" == typeof a.getName ? a.getName() : "Selection"; if ("undefined" != typeof a.rangeCount) for (var h = 0, j = a.rangeCount; h < j; ++h)b[h] = x.inspect(a.getRangeAt(h)); return "[" + e + "(Ranges: " + b.join(", ") + ")(anchor: " + c.inspect() + ", focus: " + d.inspect() + "]"
    } b.requireModules(["DomUtil", "DomRange", "WrappedRange"]); b.config.checkSelectionRanges = !0; var m = b.dom, s = b.util, x = b.DomRange, o = b.WrappedRange, z = b.DOMException, w = m.DomPosition, y, A, t = b.util.isHostMethod(window, "getSelection"),
        v = b.util.isHostObject(document, "selection"), D = v && (!t || b.config.preferTextRange); D ? (y = d, b.isSelectionValid = function (a) { var a = (a || window).document, b = a.selection; return "None" != b.type || m.getDocument(b.createRange().parentElement()) == a }) : t ? (y = a, b.isSelectionValid = function () { return !0 }) : c.fail("Neither document.selection or window.getSelection() detected."); b.getNativeSelection = y; var t = y(), K = b.createNativeRange(document), F = m.getBody(document), E = s.areHostObjects(t, s.areHostProperties(t, ["anchorOffset", "focusOffset"]));
    b.features.selectionHasAnchorAndFocus = E; var I = s.isHostMethod(t, "extend"); b.features.selectionHasExtend = I; var N = "number" == typeof t.rangeCount; b.features.selectionHasRangeCount = N; var J = !1, C = !0; s.areHostMethods(t, ["addRange", "getRangeAt", "removeAllRanges"]) && ("number" == typeof t.rangeCount && b.features.implementsDomRange) && function () {
        var a = document.createElement("iframe"); F.appendChild(a); var b = m.getIframeDocument(a); b.open(); b.write("<html><head></head><body>12</body></html>"); b.close(); var c = m.getIframeWindow(a).getSelection(),
            d = b.documentElement.lastChild.firstChild, b = b.createRange(); b.setStart(d, 1); b.collapse(true); c.addRange(b); C = c.rangeCount == 1; c.removeAllRanges(); var e = b.cloneRange(); b.setStart(d, 0); e.setEnd(d, 2); c.addRange(b); c.addRange(e); J = c.rangeCount == 2; b.detach(); e.detach(); F.removeChild(a)
    }(); b.features.selectionSupportsMultipleRanges = J; b.features.collapsedNonEditableSelectionsSupported = C; var l = !1, u; F && s.isHostMethod(F, "createControlRange") && (u = F.createControlRange(), s.areHostProperties(u, ["item", "add"]) && (l =
        !0)); b.features.implementsControlRange = l; A = E ? function (a) { return a.anchorNode === a.focusNode && a.anchorOffset === a.focusOffset } : function (a) { return a.rangeCount ? a.getRangeAt(a.rangeCount - 1).collapsed : false }; var B; s.isHostMethod(t, "getRangeAt") ? B = function (a, b) { try { return a.getRangeAt(b) } catch (c) { return null } } : E && (B = function (a) {
            var c = m.getDocument(a.anchorNode), c = b.createRange(c); c.setStart(a.anchorNode, a.anchorOffset); c.setEnd(a.focusNode, a.focusOffset); if (c.collapsed !== this.isCollapsed) {
                c.setStart(a.focusNode,
                    a.focusOffset); c.setEnd(a.anchorNode, a.anchorOffset)
            } return c
        }); b.getSelection = function (a) { var a = a || window, b = a._rangySelection, c = y(a), e = v ? d(a) : null; if (b) { b.nativeSelection = c; b.docSelection = e; b.refresh(a) } else { b = new n(c, e, a); a._rangySelection = b } return b }; b.getIframeSelection = function (a) { return b.getSelection(m.getIframeWindow(a)) }; u = n.prototype; if (!D && E && s.areHostMethods(t, ["removeAllRanges", "addRange"])) {
        u.removeAllRanges = function () { this.nativeSelection.removeAllRanges(); f(this) }; var L = function (a,
            c) { var d = x.getRangeDocument(c), d = b.createRange(d); d.collapseToPoint(c.endContainer, c.endOffset); a.nativeSelection.addRange(g(d)); a.nativeSelection.extend(c.startContainer, c.startOffset); a.refresh() }; u.addRange = N ? function (a, c) {
                if (l && v && this.docSelection.type == "Control") j(this, a); else if (c && I) L(this, a); else {
                    var d; if (J) d = this.rangeCount; else { this.removeAllRanges(); d = 0 } this.nativeSelection.addRange(g(a)); this.rangeCount = this.nativeSelection.rangeCount; if (this.rangeCount == d + 1) {
                        if (b.config.checkSelectionRanges) (d =
                            B(this.nativeSelection, this.rangeCount - 1)) && !x.rangesEqual(d, a) && (a = new o(d)); this._ranges[this.rangeCount - 1] = a; e(this, a, H(this.nativeSelection)); this.isCollapsed = A(this)
                    } else this.refresh()
                }
            } : function (a, b) { if (b && I) L(this, a); else { this.nativeSelection.addRange(g(a)); this.refresh() } }; u.setRanges = function (a) { if (l && a.length > 1) p(this, a); else { this.removeAllRanges(); for (var b = 0, c = a.length; b < c; ++b)this.addRange(a[b]) } }
        } else if (s.isHostMethod(t, "empty") && s.isHostMethod(K, "select") && l && D) u.removeAllRanges =
            function () { try { this.docSelection.empty(); if (this.docSelection.type != "None") { var a; if (this.anchorNode) a = m.getDocument(this.anchorNode); else if (this.docSelection.type == "Control") { var b = this.docSelection.createRange(); b.length && (a = m.getDocument(b.item(0)).body.createTextRange()) } if (a) { a.body.createTextRange().select(); this.docSelection.empty() } } } catch (c) { } f(this) }, u.addRange = function (a) {
                if (this.docSelection.type == "Control") j(this, a); else {
                    o.rangeToTextRange(a).select(); this._ranges[0] = a; this.rangeCount =
                        1; this.isCollapsed = this._ranges[0].collapsed; e(this, a, false)
                }
            }, u.setRanges = function (a) { this.removeAllRanges(); var b = a.length; b > 1 ? p(this, a) : b && this.addRange(a[0]) }; else return c.fail("No means of selecting a Range or TextRange was found"), !1; u.getRangeAt = function (a) { if (a < 0 || a >= this.rangeCount) throw new z("INDEX_SIZE_ERR"); return this._ranges[a] }; var G; if (D) G = function (a) {
                var c; if (b.isSelectionValid(a.win)) c = a.docSelection.createRange(); else { c = m.getBody(a.win.document).createTextRange(); c.collapse(true) } a.docSelection.type ==
                    "Control" ? k(a) : c && typeof c.text != "undefined" ? h(a, c) : f(a)
            }; else if (s.isHostMethod(t, "getRangeAt") && "number" == typeof t.rangeCount) G = function (a) { if (l && v && a.docSelection.type == "Control") k(a); else { a._ranges.length = a.rangeCount = a.nativeSelection.rangeCount; if (a.rangeCount) { for (var c = 0, d = a.rangeCount; c < d; ++c)a._ranges[c] = new b.WrappedRange(a.nativeSelection.getRangeAt(c)); e(a, a._ranges[a.rangeCount - 1], H(a.nativeSelection)); a.isCollapsed = A(a) } else f(a) } }; else if (E && "boolean" == typeof t.isCollapsed && "boolean" ==
                typeof K.collapsed && b.features.implementsDomRange) G = function (a) { var b; b = a.nativeSelection; if (b.anchorNode) { b = B(b, 0); a._ranges = [b]; a.rangeCount = 1; b = a.nativeSelection; a.anchorNode = b.anchorNode; a.anchorOffset = b.anchorOffset; a.focusNode = b.focusNode; a.focusOffset = b.focusOffset; a.isCollapsed = A(a) } else f(a) }; else return c.fail("No means of obtaining a Range or TextRange from the user's selection was found"), !1; u.refresh = function (a) {
                    var b = a ? this._ranges.slice(0) : null; G(this); if (a) {
                        a = b.length; if (a != this._ranges.length) return false;
                        for (; a--;)if (!x.rangesEqual(b[a], this._ranges[a])) return false; return true
                    }
                }; var P = function (a, b) { var c = a.getAllRanges(), d = false; a.removeAllRanges(); for (var e = 0, h = c.length; e < h; ++e)d || b !== c[e] ? a.addRange(c[e]) : d = true; a.rangeCount || f(a) }; u.removeRange = l ? function (a) {
                    if (this.docSelection.type == "Control") {
                        for (var b = this.docSelection.createRange(), a = i(a), c = m.getDocument(b.item(0)), c = m.getBody(c).createControlRange(), d, e = false, h = 0, j = b.length; h < j; ++h) { d = b.item(h); d !== a || e ? c.add(b.item(h)) : e = true } c.select();
                        k(this)
                    } else P(this, a)
                } : function (a) { P(this, a) }; var H; !D && E && b.features.implementsDomRange ? (H = function (a) { var b = false; a.anchorNode && (b = m.comparePoints(a.anchorNode, a.anchorOffset, a.focusNode, a.focusOffset) == 1); return b }, u.isBackwards = function () { return H(this) }) : H = u.isBackwards = function () { return false }; u.toString = function () { for (var a = [], b = 0, c = this.rangeCount; b < c; ++b)a[b] = "" + this._ranges[b]; return a.join("") }; u.collapse = function (a, c) {
                    q(this, a); var d = b.createRange(m.getDocument(a)); d.collapseToPoint(a,
                        c); this.removeAllRanges(); this.addRange(d); this.isCollapsed = true
                }; u.collapseToStart = function () { if (this.rangeCount) { var a = this._ranges[0]; this.collapse(a.startContainer, a.startOffset) } else throw new z("INVALID_STATE_ERR"); }; u.collapseToEnd = function () { if (this.rangeCount) { var a = this._ranges[this.rangeCount - 1]; this.collapse(a.endContainer, a.endOffset) } else throw new z("INVALID_STATE_ERR"); }; u.selectAllChildren = function (a) {
                    q(this, a); var c = b.createRange(m.getDocument(a)); c.selectNodeContents(a); this.removeAllRanges();
                    this.addRange(c)
                }; u.deleteFromDocument = function () { if (l && v && this.docSelection.type == "Control") { for (var a = this.docSelection.createRange(), b; a.length;) { b = a.item(0); a.remove(b); b.parentNode.removeChild(b) } this.refresh() } else if (this.rangeCount) { a = this.getAllRanges(); this.removeAllRanges(); b = 0; for (var c = a.length; b < c; ++b)a[b].deleteContents(); this.addRange(a[c - 1]) } }; u.getAllRanges = function () { return this._ranges.slice(0) }; u.setSingleRange = function (a) { this.setRanges([a]) }; u.containsNode = function (a, b) {
                    for (var c =
                        0, d = this._ranges.length; c < d; ++c)if (this._ranges[c].containsNode(a, b)) return true; return false
                }; u.toHtml = function () { var a = ""; if (this.rangeCount) { for (var a = x.getRangeDocument(this._ranges[0]).createElement("div"), b = 0, c = this._ranges.length; b < c; ++b)a.appendChild(this._ranges[b].cloneContents()); a = a.innerHTML } return a }; u.getName = function () { return "WrappedSelection" }; u.inspect = function () { return r(this) }; u.detach = function () { this.win = this.anchorNode = this.focusNode = this.win._rangySelection = null }; n.inspect =
                    r; b.Selection = n; b.selectionPrototype = u; b.addCreateMissingNativeApiListener(function (a) { if (typeof a.getSelection == "undefined") a.getSelection = function () { return b.getSelection(this) }; a = null })
}); var Base = function () { };
Base.extend = function (b, c) {
    var a = Base.prototype.extend; Base._prototyping = !0; var d = new this; a.call(d, b); d.base = function () { }; delete Base._prototyping; var e = d.constructor, f = d.constructor = function () { if (!Base._prototyping) if (this._constructing || this.constructor == f) this._constructing = !0, e.apply(this, arguments), delete this._constructing; else if (null != arguments[0]) return (arguments[0].extend || a).call(arguments[0], d) }; f.ancestor = this; f.extend = this.extend; f.forEach = this.forEach; f.implement = this.implement; f.prototype =
        d; f.toString = this.toString; f.valueOf = function (a) { return "object" == a ? f : e.valueOf() }; a.call(f, c); "function" == typeof f.init && f.init(); return f
};
Base.prototype = {
    extend: function (b, c) {
        if (1 < arguments.length) { var a = this[b]; if (a && "function" == typeof c && (!a.valueOf || a.valueOf() != c.valueOf()) && /\bbase\b/.test(c)) { var d = c.valueOf(), c = function () { var b = this.base || Base.prototype.base; this.base = a; var c = d.apply(this, arguments); this.base = b; return c }; c.valueOf = function (a) { return "object" == a ? c : d }; c.toString = Base.toString } this[b] = c } else if (b) {
            var e = Base.prototype.extend; !Base._prototyping && "function" != typeof this && (e = this.extend || e); for (var f = { toSource: null },
                g = ["constructor", "toString", "valueOf"], i = Base._prototyping ? 0 : 1; h = g[i++];)b[h] != f[h] && e.call(this, h, b[h]); for (var h in b) f[h] || e.call(this, h, b[h])
        } return this
    }
};
Base = Base.extend({ constructor: function (b) { this.extend(b) } }, { ancestor: Object, version: "1.1", forEach: function (b, c, a) { for (var d in b) void 0 === this.prototype[d] && c.call(a, b[d], d, b) }, implement: function () { for (var b = 0; b < arguments.length; b++)if ("function" == typeof arguments[b]) arguments[b](this.prototype); else this.prototype.extend(arguments[b]); return this }, toString: function () { return "" + this.valueOf() } });
wysihtml5.browser = function () {
    var b = navigator.userAgent, c = document.createElement("div"), a = -1 !== b.indexOf("MSIE") && -1 === b.indexOf("Opera"), d = -1 !== b.indexOf("Gecko") && -1 === b.indexOf("KHTML"), e = -1 !== b.indexOf("AppleWebKit/"), f = -1 !== b.indexOf("Chrome/"), g = -1 !== b.indexOf("Opera/"); return {
        USER_AGENT: b, supported: function () {
            var a = this.USER_AGENT.toLowerCase(), b = "contentEditable" in c, d = document.execCommand && document.queryCommandSupported && document.queryCommandState, e = document.querySelector && document.querySelectorAll,
            a = this.isIos() && 5 > (/ipad|iphone|ipod/.test(a) && a.match(/ os (\d+).+? like mac os x/) || [, 0])[1] || -1 !== a.indexOf("opera mobi") || -1 !== a.indexOf("hpwos/"); return b && d && e && !a
        }, isTouchDevice: function () { return this.supportsEvent("touchmove") }, isIos: function () { var a = this.USER_AGENT.toLowerCase(); return -1 !== a.indexOf("webkit") && -1 !== a.indexOf("mobile") }, supportsSandboxedIframes: function () { return a }, throwsMixedContentWarningWhenIframeSrcIsEmpty: function () { return !("querySelector" in document) }, displaysCaretInEmptyContentEditableCorrectly: function () { return !d },
        hasCurrentStyleProperty: function () { return "currentStyle" in c }, insertsLineBreaksOnReturn: function () { return d }, supportsPlaceholderAttributeOn: function (a) { return "placeholder" in a }, supportsEvent: function (a) { var b; if (!(b = "on" + a in c)) c.setAttribute("on" + a, "return;"), b = "function" === typeof c["on" + a]; return b }, supportsEventsInIframeCorrectly: function () { return !g }, firesOnDropOnlyWhenOnDragOverIsCancelled: function () { return e || d }, supportsDataTransfer: function () { try { return e && (window.Clipboard || window.DataTransfer).prototype.getData } catch (a) { return !1 } },
        supportsHTML5Tags: function (a) { a = a.createElement("div"); a.innerHTML = "<article>foo</article>"; return "<article>foo</article>" === a.innerHTML.toLowerCase() }, supportsCommand: function () { var b = { formatBlock: a, insertUnorderedList: a || g || e, insertOrderedList: a || g || e }, c = { insertHTML: d }; return function (a, d) { if (!b[d]) { try { return a.queryCommandSupported(d) } catch (e) { } try { return a.queryCommandEnabled(d) } catch (f) { return !!c[d] } } return !1 } }(), doesAutoLinkingInContentEditable: function () { return a }, canDisableAutoLinking: function () {
            return this.supportsCommand(document,
                "AutoUrlDetect")
        }, clearsContentEditableCorrectly: function () { return d || g || e }, supportsGetAttributeCorrectly: function () { return "1" != document.createElement("td").getAttribute("rowspan") }, canSelectImagesInContentEditable: function () { return d || a || g }, clearsListsInContentEditableCorrectly: function () { return d || a || e }, autoScrollsToCaret: function () { return !e }, autoClosesUnclosedTags: function () {
            var a = c.cloneNode(!1), b; a.innerHTML = "<p><div></div>"; a = a.innerHTML.toLowerCase(); b = "<p></p><div></div>" === a || "<p><div></div></p>" ===
                a; this.autoClosesUnclosedTags = function () { return b }; return b
        }, supportsNativeGetElementsByClassName: function () { return -1 !== ("" + document.getElementsByClassName).indexOf("[native code]") }, supportsSelectionModify: function () { return "getSelection" in window && "modify" in window.getSelection() }, supportsClassList: function () { return "classList" in c }, needsSpaceAfterLineBreak: function () { return g }, supportsSpeechApiOn: function (a) { return 11 <= (b.match(/Chrome\/(\d+)/) || [, 0])[1] && ("onwebkitspeechchange" in a || "speech" in a) },
        crashesWhenDefineProperty: function (b) { return a && ("XMLHttpRequest" === b || "XDomainRequest" === b) }, doesAsyncFocus: function () { return a }, hasProblemsSettingCaretAfterImg: function () { return a }, hasUndoInContextMenu: function () { return d || f || g }
    }
}();
wysihtml5.lang.array = function (b) { return { contains: function (c) { if (b.indexOf) return -1 !== b.indexOf(c); for (var a = 0, d = b.length; a < d; a++)if (b[a] === c) return !0; return !1 }, without: function (c) { for (var c = wysihtml5.lang.array(c), a = [], d = 0, e = b.length; d < e; d++)c.contains(b[d]) || a.push(b[d]); return a }, get: function () { for (var c = 0, a = b.length, d = []; c < a; c++)d.push(b[c]); return d } } };
wysihtml5.lang.Dispatcher = Base.extend({
    observe: function (b, c) { this.events = this.events || {}; this.events[b] = this.events[b] || []; this.events[b].push(c); return this }, on: function () { return this.observe.apply(this, wysihtml5.lang.array(arguments).get()) }, fire: function (b, c) { this.events = this.events || {}; for (var a = this.events[b] || [], d = 0; d < a.length; d++)a[d].call(this, c); return this }, stopObserving: function (b, c) {
    this.events = this.events || {}; var a = 0, d, e; if (b) {
        d = this.events[b] || []; for (e = []; a < d.length; a++)d[a] !== c && c &&
            e.push(d[a]); this.events[b] = e
    } else this.events = {}; return this
    }
}); wysihtml5.lang.object = function (b) { return { merge: function (c) { for (var a in c) b[a] = c[a]; return this }, get: function () { return b }, clone: function () { var c = {}, a; for (a in b) c[a] = b[a]; return c }, isArray: function () { return "[object Array]" === Object.prototype.toString.call(b) } } };
(function () { var b = /^\s+/, c = /\s+$/; wysihtml5.lang.string = function (a) { a = "" + a; return { trim: function () { return a.replace(b, "").replace(c, "") }, interpolate: function (b) { for (var c in b) a = this.replace("#{" + c + "}").by(b[c]); return a }, replace: function (b) { return { by: function (c) { return a.split(b).join(c) } } } } } })();
(function (b) {
    function c(a) { return a.replace(e, function (a, b) { var c = (b.match(f) || [])[1] || "", d = i[c], b = b.replace(f, ""); b.split(d).length > b.split(c).length && (b += c, c = ""); var e = d = b; b.length > g && (e = e.substr(0, g) + "..."); "www." === d.substr(0, 4) && (d = "http://" + d); return '<a href="' + d + '">' + e + "</a>" + c }) } function a(h) {
        if (!d.contains(h.nodeName)) if (h.nodeType === b.TEXT_NODE && h.data.match(e)) {
            var f = h.parentNode, j; j = f.ownerDocument; var g = j._wysihtml5_tempElement; g || (g = j._wysihtml5_tempElement = j.createElement("div")); j =
                g; j.innerHTML = "<span></span>" + c(h.data); for (j.removeChild(j.firstChild); j.firstChild;)f.insertBefore(j.firstChild, h); f.removeChild(h)
        } else { f = b.lang.array(h.childNodes).get(); j = f.length; for (g = 0; g < j; g++)a(f[g]); return h }
    } var d = b.lang.array("CODE PRE A SCRIPT HEAD TITLE STYLE".split(" ")), e = /((https?:\/\/|www\.)[^\s<]{3,})/gi, f = /([^\w\/\-](,?))$/i, g = 100, i = { ")": "(", "]": "[", "}": "{" }; b.dom.autoLink = function (b) {
        var c; a: {
            c = b; for (var e; c.parentNode;) {
                c = c.parentNode; e = c.nodeName; if (d.contains(e)) { c = !0; break a } if ("body" ===
                    e) break
            } c = !1
        } if (c) return b; b === b.ownerDocument.documentElement && (b = b.ownerDocument.body); return a(b)
    }; b.dom.autoLink.URL_REG_EXP = e
})(wysihtml5);
(function (b) { var c = b.browser.supportsClassList(), a = b.dom; a.addClass = function (b, e) { if (c) return b.classList.add(e); a.hasClass(b, e) || (b.className += " " + e) }; a.removeClass = function (a, b) { if (c) return a.classList.remove(b); a.className = a.className.replace(RegExp("(^|\\s+)" + b + "(\\s+|$)"), " ") }; a.hasClass = function (a, b) { if (c) return a.classList.contains(b); var f = a.className; return 0 < f.length && (f == b || RegExp("(^|\\s)" + b + "(\\s|$)").test(f)) } })(wysihtml5);
wysihtml5.dom.contains = function () { var b = document.documentElement; if (b.contains) return function (b, a) { a.nodeType !== wysihtml5.ELEMENT_NODE && (a = a.parentNode); return b !== a && b.contains(a) }; if (b.compareDocumentPosition) return function (b, a) { return !!(b.compareDocumentPosition(a) & 16) } }();
wysihtml5.dom.convertToList = function () {
    function b(b, a) { var d = b.createElement("li"); a.appendChild(d); return d } return function (c, a) {
        if ("UL" === c.nodeName || "OL" === c.nodeName || "MENU" === c.nodeName) return c; var d = c.ownerDocument, e = d.createElement(a), f = c.querySelectorAll("br"), g = f.length, i, h, k, j, n; for (n = 0; n < g; n++)for (i = f[n]; (h = i.parentNode) && h !== c && h.lastChild === i;) { if ("block" === wysihtml5.dom.getStyle("display").from(h)) { h.removeChild(i); break } wysihtml5.dom.insert(i).after(i.parentNode) } f = wysihtml5.lang.array(c.childNodes).get();
        g = f.length; for (n = 0; n < g; n++)j = j || b(d, e), i = f[n], h = "block" === wysihtml5.dom.getStyle("display").from(i), k = "BR" === i.nodeName, h ? (j = j.firstChild ? b(d, e) : j, j.appendChild(i), j = null) : k ? j = j.firstChild ? null : j : j.appendChild(i); c.parentNode.replaceChild(e, c); return e
    }
}(); wysihtml5.dom.copyAttributes = function (b) { return { from: function (c) { return { to: function (a) { for (var d, e = 0, f = b.length; e < f; e++)d = b[e], "undefined" !== typeof c[d] && "" !== c[d] && (a[d] = c[d]); return { andTo: arguments.callee } } } } } };
(function (b) { var c = ["-webkit-box-sizing", "-moz-box-sizing", "-ms-box-sizing", "box-sizing"], a = function (a) { var e; a: for (var f = 0, g = c.length; f < g; f++)if ("border-box" === b.getStyle(c[f]).from(a)) { e = c[f]; break a } return e ? parseInt(b.getStyle("width").from(a), 10) < a.offsetWidth : !1 }; b.copyStyles = function (d) { return { from: function (e) { a(e) && (d = wysihtml5.lang.array(d).without(c)); for (var f = "", g = d.length, i = 0, h; i < g; i++)h = d[i], f += h + ":" + b.getStyle(h).from(e) + ";"; return { to: function (a) { b.setStyles(f).on(a); return { andTo: arguments.callee } } } } } } })(wysihtml5.dom);
(function (b) { b.dom.delegate = function (c, a, d, e) { return b.dom.observe(c, d, function (d) { for (var g = d.target, i = b.lang.array(c.querySelectorAll(a)); g && g !== c;) { if (i.contains(g)) { e.call(g, d); break } g = g.parentNode } }) } })(wysihtml5);
wysihtml5.dom.getAsDom = function () {
    var b = "abbr article aside audio bdi canvas command datalist details figcaption figure footer header hgroup keygen mark meter nav output progress rp rt ruby svg section source summary time track video wbr".split(" "); return function (c, a) {
        var a = a || document, d; if ("object" === typeof c && c.nodeType) d = a.createElement("div"), d.appendChild(c); else if (wysihtml5.browser.supportsHTML5Tags(a)) d = a.createElement("div"), d.innerHTML = c; else {
            d = a; if (!d._wysihtml5_supportsHTML5Tags) {
                for (var e =
                    0, f = b.length; e < f; e++)d.createElement(b[e]); d._wysihtml5_supportsHTML5Tags = !0
            } d = a; e = d.createElement("div"); e.style.display = "none"; d.body.appendChild(e); try { e.innerHTML = c } catch (g) { } d.body.removeChild(e); d = e
        } return d
    }
}();
wysihtml5.dom.getParentElement = function () {
    function b(b, a) { return !a || !a.length ? !0 : "string" === typeof a ? b === a : wysihtml5.lang.array(a).contains(b) } return function (c, a, d) {
        d = d || 50; if (a.className || a.classRegExp) { a: { for (var e = a.nodeName, f = a.className, a = a.classRegExp; d-- && c && "BODY" !== c.nodeName;) { var g; if (g = c.nodeType === wysihtml5.ELEMENT_NODE) if (g = b(c.nodeName, e)) { g = f; var i = (c.className || "").match(a) || []; g = !g ? !!i.length : i[i.length - 1] === g } if (g) break a; c = c.parentNode } c = null } return c } a: {
            e = a.nodeName; for (f = d; f-- &&
                c && "BODY" !== c.nodeName;) { if (b(c.nodeName, e)) break a; c = c.parentNode } c = null
        } return c
    }
}();
wysihtml5.dom.getStyle = function () {
    function b(b) { return b.replace(a, function (a) { return a.charAt(1).toUpperCase() }) } var c = { "float": "styleFloat" in document.createElement("div").style ? "styleFloat" : "cssFloat" }, a = /\-[a-z]/g; return function (a) {
        return {
            from: function (e) {
                if (e.nodeType === wysihtml5.ELEMENT_NODE) {
                    var f = e.ownerDocument, g = c[a] || b(a), i = e.style, h = e.currentStyle, k = i[g]; if (k) return k; if (h) try { return h[g] } catch (j) { } var g = f.defaultView || f.parentWindow, f = ("height" === a || "width" === a) && "TEXTAREA" === e.nodeName,
                        n; if (g.getComputedStyle) return f && (n = i.overflow, i.overflow = "hidden"), e = g.getComputedStyle(e, null).getPropertyValue(a), f && (i.overflow = n || ""), e
                }
            }
        }
    }
}(); wysihtml5.dom.hasElementWithTagName = function () { var b = {}, c = 1; return function (a, d) { var e = (a._wysihtml5_identifier || (a._wysihtml5_identifier = c++)) + ":" + d, f = b[e]; f || (f = b[e] = a.getElementsByTagName(d)); return 0 < f.length } }();
(function (b) { var c = {}, a = 1; b.dom.hasElementWithClassName = function (d, e) { if (!b.browser.supportsNativeGetElementsByClassName()) return !!d.querySelector("." + e); var f = (d._wysihtml5_identifier || (d._wysihtml5_identifier = a++)) + ":" + e, g = c[f]; g || (g = c[f] = d.getElementsByClassName(e)); return 0 < g.length } })(wysihtml5); wysihtml5.dom.insert = function (b) { return { after: function (c) { c.parentNode.insertBefore(b, c.nextSibling) }, before: function (c) { c.parentNode.insertBefore(b, c) }, into: function (c) { c.appendChild(b) } } };
wysihtml5.dom.insertCSS = function (b) { b = b.join("\n"); return { into: function (c) { var a = c.head || c.getElementsByTagName("head")[0], d = c.createElement("style"); d.type = "text/css"; d.styleSheet ? d.styleSheet.cssText = b : d.appendChild(c.createTextNode(b)); a && a.appendChild(d) } } };
wysihtml5.dom.observe = function (b, c, a) {
    for (var c = "string" === typeof c ? [c] : c, d, e, f = 0, g = c.length; f < g; f++)e = c[f], b.addEventListener ? b.addEventListener(e, a, !1) : (d = function (c) { "target" in c || (c.target = c.srcElement); c.preventDefault = c.preventDefault || function () { this.returnValue = false }; c.stopPropagation = c.stopPropagation || function () { this.cancelBubble = true }; a.call(b, c) }, b.attachEvent("on" + e, d)); return {
        stop: function () {
            for (var e, h = 0, f = c.length; h < f; h++)e = c[h], b.removeEventListener ? b.removeEventListener(e, a, !1) :
                b.detachEvent("on" + e, d)
        }
    }
};
wysihtml5.dom.parse = function () {
    function b(c, e) { var h = c.childNodes, f = h.length, g; g = a[c.nodeType]; var k = 0; g = g && g(c); if (!g) return null; for (k = 0; k < f; k++)(newChild = b(h[k], e)) && g.appendChild(newChild); return e && 1 >= g.childNodes.length && g.nodeName.toLowerCase() === d && !g.attributes.length ? g.firstChild : g } function c(a, b) {
        var b = b.toLowerCase(), c; if (c = "IMG" == a.nodeName) if (c = "src" == b) { var d; try { d = a.complete && !a.mozMatchesSelector(":-moz-broken") } catch (e) { a.complete && "complete" === a.readyState && (d = !0) } c = !0 === d } return c ?
            a.src : i && "outerHTML" in a ? -1 != a.outerHTML.toLowerCase().indexOf(" " + b + "=") ? a.getAttribute(b) : null : a.getAttribute(b)
    } var a = {
        1: function (a) {
            var b, f, i = g.tags; f = a.nodeName.toLowerCase(); b = a.scopeName; if (a._wysihtml5) return null; a._wysihtml5 = 1; if ("wysihtml5-temp" === a.className) return null; b && "HTML" != b && (f = b + ":" + f); "outerHTML" in a && !wysihtml5.browser.autoClosesUnclosedTags() && ("P" === a.nodeName && "</p>" !== a.outerHTML.slice(-4).toLowerCase()) && (f = "div"); if (f in i) {
                b = i[f]; if (!b || b.remove) return null; b = "string" ===
                    typeof b ? { rename_tag: b } : b
            } else if (a.firstChild) b = { rename_tag: d }; else return null; f = a.ownerDocument.createElement(b.rename_tag || f); var i = {}, r = b.set_class, m = b.add_class, s = b.set_attributes, x = b.check_attributes, o = g.classes, z = 0, w = []; b = []; var y = [], A = [], t; s && (i = wysihtml5.lang.object(s).clone()); if (x) for (t in x) if (s = h[x[t]]) s = s(c(a, t)), "string" === typeof s && (i[t] = s); r && w.push(r); if (m) for (t in m) if (s = k[m[t]]) r = s(c(a, t)), "string" === typeof r && w.push(r); o["_wysihtml5-temp-placeholder"] = 1; (A = a.getAttribute("class")) &&
                (w = w.concat(A.split(e))); for (m = w.length; z < m; z++)a = w[z], o[a] && b.push(a); for (o = b.length; o--;)a = b[o], wysihtml5.lang.array(y).contains(a) || y.unshift(a); y.length && (i["class"] = y.join(" ")); for (t in i) try { f.setAttribute(t, i[t]) } catch (v) { } i.src && ("undefined" !== typeof i.width && f.setAttribute("width", i.width), "undefined" !== typeof i.height && f.setAttribute("height", i.height)); return f
        }, 3: function (a) { return a.ownerDocument.createTextNode(a.data) }
    }, d = "span", e = /\s+/, f = { tags: {}, classes: {} }, g = {}, i = !wysihtml5.browser.supportsGetAttributeCorrectly(),
        h = { url: function () { var a = /^https?:\/\//i; return function (b) { return !b || !b.match(a) ? null : b.replace(a, function (a) { return a.toLowerCase() }) } }(), alt: function () { var a = /[^ a-z0-9_\-]/gi; return function (b) { return !b ? "" : b.replace(a, "") } }(), numbers: function () { var a = /\D/g; return function (b) { return (b = (b || "").replace(a, "")) || null } }() }, k = {
            align_img: function () { var a = { left: "wysiwyg-float-left", right: "wysiwyg-float-right" }; return function (b) { return a[("" + b).toLowerCase()] } }(), align_text: function () {
                var a = {
                    left: "wysiwyg-text-align-left",
                    right: "wysiwyg-text-align-right", center: "wysiwyg-text-align-center", justify: "wysiwyg-text-align-justify"
                }; return function (b) { return a[("" + b).toLowerCase()] }
            }(), clear_br: function () { var a = { left: "wysiwyg-clear-left", right: "wysiwyg-clear-right", both: "wysiwyg-clear-both", all: "wysiwyg-clear-both" }; return function (b) { return a[("" + b).toLowerCase()] } }(), size_font: function () {
                var a = {
                    1: "wysiwyg-font-size-xx-small", 2: "wysiwyg-font-size-small", 3: "wysiwyg-font-size-medium", 4: "wysiwyg-font-size-large", 5: "wysiwyg-font-size-x-large",
                    6: "wysiwyg-font-size-xx-large", 7: "wysiwyg-font-size-xx-large", "-": "wysiwyg-font-size-smaller", "+": "wysiwyg-font-size-larger"
                }; return function (b) { return a[("" + b).charAt(0)] }
            }()
        }; return function (a, c, d, e) {
            wysihtml5.lang.object(g).merge(f).merge(c).get(); for (var d = d || a.ownerDocument || document, c = d.createDocumentFragment(), h = "string" === typeof a, a = h ? wysihtml5.dom.getAsDom(a, d) : a; a.firstChild;)d = a.firstChild, a.removeChild(d), (d = b(d, e)) && c.appendChild(d); a.innerHTML = ""; a.appendChild(c); return h ? wysihtml5.quirks.getCorrectInnerHTML(a) :
                a
        }
}(); wysihtml5.dom.removeEmptyTextNodes = function (b) { for (var c = wysihtml5.lang.array(b.childNodes).get(), a = c.length, d = 0; d < a; d++)b = c[d], b.nodeType === wysihtml5.TEXT_NODE && "" === b.data && b.parentNode.removeChild(b) }; wysihtml5.dom.renameElement = function (b, c) { for (var a = b.ownerDocument.createElement(c), d; d = b.firstChild;)a.appendChild(d); wysihtml5.dom.copyAttributes(["align", "className"]).from(b).to(a); b.parentNode.replaceChild(a, b); return a };
wysihtml5.dom.replaceWithChildNodes = function (b) { if (b.parentNode) if (b.firstChild) { for (var c = b.ownerDocument.createDocumentFragment(); b.firstChild;)c.appendChild(b.firstChild); b.parentNode.replaceChild(c, b) } else b.parentNode.removeChild(b) };
(function (b) {
    function c(a) { var b = a.ownerDocument.createElement("br"); a.appendChild(b) } b.resolveList = function (a) {
        if (!("MENU" !== a.nodeName && "UL" !== a.nodeName && "OL" !== a.nodeName)) {
            var d = a.ownerDocument.createDocumentFragment(), e = a.previousElementSibling || a.previousSibling, f, g, i; for (e && "block" !== b.getStyle("display").from(e) && c(d); i = a.firstChild;) { for (f = i.lastChild; e = i.firstChild;)g = (g = e === f) && "block" !== b.getStyle("display").from(e) && "BR" !== e.nodeName, d.appendChild(e), g && c(d); i.parentNode.removeChild(i) } a.parentNode.replaceChild(d,
                a)
        }
    }
})(wysihtml5.dom);
(function (b) {
    var c = document, a = "parent top opener frameElement frames localStorage globalStorage sessionStorage indexedDB".split(" "), d = "open close openDialog showModalDialog alert confirm prompt openDatabase postMessage XMLHttpRequest XDomainRequest".split(" "), e = ["referrer", "write", "open", "close"]; b.dom.Sandbox = Base.extend({
        constructor: function (a, c) { this.callback = a || b.EMPTY_FUNCTION; this.config = b.lang.object({}).merge(c).get(); this.iframe = this._createIframe() }, insertInto: function (a) {
        "string" === typeof a &&
            (a = c.getElementById(a)); a.appendChild(this.iframe)
        }, getIframe: function () { return this.iframe }, getWindow: function () { this._readyError() }, getDocument: function () { this._readyError() }, destroy: function () { var a = this.getIframe(); a.parentNode.removeChild(a) }, _readyError: function () { throw Error("wysihtml5.Sandbox: Sandbox iframe isn't loaded yet"); }, _createIframe: function () {
            var a = this, d = c.createElement("iframe"); d.className = "wysihtml5-sandbox"; b.dom.setAttributes({
                security: "restricted", allowtransparency: "true",
                frameborder: 0, width: 0, height: 0, marginwidth: 0, marginheight: 0
            }).on(d); b.browser.throwsMixedContentWarningWhenIframeSrcIsEmpty() && (d.src = "javascript:'<html></html>'"); d.onload = function () { d.onreadystatechange = d.onload = null; a._onLoadIframe(d) }; d.onreadystatechange = function () { if (/loaded|complete/.test(d.readyState)) { d.onreadystatechange = d.onload = null; a._onLoadIframe(d) } }; return d
        }, _onLoadIframe: function (f) {
            if (b.dom.contains(c.documentElement, f)) {
                var g = this, i = f.contentWindow, h = f.contentWindow.document, k =
                    this._getHtml({ charset: c.characterSet || c.charset || "utf-8", stylesheets: this.config.stylesheets }); h.open("text/html", "replace"); h.write(k); h.close(); this.getWindow = function () { return f.contentWindow }; this.getDocument = function () { return f.contentWindow.document }; i.onerror = function (a, b, c) { throw Error("wysihtml5.Sandbox: " + a, b, c); }; if (!b.browser.supportsSandboxedIframes()) {
                        var j, k = 0; for (j = a.length; k < j; k++)this._unset(i, a[k]); k = 0; for (j = d.length; k < j; k++)this._unset(i, d[k], b.EMPTY_FUNCTION); k = 0; for (j = e.length; k <
                            j; k++)this._unset(h, e[k]); this._unset(h, "cookie", "", !0)
                    } this.loaded = !0; setTimeout(function () { g.callback(g) }, 0)
            }
        }, _getHtml: function (a) { var c = a.stylesheets, d = "", e = 0, k; if (c = "string" === typeof c ? [c] : c) for (k = c.length; e < k; e++)d += '<link rel="stylesheet" href="' + c[e] + '">'; a.stylesheets = d; return b.lang.string('<!DOCTYPE html><html><head><meta charset="#{charset}">#{stylesheets}</head><body></body></html>').interpolate(a) }, _unset: function (a, c, d, e) {
            try { a[c] = d } catch (k) { } try { a.__defineGetter__(c, function () { return d }) } catch (j) { } if (e) try {
                a.__defineSetter__(c,
                    function () { })
            } catch (n) { } if (!b.browser.crashesWhenDefineProperty(c)) try { var p = { get: function () { return d } }; e && (p.set = function () { }); Object.defineProperty(a, c, p) } catch (q) { }
        }
    })
})(wysihtml5); (function () { var b = { className: "class" }; wysihtml5.dom.setAttributes = function (c) { return { on: function (a) { for (var d in c) a.setAttribute(b[d] || d, c[d]) } } } })();
wysihtml5.dom.setStyles = function (b) { return { on: function (c) { c = c.style; if ("string" === typeof b) c.cssText += ";" + b; else for (var a in b) "float" === a ? (c.cssFloat = b[a], c.styleFloat = b[a]) : c[a] = b[a] } } };
(function (b) { b.simulatePlaceholder = function (c, a, d) { var e = function () { a.hasPlaceholderSet() && a.clear(); b.removeClass(a.element, "placeholder") }, f = function () { a.isEmpty() && (a.setValue(d), b.addClass(a.element, "placeholder")) }; c.observe("set_placeholder", f).observe("unset_placeholder", e).observe("focus:composer", e).observe("paste:composer", e).observe("blur:composer", f); f() } })(wysihtml5.dom);
(function (b) { var c = document.documentElement; "textContent" in c ? (b.setTextContent = function (a, b) { a.textContent = b }, b.getTextContent = function (a) { return a.textContent }) : "innerText" in c ? (b.setTextContent = function (a, b) { a.innerText = b }, b.getTextContent = function (a) { return a.innerText }) : (b.setTextContent = function (a, b) { a.nodeValue = b }, b.getTextContent = function (a) { return a.nodeValue }) })(wysihtml5.dom);
wysihtml5.quirks.cleanPastedHTML = function () { var b = { "a u": wysihtml5.dom.replaceWithChildNodes }; return function (c, a, d) { var a = a || b, d = d || c.ownerDocument || document, e = "string" === typeof c, f, g, i, h = 0, c = e ? wysihtml5.dom.getAsDom(c, d) : c; for (i in a) { f = c.querySelectorAll(i); d = a[i]; for (g = f.length; h < g; h++)d(f[h]) } return e ? c.innerHTML : c } }();
(function (b) {
    var c = b.dom; b.quirks.ensureProperClearing = function () { var a = function () { var a = this; setTimeout(function () { var b = a.innerHTML.toLowerCase(); if ("<p>&nbsp;</p>" == b || "<p>&nbsp;</p><p>&nbsp;</p>" == b) a.innerHTML = "" }, 0) }; return function (b) { c.observe(b.element, ["cut", "keydown"], a) } }(); b.quirks.ensureProperClearingOfLists = function () {
        var a = ["OL", "UL", "MENU"]; return function (d) {
            c.observe(d.element, "keydown", function (e) {
                if (e.keyCode === b.BACKSPACE_KEY) {
                    var f = d.selection.getSelectedNode(), e = d.element;
                    e.firstChild && b.lang.array(a).contains(e.firstChild.nodeName) && (f = c.getParentElement(f, { nodeName: a })) && f == e.firstChild && 1 >= f.childNodes.length && (f.firstChild ? "" === f.firstChild.innerHTML : 1) && f.parentNode.removeChild(f)
                }
            })
        }
    }()
})(wysihtml5);
(function (b) { b.quirks.getCorrectInnerHTML = function (c) { var a = c.innerHTML; if (-1 === a.indexOf("%7E")) return a; var c = c.querySelectorAll("[href*='~'], [src*='~']"), d, e, f, g; g = 0; for (f = c.length; g < f; g++)d = c[g].href || c[g].src, e = b.lang.string(d).replace("~").by("%7E"), a = b.lang.string(a).replace(e).by(d); return a } })(wysihtml5);
(function (b) {
    var c = b.dom, a = "LI P H1 H2 H3 H4 H5 H6".split(" "), d = ["UL", "OL", "MENU"]; b.quirks.insertLineBreakOnReturn = function (e) {
        function f(a) { if (a = c.getParentElement(a, { nodeName: ["P", "DIV"] }, 2)) { var d = document.createTextNode(b.INVISIBLE_SPACE); c.insert(d).before(a); c.replaceWithChildNodes(a); e.selection.selectNode(d) } } c.observe(e.element.ownerDocument, "keydown", function (g) {
            var i = g.keyCode; if (!(g.shiftKey || i !== b.ENTER_KEY && i !== b.BACKSPACE_KEY)) {
                var h = e.selection.getSelectedNode(); (h = c.getParentElement(h,
                    { nodeName: a }, 4)) ? "LI" === h.nodeName && (i === b.ENTER_KEY || i === b.BACKSPACE_KEY) ? setTimeout(function () { var a = e.selection.getSelectedNode(), b; a && ((b = c.getParentElement(a, { nodeName: d }, 2)) || f(a)) }, 0) : h.nodeName.match(/H[1-6]/) && i === b.ENTER_KEY && setTimeout(function () { f(e.selection.getSelectedNode()) }, 0) : i === b.ENTER_KEY && !b.browser.insertsLineBreaksOnReturn() && (e.commands.exec("insertLineBreak"), g.preventDefault())
            }
        })
    }
})(wysihtml5);
(function (b) { b.quirks.redraw = function (c) { b.dom.addClass(c, "wysihtml5-quirks-redraw"); b.dom.removeClass(c, "wysihtml5-quirks-redraw"); try { var a = c.ownerDocument; a.execCommand("italic", !1, null); a.execCommand("italic", !1, null) } catch (d) { } } })(wysihtml5);
(function (b) {
    var c = b.dom; b.Selection = Base.extend({
        constructor: function (a) { window.rangy.init(); this.editor = a; this.composer = a.composer; this.doc = this.composer.doc }, getBookmark: function () { var a = this.getRange(); return a && a.cloneRange() }, setBookmark: function (a) { a && this.setSelection(a) }, setBefore: function (a) { var b = rangy.createRange(this.doc); b.setStartBefore(a); b.setEndBefore(a); return this.setSelection(b) }, setAfter: function (a) { var b = rangy.createRange(this.doc); b.setStartAfter(a); b.setEndAfter(a); return this.setSelection(b) },
        selectNode: function (a) { var d = rangy.createRange(this.doc), e = a.nodeType === b.ELEMENT_NODE, f = "canHaveHTML" in a ? a.canHaveHTML : "IMG" !== a.nodeName, g = e ? a.innerHTML : a.data, g = "" === g || g === b.INVISIBLE_SPACE, i = c.getStyle("display").from(a), i = "block" === i || "list-item" === i; if (g && e && f) try { a.innerHTML = b.INVISIBLE_SPACE } catch (h) { } f ? d.selectNodeContents(a) : d.selectNode(a); f && g && e ? d.collapse(i) : f && g && (d.setStartAfter(a), d.setEndAfter(a)); this.setSelection(d) }, getSelectedNode: function (a) {
            if (a && this.doc.selection && "Control" ===
                this.doc.selection.type && (a = this.doc.selection.createRange()) && a.length) return a.item(0); a = this.getSelection(this.doc); return a.focusNode === a.anchorNode ? a.focusNode : (a = this.getRange(this.doc)) ? a.commonAncestorContainer : this.doc.body
        }, executeAndRestore: function (a, c) {
            var e = this.doc.body, f = c && e.scrollTop, g = c && e.scrollLeft, i = '<span class="_wysihtml5-temp-placeholder">' + b.INVISIBLE_SPACE + "</span>", h = this.getRange(this.doc); if (h) {
                i = h.createContextualFragment(i); h.insertNode(i); try { a(h.startContainer, h.endContainer) } catch (k) {
                    setTimeout(function () {
                        throw k;
                    }, 0)
                } (caretPlaceholder = this.doc.querySelector("._wysihtml5-temp-placeholder")) ? (h = rangy.createRange(this.doc), h.selectNode(caretPlaceholder), h.deleteContents(), this.setSelection(h)) : e.focus(); c && (e.scrollTop = f, e.scrollLeft = g); try { caretPlaceholder.parentNode.removeChild(caretPlaceholder) } catch (j) { }
            } else a(e, e)
        }, executeAndRestoreSimple: function (a) {
            var b, c, f = this.getRange(), g = this.doc.body, i; if (f) {
                b = f.getNodes([3]); g = b[0] || f.startContainer; i = b[b.length - 1] || f.endContainer; b = g === f.startContainer ? f.startOffset :
                    0; c = i === f.endContainer ? f.endOffset : i.length; try { a(f.startContainer, f.endContainer) } catch (h) { setTimeout(function () { throw h; }, 0) } a = rangy.createRange(this.doc); try { a.setStart(g, b) } catch (k) { } try { a.setEnd(i, c) } catch (j) { } try { this.setSelection(a) } catch (n) { }
            } else a(g, g)
        }, insertHTML: function (a) { var a = rangy.createRange(this.doc).createContextualFragment(a), b = a.lastChild; this.insertNode(a); b && this.setAfter(b) }, insertNode: function (a) { var b = this.getRange(); b && b.insertNode(a) }, surround: function (a) {
            var b = this.getRange();
            if (b) try { b.surroundContents(a), this.selectNode(a) } catch (c) { a.appendChild(b.extractContents()), b.insertNode(a) }
        }, scrollIntoView: function () {
            var a = this.doc, c = a.documentElement.scrollHeight > a.documentElement.offsetHeight, e; if (!(e = a._wysihtml5ScrollIntoViewElement)) e = a.createElement("span"), e.innerHTML = b.INVISIBLE_SPACE; e = a._wysihtml5ScrollIntoViewElement = e; if (c) {
                this.insertNode(e); var c = e, f = 0; if (c.parentNode) { do f += c.offsetTop || 0, c = c.offsetParent; while (c) } c = f; e.parentNode.removeChild(e); c > a.body.scrollTop &&
                    (a.body.scrollTop = c)
            }
        }, selectLine: function () { b.browser.supportsSelectionModify() ? this._selectLine_W3C() : this.doc.selection && this._selectLine_MSIE() }, _selectLine_W3C: function () { var a = this.doc.defaultView.getSelection(); a.modify("extend", "left", "lineboundary"); a.modify("extend", "right", "lineboundary") }, _selectLine_MSIE: function () {
            var a = this.doc.selection.createRange(), b = a.boundingTop, c = this.doc.body.scrollWidth, f; if (a.moveToPoint) {
            0 === b && (f = this.doc.createElement("span"), this.insertNode(f), b = f.offsetTop,
                f.parentNode.removeChild(f)); b += 1; for (f = -10; f < c; f += 2)try { a.moveToPoint(f, b); break } catch (g) { } for (f = this.doc.selection.createRange(); 0 <= c; c--)try { f.moveToPoint(c, b); break } catch (i) { } a.setEndPoint("EndToEnd", f); a.select()
            }
        }, getText: function () { var a = this.getSelection(); return a ? a.toString() : "" }, getNodes: function (a, b) { var c = this.getRange(); return c ? c.getNodes([a], b) : [] }, getRange: function () { var a = this.getSelection(); return a && a.rangeCount && a.getRangeAt(0) }, getSelection: function () {
            return rangy.getSelection(this.doc.defaultView ||
                this.doc.parentWindow)
        }, setSelection: function (a) { return rangy.getSelection(this.doc.defaultView || this.doc.parentWindow).setSingleRange(a) }
    })
})(wysihtml5);
(function (b, c) {
    function a(a, b) { return c.dom.isCharacterDataNode(a) ? 0 == b ? !!a.previousSibling : b == a.length ? !!a.nextSibling : !0 : 0 < b && b < a.childNodes.length } function d(a, b, e) { var f; c.dom.isCharacterDataNode(b) && (0 == e ? (e = c.dom.getNodeIndex(b), b = b.parentNode) : e == b.length ? (e = c.dom.getNodeIndex(b) + 1, b = b.parentNode) : f = c.dom.splitDataNode(b, e)); if (!f) { f = b.cloneNode(!1); f.id && f.removeAttribute("id"); for (var g; g = b.childNodes[e];)f.appendChild(g); c.dom.insertAfter(f, b) } return b == a ? f : d(a, f.parentNode, c.dom.getNodeIndex(f)) }
    function e(a) { this.firstTextNode = (this.isElementMerge = a.nodeType == b.ELEMENT_NODE) ? a.lastChild : a; this.textNodes = [this.firstTextNode] } function f(a, b, c, d) { this.tagNames = a || [g]; this.cssClass = b || ""; this.similarClassRegExp = c; this.normalize = d; this.applyToAnyTagName = !1 } var g = "span", i = /\s+/g; e.prototype = {
        doMerge: function () {
            for (var a = [], b, c, d = 0, e = this.textNodes.length; d < e; ++d)b = this.textNodes[d], c = b.parentNode, a[d] = b.data, d && (c.removeChild(b), c.hasChildNodes() || c.parentNode.removeChild(c)); return this.firstTextNode.data =
                a = a.join("")
        }, getLength: function () { for (var a = this.textNodes.length, b = 0; a--;)b += this.textNodes[a].length; return b }, toString: function () { for (var a = [], b = 0, c = this.textNodes.length; b < c; ++b)a[b] = "'" + this.textNodes[b].data + "'"; return "[Merge(" + a.join(",") + ")]" }
    }; f.prototype = {
        getAncestorWithClass: function (a) {
            for (var d; a;) {
                if (this.cssClass) if (d = this.cssClass, a.className) { var e = a.className.match(this.similarClassRegExp) || []; d = e[e.length - 1] === d } else d = !1; else d = !0; if (a.nodeType == b.ELEMENT_NODE && c.dom.arrayContains(this.tagNames,
                    a.tagName.toLowerCase()) && d) return a; a = a.parentNode
            } return !1
        }, postApply: function (a, b) {
            for (var c = a[0], d = a[a.length - 1], f = [], g, i = c, m = d, s = 0, x = d.length, o, z, w = 0, y = a.length; w < y; ++w)if (o = a[w], z = this.getAdjacentMergeableTextNode(o.parentNode, !1)) { if (g || (g = new e(z), f.push(g)), g.textNodes.push(o), o === c && (i = g.firstTextNode, s = i.length), o === d) m = g.firstTextNode, x = g.getLength() } else g = null; if (c = this.getAdjacentMergeableTextNode(d.parentNode, !0)) g || (g = new e(d), f.push(g)), g.textNodes.push(c); if (f.length) {
                w = 0; for (y =
                    f.length; w < y; ++w)f[w].doMerge(); b.setStart(i, s); b.setEnd(m, x)
            }
        }, getAdjacentMergeableTextNode: function (a, c) { var d = a.nodeType == b.TEXT_NODE, e = d ? a.parentNode : a, f = c ? "nextSibling" : "previousSibling"; if (d) { if ((d = a[f]) && d.nodeType == b.TEXT_NODE) return d } else if ((d = e[f]) && this.areElementsMergeable(a, d)) return d[c ? "firstChild" : "lastChild"]; return null }, areElementsMergeable: function (a, b) {
            var d; if (d = c.dom.arrayContains(this.tagNames, (a.tagName || "").toLowerCase())) if (d = c.dom.arrayContains(this.tagNames, (b.tagName ||
                "").toLowerCase())) if (d = a.className.replace(i, " ") == b.className.replace(i, " ")) a: if (a.attributes.length != b.attributes.length) d = !1; else { d = 0; for (var e = a.attributes.length, f, g; d < e; ++d)if (f = a.attributes[d], g = f.name, "class" != g && (g = b.attributes.getNamedItem(g), f.specified != g.specified || f.specified && f.nodeValue !== g.nodeValue)) { d = !1; break a } d = !0 } return d
        }, createContainer: function (a) { a = a.createElement(this.tagNames[0]); this.cssClass && (a.className = this.cssClass); return a }, applyToTextNode: function (a) {
            var b =
                a.parentNode; 1 == b.childNodes.length && c.dom.arrayContains(this.tagNames, b.tagName.toLowerCase()) ? this.cssClass && (a = this.cssClass, b.className ? (b.className && (b.className = b.className.replace(this.similarClassRegExp, "")), b.className += " " + a) : b.className = a) : (b = this.createContainer(c.dom.getDocument(a)), a.parentNode.insertBefore(b, a), b.appendChild(a))
        }, isRemovable: function (a) { return c.dom.arrayContains(this.tagNames, a.tagName.toLowerCase()) && b.lang.string(a.className).trim() == this.cssClass }, undoToTextNode: function (b,
            c, e) {
                c.containsNode(e) || (b = c.cloneRange(), b.selectNode(e), b.isPointInRange(c.endContainer, c.endOffset) && a(c.endContainer, c.endOffset) && (d(e, c.endContainer, c.endOffset), c.setEndAfter(e)), b.isPointInRange(c.startContainer, c.startOffset) && a(c.startContainer, c.startOffset) && (e = d(e, c.startContainer, c.startOffset))); this.similarClassRegExp && e.className && (e.className = e.className.replace(this.similarClassRegExp, "")); if (this.isRemovable(e)) {
                    c = e; for (e = c.parentNode; c.firstChild;)e.insertBefore(c.firstChild,
                        c); e.removeChild(c)
                }
        }, applyToRange: function (a) { var c = a.getNodes([b.TEXT_NODE]); if (!c.length) try { var d = this.createContainer(a.endContainer.ownerDocument); a.surroundContents(d); this.selectNode(a, d); return } catch (e) { } a.splitBoundaries(); c = a.getNodes([b.TEXT_NODE]); if (c.length) { for (var f = 0, g = c.length; f < g; ++f)d = c[f], this.getAncestorWithClass(d) || this.applyToTextNode(d); a.setStart(c[0], 0); d = c[c.length - 1]; a.setEnd(d, d.length); this.normalize && this.postApply(c, a) } }, undoToRange: function (a) {
            var c = a.getNodes([b.TEXT_NODE]),
            d, e; c.length ? (a.splitBoundaries(), c = a.getNodes([b.TEXT_NODE])) : (c = a.endContainer.ownerDocument.createTextNode(b.INVISIBLE_SPACE), a.insertNode(c), a.selectNode(c), c = [c]); for (var f = 0, g = c.length; f < g; ++f)d = c[f], (e = this.getAncestorWithClass(d)) && this.undoToTextNode(d, a, e); 1 == g ? this.selectNode(a, c[0]) : (a.setStart(c[0], 0), d = c[c.length - 1], a.setEnd(d, d.length), this.normalize && this.postApply(c, a))
        }, selectNode: function (a, c) {
            var d = c.nodeType === b.ELEMENT_NODE, e = "canHaveHTML" in c ? c.canHaveHTML : !0, f = d ? c.innerHTML :
                c.data; if ((f = "" === f || f === b.INVISIBLE_SPACE) && d && e) try { c.innerHTML = b.INVISIBLE_SPACE } catch (g) { } a.selectNodeContents(c); f && d ? a.collapse(!1) : f && (a.setStartAfter(c), a.setEndAfter(c))
        }, getTextSelectedByRange: function (a, b) { var c = b.cloneRange(); c.selectNodeContents(a); var d = c.intersection(b), d = d ? d.toString() : ""; c.detach(); return d }, isAppliedToRange: function (a) {
            var c = [], d, e = a.getNodes([b.TEXT_NODE]); if (!e.length) return (d = this.getAncestorWithClass(a.startContainer)) ? [d] : !1; for (var f = 0, g = e.length, i; f < g; ++f) {
                i =
                this.getTextSelectedByRange(e[f], a); d = this.getAncestorWithClass(e[f]); if ("" != i && !d) return !1; c.push(d)
            } return c
        }, toggleRange: function (a) { this.isAppliedToRange(a) ? this.undoToRange(a) : this.applyToRange(a) }
    }; b.selection.HTMLApplier = f
})(wysihtml5, rangy);
wysihtml5.Commands = Base.extend({
    constructor: function (b) { this.editor = b; this.composer = b.composer; this.doc = this.composer.doc }, support: function (b) { return wysihtml5.browser.supportsCommand(this.doc, b) }, exec: function (b, c) { var a = wysihtml5.commands[b], d = wysihtml5.lang.array(arguments).get(), e = a && a.exec, f = null; this.editor.fire("beforecommand:composer"); if (e) d.unshift(this.composer), f = e.apply(a, d); else try { f = this.doc.execCommand(b, !1, c) } catch (g) { } this.editor.fire("aftercommand:composer"); return f }, state: function (b,
        c) { var a = wysihtml5.commands[b], d = wysihtml5.lang.array(arguments).get(), e = a && a.state; if (e) return d.unshift(this.composer), e.apply(a, d); try { return this.doc.queryCommandState(b) } catch (f) { return !1 } }, value: function (b) { var c = wysihtml5.commands[b], a = c && c.value; if (a) return a.call(c, this.composer, b); try { return this.doc.queryCommandValue(b) } catch (d) { return null } }
});
(function (b) { b.commands.bold = { exec: function (c, a) { return b.commands.formatInline.exec(c, a, "b") }, state: function (c, a) { return b.commands.formatInline.state(c, a, "b") }, value: function () { } } })(wysihtml5);
(function (b) {
    function c(c, g) { var i = c.doc, h = "_wysihtml5-temp-" + +new Date, k = 0, j, n, p; b.commands.formatInline.exec(c, a, d, h, /non-matching-class/g); j = i.querySelectorAll(d + "." + h); for (h = j.length; k < h; k++)for (p in n = j[k], n.removeAttribute("class"), g) n.setAttribute(p, g[p]); k = n; 1 === h && (p = e.getTextContent(n), h = !!n.querySelector("*"), p = "" === p || p === b.INVISIBLE_SPACE, !h && p && (e.setTextContent(n, g.text || n.href), i = i.createTextNode(" "), c.selection.setAfter(n), c.selection.insertNode(i), k = i)); c.selection.setAfter(k) }
    var a, d = "A", e = b.dom; b.commands.createLink = { exec: function (a, b, d) { var h = this.state(a, b); h ? a.selection.executeAndRestore(function () { for (var a = h.length, b = 0, c, d, f; b < a; b++)c = h[b], d = e.getParentElement(c, { nodeName: "code" }), f = e.getTextContent(c), f.match(e.autoLink.URL_REG_EXP) && !d ? e.renameElement(c, "code") : e.replaceWithChildNodes(c) }) : (d = "object" === typeof d ? d : { href: d }, c(a, d)) }, state: function (a, c) { return b.commands.formatInline.state(a, c, "A") }, value: function () { return a } }
})(wysihtml5);
(function (b) { var c = /wysiwyg-font-size-[a-z\-]+/g; b.commands.fontSize = { exec: function (a, d, e) { return b.commands.formatInline.exec(a, d, "span", "wysiwyg-font-size-" + e, c) }, state: function (a, d, e) { return b.commands.formatInline.state(a, d, "span", "wysiwyg-font-size-" + e, c) }, value: function () { } } })(wysihtml5);
(function (b) { var c = /wysiwyg-color-[a-z]+/g; b.commands.foreColor = { exec: function (a, d, e) { return b.commands.formatInline.exec(a, d, "span", "wysiwyg-color-" + e, c) }, state: function (a, d, e) { return b.commands.formatInline.state(a, d, "span", "wysiwyg-color-" + e, c) }, value: function () { } } })(wysihtml5);
(function (b) {
    function c(a) { for (a = a.previousSibling; a && a.nodeType === b.TEXT_NODE && !b.lang.string(a.data).trim();)a = a.previousSibling; return a } function a(a) { for (a = a.nextSibling; a && a.nodeType === b.TEXT_NODE && !b.lang.string(a.data).trim();)a = a.nextSibling; return a } function d(a) { return "BR" === a.nodeName || "block" === g.getStyle("display").from(a) ? !0 : !1 } function e(a, c, d, e) {
        if (e) var f = g.observe(a, "DOMNodeInserted", function (a) {
            var a = a.target, c; a.nodeType === b.ELEMENT_NODE && (c = g.getStyle("display").from(a), "inline" !==
                c.substr(0, 6) && (a.className += " " + e))
        }); a.execCommand(c, !1, d); f && f.stop()
    } function f(b, d) { b.selection.selectLine(); b.selection.surround(d); var e = a(d), f = c(d); e && "BR" === e.nodeName && e.parentNode.removeChild(e); f && "BR" === f.nodeName && f.parentNode.removeChild(f); (e = d.lastChild) && "BR" === e.nodeName && e.parentNode.removeChild(e); b.selection.selectNode(d) } var g = b.dom, i = "H1 H2 H3 H4 H5 H6 P BLOCKQUOTE DIV".split(" "); b.commands.formatBlock = {
        exec: function (h, k, j, n, p) {
            var q = h.doc, r = this.state(h, k, j, n, p), m, j = "string" ===
                typeof j ? j.toUpperCase() : j; if (r) h.selection.executeAndRestoreSimple(function () { p && (r.className = r.className.replace(p, "")); var e = !!b.lang.string(r.className).trim(); if (!e && r.nodeName === (j || "DIV")) { var e = r, f = e.ownerDocument, h = a(e), i = c(e); h && !d(h) && e.parentNode.insertBefore(f.createElement("br"), h); i && !d(i) && e.parentNode.insertBefore(f.createElement("br"), e); g.replaceWithChildNodes(r) } else e && g.renameElement(r, "DIV") }); else {
                    if (null === j || b.lang.array(i).contains(j)) if (m = h.selection.getSelectedNode(),
                        r = g.getParentElement(m, { nodeName: i })) { h.selection.executeAndRestoreSimple(function () { j && (r = g.renameElement(r, j)); if (n) { var a = r; a.className ? (a.className = a.className.replace(p, ""), a.className += " " + n) : a.className = n } }); return } h.commands.support(k) ? e(q, k, j || "DIV", n) : (r = q.createElement(j || "DIV"), n && (r.className = n), f(h, r))
                }
        }, state: function (a, b, c, d, e) { c = "string" === typeof c ? c.toUpperCase() : c; a = a.selection.getSelectedNode(); return g.getParentElement(a, { nodeName: c, className: d, classRegExp: e }) }, value: function () { }
    }
})(wysihtml5);
(function (b) {
    function c(c, f, g) { var i = c + ":" + f; if (!d[i]) { var h = d, k = b.selection.HTMLApplier, j = a[c], c = j ? [c.toLowerCase(), j.toLowerCase()] : [c.toLowerCase()]; h[i] = new k(c, f, g, !0) } return d[i] } var a = { strong: "b", em: "i", b: "strong", i: "em" }, d = {}; b.commands.formatInline = {
        exec: function (a, b, d, i, h) { b = a.selection.getRange(); if (!b) return !1; c(d, i, h).toggleRange(b); a.selection.setSelection(b) }, state: function (d, f, g, i, h) {
            var f = d.doc, k = a[g] || g; if (!b.dom.hasElementWithTagName(f, g) && !b.dom.hasElementWithTagName(f, k) || i &&
                !b.dom.hasElementWithClassName(f, i)) return !1; d = d.selection.getRange(); return !d ? !1 : c(g, i, h).isAppliedToRange(d)
        }, value: function () { }
    }
})(wysihtml5); (function (b) { b.commands.insertHTML = { exec: function (b, a, d) { b.commands.support(a) ? b.doc.execCommand(a, !1, d) : b.selection.insertHTML(d) }, state: function () { return !1 }, value: function () { } } })(wysihtml5);
(function (b) {
    b.commands.insertImage = {
        exec: function (c, a, d) {
            var d = "object" === typeof d ? d : { src: d }, e = c.doc, a = this.state(c), f; if (a) c.selection.setBefore(a), d = a.parentNode, d.removeChild(a), b.dom.removeEmptyTextNodes(d), "A" === d.nodeName && !d.firstChild && (c.selection.setAfter(d), d.parentNode.removeChild(d)), b.quirks.redraw(c.element); else {
                a = e.createElement("IMG"); for (f in d) a[f] = d[f]; c.selection.insertNode(a); b.browser.hasProblemsSettingCaretAfterImg() ? (d = e.createTextNode(b.INVISIBLE_SPACE), c.selection.insertNode(d),
                    c.selection.setAfter(d)) : c.selection.setAfter(a)
            }
        }, state: function (c) { var a; if (!b.dom.hasElementWithTagName(c.doc, "IMG")) return !1; a = c.selection.getSelectedNode(); if (!a) return !1; if ("IMG" === a.nodeName) return a; if (a.nodeType !== b.ELEMENT_NODE) return !1; a = c.selection.getText(); if (a = b.lang.string(a).trim()) return !1; c = c.selection.getNodes(b.ELEMENT_NODE, function (a) { return "IMG" === a.nodeName }); return 1 !== c.length ? !1 : c[0] }, value: function (b) { return (b = this.state(b)) && b.src }
    }
})(wysihtml5);
(function (b) { var c = "<br>" + (b.browser.needsSpaceAfterLineBreak() ? " " : ""); b.commands.insertLineBreak = { exec: function (a, d) { a.commands.support(d) ? (a.doc.execCommand(d, !1, null), b.browser.autoScrollsToCaret() || a.selection.scrollIntoView()) : a.commands.exec("insertHTML", c) }, state: function () { return !1 }, value: function () { } } })(wysihtml5);
(function (b) {
    b.commands.insertOrderedList = {
        exec: function (c, a) {
            var d = c.doc, e = c.selection.getSelectedNode(), f = b.dom.getParentElement(e, { nodeName: "OL" }), g = b.dom.getParentElement(e, { nodeName: "UL" }), e = "_wysihtml5-temp-" + (new Date).getTime(), i; c.commands.support(a) ? d.execCommand(a, !1, null) : f ? c.selection.executeAndRestoreSimple(function () { b.dom.resolveList(f) }) : g ? c.selection.executeAndRestoreSimple(function () { b.dom.renameElement(g, "ol") }) : (c.commands.exec("formatBlock", "div", e), i = d.querySelector("." + e),
                d = "" === i.innerHTML || i.innerHTML === b.INVISIBLE_SPACE, c.selection.executeAndRestoreSimple(function () { f = b.dom.convertToList(i, "ol") }), d && c.selection.selectNode(f.querySelector("li")))
        }, state: function (c) { c = c.selection.getSelectedNode(); return b.dom.getParentElement(c, { nodeName: "OL" }) }, value: function () { }
    }
})(wysihtml5);
(function (b) {
    b.commands.insertUnorderedList = {
        exec: function (c, a) {
            var d = c.doc, e = c.selection.getSelectedNode(), f = b.dom.getParentElement(e, { nodeName: "UL" }), g = b.dom.getParentElement(e, { nodeName: "OL" }), e = "_wysihtml5-temp-" + (new Date).getTime(), i; c.commands.support(a) ? d.execCommand(a, !1, null) : f ? c.selection.executeAndRestoreSimple(function () { b.dom.resolveList(f) }) : g ? c.selection.executeAndRestoreSimple(function () { b.dom.renameElement(g, "ul") }) : (c.commands.exec("formatBlock", "div", e), i = d.querySelector("." + e),
                d = "" === i.innerHTML || i.innerHTML === b.INVISIBLE_SPACE, c.selection.executeAndRestoreSimple(function () { f = b.dom.convertToList(i, "ul") }), d && c.selection.selectNode(f.querySelector("li")))
        }, state: function (c) { c = c.selection.getSelectedNode(); return b.dom.getParentElement(c, { nodeName: "UL" }) }, value: function () { }
    }
})(wysihtml5); (function (b) { b.commands.italic = { exec: function (c, a) { return b.commands.formatInline.exec(c, a, "i") }, state: function (c, a) { return b.commands.formatInline.state(c, a, "i") }, value: function () { } } })(wysihtml5);
(function (b) { var c = /wysiwyg-text-align-[a-z]+/g; b.commands.justifyCenter = { exec: function (a) { return b.commands.formatBlock.exec(a, "formatBlock", null, "wysiwyg-text-align-center", c) }, state: function (a) { return b.commands.formatBlock.state(a, "formatBlock", null, "wysiwyg-text-align-center", c) }, value: function () { } } })(wysihtml5);
(function (b) { var c = /wysiwyg-text-align-[a-z]+/g; b.commands.justifyLeft = { exec: function (a) { return b.commands.formatBlock.exec(a, "formatBlock", null, "wysiwyg-text-align-left", c) }, state: function (a) { return b.commands.formatBlock.state(a, "formatBlock", null, "wysiwyg-text-align-left", c) }, value: function () { } } })(wysihtml5);
(function (b) { var c = /wysiwyg-text-align-[a-z]+/g; b.commands.justifyRight = { exec: function (a) { return b.commands.formatBlock.exec(a, "formatBlock", null, "wysiwyg-text-align-right", c) }, state: function (a) { return b.commands.formatBlock.state(a, "formatBlock", null, "wysiwyg-text-align-right", c) }, value: function () { } } })(wysihtml5); (function (b) { b.commands.underline = { exec: function (c, a) { return b.commands.formatInline.exec(c, a, "u") }, state: function (c, a) { return b.commands.formatInline.state(c, a, "u") }, value: function () { } } })(wysihtml5);
(function (b) {
    var c = '<span id="_wysihtml5-undo" class="_wysihtml5-temp">' + b.INVISIBLE_SPACE + "</span>", a = '<span id="_wysihtml5-redo" class="_wysihtml5-temp">' + b.INVISIBLE_SPACE + "</span>", d = b.dom; b.UndoManager = b.lang.Dispatcher.extend({
        constructor: function (a) { this.editor = a; this.composer = a.composer; this.element = this.composer.element; this.history = [this.composer.getValue()]; this.position = 1; this.composer.commands.support("insertHTML") && this._observe() }, _observe: function () {
            var e = this, f = this.composer.sandbox.getDocument(),
            g; d.observe(this.element, "keydown", function (a) { if (!(a.altKey || !a.ctrlKey && !a.metaKey)) { var b = a.keyCode, c = 90 === b && a.shiftKey || 89 === b; 90 === b && !a.shiftKey ? (e.undo(), a.preventDefault()) : c && (e.redo(), a.preventDefault()) } }); d.observe(this.element, "keydown", function (a) { a = a.keyCode; a !== g && (g = a, (8 === a || 46 === a) && e.transact()) }); if (b.browser.hasUndoInContextMenu()) {
                var i, h, k = function () { for (var a; a = f.querySelector("._wysihtml5-temp");)a.parentNode.removeChild(a); clearInterval(i) }; d.observe(this.element, "contextmenu",
                    function () { k(); e.composer.selection.executeAndRestoreSimple(function () { e.element.lastChild && e.composer.selection.setAfter(e.element.lastChild); f.execCommand("insertHTML", !1, c); f.execCommand("insertHTML", !1, a); f.execCommand("undo", !1, null) }); i = setInterval(function () { f.getElementById("_wysihtml5-redo") ? (k(), e.redo()) : f.getElementById("_wysihtml5-undo") || (k(), e.undo()) }, 400); h || (h = !0, d.observe(document, "mousedown", k), d.observe(f, ["mousedown", "paste", "cut", "copy"], k)) })
            } this.editor.observe("newword:composer",
                function () { e.transact() }).observe("beforecommand:composer", function () { e.transact() })
        }, transact: function () { var a = this.history[this.position - 1], b = this.composer.getValue(); if (b != a) { if (40 < (this.history.length = this.position)) this.history.shift(), this.position--; this.position++; this.history.push(b) } }, undo: function () { this.transact(); 1 >= this.position || (this.set(this.history[--this.position - 1]), this.editor.fire("undo:composer")) }, redo: function () {
        this.position >= this.history.length || (this.set(this.history[++this.position -
            1]), this.editor.fire("redo:composer"))
        }, set: function (a) { this.composer.setValue(a); this.editor.focus(!0) }
    })
})(wysihtml5);
wysihtml5.views.View = Base.extend({
    constructor: function (b, c, a) { this.parent = b; this.element = c; this.config = a; this._observeViewChange() }, _observeViewChange: function () { var b = this; this.parent.observe("beforeload", function () { b.parent.observe("change_view", function (c) { c === b.name ? (b.parent.currentView = b, b.show(), setTimeout(function () { b.focus() }, 0)) : b.hide() }) }) }, focus: function () { if (this.element.ownerDocument.querySelector(":focus") !== this.element) try { this.element.focus() } catch (b) { } }, hide: function () {
        this.element.style.display =
        "none"
    }, show: function () { this.element.style.display = "" }, disable: function () { this.element.setAttribute("disabled", "disabled") }, enable: function () { this.element.removeAttribute("disabled") }
});
(function (b) {
    var c = b.dom, a = b.browser; b.views.Composer = b.views.View.extend({
        name: "composer", CARET_HACK: "<br>", constructor: function (a, b, c) { this.base(a, b, c); this.textarea = this.parent.textarea; this._initSandbox() }, clear: function () { this.element.innerHTML = a.displaysCaretInEmptyContentEditableCorrectly() ? "" : this.CARET_HACK }, getValue: function (a) { var c = this.isEmpty() ? "" : b.quirks.getCorrectInnerHTML(this.element); a && (c = this.parent.parse(c)); return c = b.lang.string(c).replace(b.INVISIBLE_SPACE).by("") }, setValue: function (a,
            b) { b && (a = this.parent.parse(a)); this.element.innerHTML = a }, show: function () { this.iframe.style.display = this._displayStyle || ""; this.disable(); this.enable() }, hide: function () { this._displayStyle = c.getStyle("display").from(this.iframe); "none" === this._displayStyle && (this._displayStyle = null); this.iframe.style.display = "none" }, disable: function () { this.element.removeAttribute("contentEditable"); this.base() }, enable: function () { this.element.setAttribute("contentEditable", "true"); this.base() }, focus: function (a) {
                b.browser.doesAsyncFocus() &&
                this.hasPlaceholderSet() && this.clear(); this.base(); var c = this.element.lastChild; a && c && ("BR" === c.nodeName ? this.selection.setBefore(this.element.lastChild) : this.selection.setAfter(this.element.lastChild))
            }, getTextContent: function () { return c.getTextContent(this.element) }, hasPlaceholderSet: function () { return this.getTextContent() == this.textarea.element.getAttribute("placeholder") }, isEmpty: function () {
                var a = this.element.innerHTML; return "" === a || a === this.CARET_HACK || this.hasPlaceholderSet() || "" === this.getTextContent() &&
                    !this.element.querySelector("blockquote, ul, ol, img, embed, object, table, iframe, svg, video, audio, button, input, select, textarea")
            }, _initSandbox: function () { var a = this; this.sandbox = new c.Sandbox(function () { a._create() }, { stylesheets: this.config.stylesheets }); this.iframe = this.sandbox.getIframe(); var b = document.createElement("input"); b.type = "hidden"; b.name = "_wysihtml5_mode"; b.value = 1; var f = this.textarea.element; c.insert(this.iframe).after(f); c.insert(b).after(f) }, _create: function () {
                var d = this; this.doc =
                    this.sandbox.getDocument(); this.element = this.doc.body; this.textarea = this.parent.textarea; this.element.innerHTML = this.textarea.getValue(!0); this.enable(); this.selection = new b.Selection(this.parent); this.commands = new b.Commands(this.parent); c.copyAttributes("className spellcheck title lang dir accessKey".split(" ")).from(this.textarea.element).to(this.element); c.addClass(this.element, this.config.composerClassName); this.config.style && this.style(); this.observe(); var e = this.config.name; e && (c.addClass(this.element,
                        e), c.addClass(this.iframe, e)); (e = "string" === typeof this.config.placeholder ? this.config.placeholder : this.textarea.element.getAttribute("placeholder")) && c.simulatePlaceholder(this.parent, this, e); this.commands.exec("styleWithCSS", !1); this._initAutoLinking(); this._initObjectResizing(); this._initUndoManager(); (this.textarea.element.hasAttribute("autofocus") || document.querySelector(":focus") == this.textarea.element) && setTimeout(function () { d.focus() }, 100); b.quirks.insertLineBreakOnReturn(this); a.clearsContentEditableCorrectly() ||
                            b.quirks.ensureProperClearing(this); a.clearsListsInContentEditableCorrectly() || b.quirks.ensureProperClearingOfLists(this); this.initSync && this.config.sync && this.initSync(); this.textarea.hide(); this.parent.fire("beforeload").fire("load")
            }, _initAutoLinking: function () {
                var d = this, e = a.canDisableAutoLinking(), f = a.doesAutoLinkingInContentEditable(); e && this.commands.exec("autoUrlDetect", !1); if (this.config.autoLink) {
                (!f || f && e) && this.parent.observe("newword:composer", function () {
                    d.selection.executeAndRestore(function (a,
                        b) { c.autoLink(b.parentNode) })
                }); var g = this.sandbox.getDocument().getElementsByTagName("a"), i = c.autoLink.URL_REG_EXP, h = function (a) { a = b.lang.string(c.getTextContent(a)).trim(); "www." === a.substr(0, 4) && (a = "http://" + a); return a }; c.observe(this.element, "keydown", function (a) { if (g.length) { var a = d.selection.getSelectedNode(a.target.ownerDocument), b = c.getParentElement(a, { nodeName: "A" }, 4), e; b && (e = h(b), setTimeout(function () { var a = h(b); a !== e && a.match(i) && b.setAttribute("href", a) }, 0)) } })
                }
            }, _initObjectResizing: function () {
                var d =
                    ["width", "height"], e = d.length, f = this.element; this.commands.exec("enableObjectResizing", this.config.allowObjectResizing); this.config.allowObjectResizing ? a.supportsEvent("resizeend") && c.observe(f, "resizeend", function (a) { for (var a = a.target || a.srcElement, c = a.style, h = 0, k; h < e; h++)k = d[h], c[k] && (a.setAttribute(k, parseInt(c[k], 10)), c[k] = ""); b.quirks.redraw(f) }) : a.supportsEvent("resizestart") && c.observe(f, "resizestart", function (a) { a.preventDefault() })
            }, _initUndoManager: function () { new b.UndoManager(this.parent) }
    })
})(wysihtml5);
(function (b) {
    var c = b.dom, a = document, d = window, e = a.createElement("div"), f = "background-color color cursor font-family font-size font-style font-variant font-weight line-height letter-spacing text-align text-decoration text-indent text-rendering word-break word-wrap word-spacing".split(" "), g = "background-color border-collapse border-bottom-color border-bottom-style border-bottom-width border-left-color border-left-style border-left-width border-right-color border-right-style border-right-width border-top-color border-top-style border-top-width clear display float margin-bottom margin-left margin-right margin-top outline-color outline-offset outline-width outline-style padding-left padding-right padding-top padding-bottom position top left right bottom z-index vertical-align text-align -webkit-box-sizing -moz-box-sizing -ms-box-sizing box-sizing -webkit-box-shadow -moz-box-shadow -ms-box-shadow box-shadow -webkit-border-top-right-radius -moz-border-radius-topright border-top-right-radius -webkit-border-bottom-right-radius -moz-border-radius-bottomright border-bottom-right-radius -webkit-border-bottom-left-radius -moz-border-radius-bottomleft border-bottom-left-radius -webkit-border-top-left-radius -moz-border-radius-topleft border-top-left-radius width height".split(" "),
    i = "width height top left right bottom".split(" "), h = ["html             { height: 100%; }", "body             { min-height: 100%; padding: 0; margin: 0; margin-top: -1px; padding-top: 1px; }", "._wysihtml5-temp { display: none; }", b.browser.isGecko ? "body.placeholder { color: graytext !important; }" : "body.placeholder { color: #a9a9a9 !important; }", "body[disabled]   { background-color: #eee !important; color: #999 !important; cursor: default !important; }", "img:-moz-broken  { -moz-force-broken-image-icon: 1; height: 24px; width: 24px; }"],
    k = function (b) { if (b.setActive) try { b.setActive() } catch (e) { } else { var f = b.style, h = a.documentElement.scrollTop || a.body.scrollTop, g = a.documentElement.scrollLeft || a.body.scrollLeft, f = { position: f.position, top: f.top, left: f.left, WebkitUserSelect: f.WebkitUserSelect }; c.setStyles({ position: "absolute", top: "-99999px", left: "-99999px", WebkitUserSelect: "none" }).on(b); b.focus(); c.setStyles(f).on(b); d.scrollTo && d.scrollTo(g, h) } }; b.views.Composer.prototype.style = function () {
        var j = this, n = a.querySelector(":focus"), p = this.textarea.element,
        q = p.hasAttribute("placeholder"), r = q && p.getAttribute("placeholder"); this.focusStylesHost = this.focusStylesHost || e.cloneNode(!1); this.blurStylesHost = this.blurStylesHost || e.cloneNode(!1); q && p.removeAttribute("placeholder"); p === n && p.blur(); c.copyStyles(g).from(p).to(this.iframe).andTo(this.blurStylesHost); c.copyStyles(f).from(p).to(this.element).andTo(this.blurStylesHost); c.insertCSS(h).into(this.element.ownerDocument); k(p); c.copyStyles(g).from(p).to(this.focusStylesHost); c.copyStyles(f).from(p).to(this.focusStylesHost);
        var m = b.lang.array(g).without(["display"]); n ? n.focus() : p.blur(); q && p.setAttribute("placeholder", r); if (!b.browser.hasCurrentStyleProperty()) var s = c.observe(d, "resize", function () { if (c.contains(document.documentElement, j.iframe)) { var a = c.getStyle("display").from(p), b = c.getStyle("display").from(j.iframe); p.style.display = ""; j.iframe.style.display = "none"; c.copyStyles(i).from(p).to(j.iframe).andTo(j.focusStylesHost).andTo(j.blurStylesHost); j.iframe.style.display = b; p.style.display = a } else s.stop() }); this.parent.observe("focus:composer",
            function () { c.copyStyles(m).from(j.focusStylesHost).to(j.iframe); c.copyStyles(f).from(j.focusStylesHost).to(j.element) }); this.parent.observe("blur:composer", function () { c.copyStyles(m).from(j.blurStylesHost).to(j.iframe); c.copyStyles(f).from(j.blurStylesHost).to(j.element) }); return this
    }
})(wysihtml5);
(function (b) {
    var c = b.dom, a = b.browser, d = { 66: "bold", 73: "italic", 85: "underline" }; b.views.Composer.prototype.observe = function () {
        var e = this, f = this.getValue(), g = this.sandbox.getIframe(), i = this.element, h = a.supportsEventsInIframeCorrectly() ? i : this.sandbox.getWindow(), k = a.supportsEvent("drop") ? ["drop", "paste"] : ["dragdrop", "paste"]; c.observe(g, "DOMNodeRemoved", function () { clearInterval(j); e.parent.fire("destroy:composer") }); var j = setInterval(function () {
            c.contains(document.documentElement, g) || (clearInterval(j),
                e.parent.fire("destroy:composer"))
        }, 250); c.observe(h, "focus", function () { e.parent.fire("focus").fire("focus:composer"); setTimeout(function () { f = e.getValue() }, 0) }); c.observe(h, "blur", function () { f !== e.getValue() && e.parent.fire("change").fire("change:composer"); e.parent.fire("blur").fire("blur:composer") }); b.browser.isIos() && c.observe(i, "blur", function () {
            var a = i.ownerDocument.createElement("input"), b = document.documentElement.scrollTop || document.body.scrollTop, c = document.documentElement.scrollLeft || document.body.scrollLeft;
            try { e.selection.insertNode(a) } catch (d) { i.appendChild(a) } a.focus(); a.parentNode.removeChild(a); window.scrollTo(c, b)
        }); c.observe(i, "dragenter", function () { e.parent.fire("unset_placeholder") }); a.firesOnDropOnlyWhenOnDragOverIsCancelled() && c.observe(i, ["dragover", "dragenter"], function (a) { a.preventDefault() }); c.observe(i, k, function (b) {
            var c = b.dataTransfer, d; c && a.supportsDataTransfer() && (d = c.getData("text/html") || c.getData("text/plain")); d ? (i.focus(), e.commands.exec("insertHTML", d), e.parent.fire("paste").fire("paste:composer"),
                b.stopPropagation(), b.preventDefault()) : setTimeout(function () { e.parent.fire("paste").fire("paste:composer") }, 0)
        }); c.observe(i, "keyup", function (a) { a = a.keyCode; (a === b.SPACE_KEY || a === b.ENTER_KEY) && e.parent.fire("newword:composer") }); this.parent.observe("paste:composer", function () { setTimeout(function () { e.parent.fire("newword:composer") }, 0) }); a.canSelectImagesInContentEditable() || c.observe(i, "mousedown", function (a) { var b = a.target; "IMG" === b.nodeName && (e.selection.selectNode(b), a.preventDefault()) }); c.observe(i,
            "keydown", function (a) { var b = d[a.keyCode]; if ((a.ctrlKey || a.metaKey) && !a.altKey && b) e.commands.exec(b), a.preventDefault() }); c.observe(i, "keydown", function (a) { var c = e.selection.getSelectedNode(!0), d = a.keyCode; if (c && "IMG" === c.nodeName && (d === b.BACKSPACE_KEY || d === b.DELETE_KEY)) d = c.parentNode, d.removeChild(c), "A" === d.nodeName && !d.firstChild && d.parentNode.removeChild(d), setTimeout(function () { b.quirks.redraw(i) }, 0), a.preventDefault() }); var n = { IMG: "Image: ", A: "Link: " }; c.observe(i, "mouseover", function (a) {
                var a =
                    a.target, b = a.nodeName; !("A" !== b && "IMG" !== b) && !a.hasAttribute("title") && (b = n[b] + (a.getAttribute("href") || a.getAttribute("src")), a.setAttribute("title", b))
            })
    }
})(wysihtml5);
(function (b) {
    b.views.Synchronizer = Base.extend({
        constructor: function (b, a, d) { this.editor = b; this.textarea = a; this.composer = d; this._observe() }, fromComposerToTextarea: function (c) { this.textarea.setValue(b.lang.string(this.composer.getValue()).trim(), c) }, fromTextareaToComposer: function (b) { var a = this.textarea.getValue(); a ? this.composer.setValue(a, b) : (this.composer.clear(), this.editor.fire("set_placeholder")) }, sync: function (b) { "textarea" === this.editor.currentView.name ? this.fromTextareaToComposer(b) : this.fromComposerToTextarea(b) },
        _observe: function () {
            var c, a = this, d = this.textarea.element.form, e = function () { c = setInterval(function () { a.fromComposerToTextarea() }, 400) }, f = function () { clearInterval(c); c = null }; e(); d && (b.dom.observe(d, "submit", function () { a.sync(!0) }), b.dom.observe(d, "reset", function () { setTimeout(function () { a.fromTextareaToComposer() }, 0) })); this.editor.observe("change_view", function (b) { if (b === "composer" && !c) { a.fromTextareaToComposer(true); e() } else if (b === "textarea") { a.fromComposerToTextarea(true); f() } }); this.editor.observe("destroy:composer",
                f)
        }
    })
})(wysihtml5);
wysihtml5.views.Textarea = wysihtml5.views.View.extend({
    name: "textarea", constructor: function (b, c, a) { this.base(b, c, a); this._observe() }, clear: function () { this.element.value = "" }, getValue: function (b) { var c = this.isEmpty() ? "" : this.element.value; b && (c = this.parent.parse(c)); return c }, setValue: function (b, c) { c && (b = this.parent.parse(b)); this.element.value = b }, hasPlaceholderSet: function () {
        var b = wysihtml5.browser.supportsPlaceholderAttributeOn(this.element), c = this.element.getAttribute("placeholder") || null, a = this.element.value;
        return b && !a || a === c
    }, isEmpty: function () { return !wysihtml5.lang.string(this.element.value).trim() || this.hasPlaceholderSet() }, _observe: function () {
        var b = this.element, c = this.parent, a = { focusin: "focus", focusout: "blur" }, d = wysihtml5.browser.supportsEvent("focusin") ? ["focusin", "focusout", "change"] : ["focus", "blur", "change"]; c.observe("beforeload", function () {
            wysihtml5.dom.observe(b, d, function (b) { b = a[b.type] || b.type; c.fire(b).fire(b + ":textarea") }); wysihtml5.dom.observe(b, ["paste", "drop"], function () {
                setTimeout(function () { c.fire("paste").fire("paste:textarea") },
                    0)
            })
        })
    }
});
(function (b) {
    var c = b.dom; b.toolbar.Dialog = b.lang.Dispatcher.extend({
        constructor: function (a, b) { this.link = a; this.container = b }, _observe: function () {
            if (!this._observed) {
                var a = this, d = function (b) { var c = a._serialize(); c == a.elementToChange ? a.fire("edit", c) : a.fire("save", c); a.hide(); b.preventDefault(); b.stopPropagation() }; c.observe(a.link, "click", function () { c.hasClass(a.link, "wysihtml5-command-dialog-opened") && setTimeout(function () { a.hide() }, 0) }); c.observe(this.container, "keydown", function (c) {
                    var e = c.keyCode;
                    e === b.ENTER_KEY && d(c); e === b.ESCAPE_KEY && a.hide()
                }); c.delegate(this.container, "[data-wysihtml5-dialog-action=save]", "click", d); c.delegate(this.container, "[data-wysihtml5-dialog-action=cancel]", "click", function (b) { a.fire("cancel"); a.hide(); b.preventDefault(); b.stopPropagation() }); for (var e = this.container.querySelectorAll("input, select, textarea"), f = 0, g = e.length, i = function () { clearInterval(a.interval) }; f < g; f++)c.observe(e[f], "change", i); this._observed = !0
            }
        }, _serialize: function () {
            for (var a = this.elementToChange ||
                {}, b = this.container.querySelectorAll("[data-wysihtml5-dialog-field]"), c = b.length, f = 0; f < c; f++)a[b[f].getAttribute("data-wysihtml5-dialog-field")] = b[f].value; return a
        }, _interpolate: function (a) { for (var b, c, f = document.querySelector(":focus"), g = this.container.querySelectorAll("[data-wysihtml5-dialog-field]"), i = g.length, h = 0; h < i; h++)b = g[h], b !== f && !(a && "hidden" === b.type) && (c = b.getAttribute("data-wysihtml5-dialog-field"), c = this.elementToChange ? this.elementToChange[c] || "" : b.defaultValue, b.value = c) }, show: function (a) {
            var b =
                this, e = this.container.querySelector("input, select, textarea"); this.elementToChange = a; this._observe(); this._interpolate(); a && (this.interval = setInterval(function () { b._interpolate(!0) }, 500)); c.addClass(this.link, "wysihtml5-command-dialog-opened"); this.container.style.display = ""; this.fire("show"); if (e && !a) try { e.focus() } catch (f) { }
        }, hide: function () { clearInterval(this.interval); this.elementToChange = null; c.removeClass(this.link, "wysihtml5-command-dialog-opened"); this.container.style.display = "none"; this.fire("hide") }
    })
})(wysihtml5);
(function (b) {
    var c = b.dom, a = { position: "relative" }, d = { left: 0, margin: 0, opacity: 0, overflow: "hidden", padding: 0, position: "absolute", top: 0, zIndex: 1 }, e = { cursor: "inherit", fontSize: "50px", height: "50px", marginTop: "-25px", outline: 0, padding: 0, position: "absolute", right: "-4px", top: "50%" }, f = { "x-webkit-speech": "", speech: "" }; b.toolbar.Speech = function (g, i) {
        var h = document.createElement("input"); if (b.browser.supportsSpeechApiOn(h)) {
            var k = document.createElement("div"); b.lang.object(d).merge({
                width: i.offsetWidth + "px", height: i.offsetHeight +
                    "px"
            }); c.insert(h).into(k); c.insert(k).into(i); c.setStyles(e).on(h); c.setAttributes(f).on(h); c.setStyles(d).on(k); c.setStyles(a).on(i); c.observe(h, "onwebkitspeechchange" in h ? "webkitspeechchange" : "speechchange", function () { g.execCommand("insertText", h.value); h.value = "" }); c.observe(h, "click", function (a) { c.hasClass(i, "wysihtml5-command-disabled") && a.preventDefault(); a.stopPropagation() })
        } else i.style.display = "none"
    }
})(wysihtml5);
(function (b) {
    var c = b.dom; b.toolbar.Toolbar = Base.extend({
        constructor: function (a, c) { this.editor = a; this.container = "string" === typeof c ? document.getElementById(c) : c; this.composer = a.composer; this._getLinks("command"); this._getLinks("action"); this._observe(); this.show(); for (var e = this.container.querySelectorAll("[data-wysihtml5-command=insertSpeech]"), f = e.length, g = 0; g < f; g++)new b.toolbar.Speech(this, e[g]) }, _getLinks: function (a) {
            for (var c = this[a + "Links"] = b.lang.array(this.container.querySelectorAll("[data-wysihtml5-" +
                a + "]")).get(), e = c.length, f = 0, g = this[a + "Mapping"] = {}, i, h, k, j, n; f < e; f++)i = c[f], k = i.getAttribute("data-wysihtml5-" + a), j = i.getAttribute("data-wysihtml5-" + a + "-value"), h = this.container.querySelector("[data-wysihtml5-" + a + "-group='" + k + "']"), n = this._getDialog(i, k), g[k + ":" + j] = { link: i, group: h, name: k, value: j, dialog: n, state: !1 }
        }, _getDialog: function (a, c) {
            var e = this, f = this.container.querySelector("[data-wysihtml5-dialog='" + c + "']"), g, i; f && (g = new b.toolbar.Dialog(a, f), g.observe("show", function () {
                i = e.composer.selection.getBookmark();
                e.editor.fire("show:dialog", { command: c, dialogContainer: f, commandLink: a })
            }), g.observe("save", function (b) { i && e.composer.selection.setBookmark(i); e._execCommand(c, b); e.editor.fire("save:dialog", { command: c, dialogContainer: f, commandLink: a }) }), g.observe("cancel", function () { e.editor.focus(!1); e.editor.fire("cancel:dialog", { command: c, dialogContainer: f, commandLink: a }) })); return g
        }, execCommand: function (a, b) {
            if (!this.commandsDisabled) {
                var c = this.commandMapping[a + ":" + b]; c && c.dialog && !c.state ? c.dialog.show() :
                    this._execCommand(a, b)
            }
        }, _execCommand: function (a, b) { this.editor.focus(!1); this.composer.commands.exec(a, b); this._updateLinkStates() }, execAction: function (a) { var b = this.editor; switch (a) { case "change_view": b.currentView === b.textarea ? b.fire("change_view", "composer") : b.fire("change_view", "textarea") } }, _observe: function () {
            for (var a = this, b = this.editor, e = this.container, f = this.commandLinks.concat(this.actionLinks), g = f.length, i = 0; i < g; i++)c.setAttributes({ href: "javascript:;", unselectable: "on" }).on(f[i]); c.delegate(e,
                "[data-wysihtml5-command]", "mousedown", function (a) { a.preventDefault() }); c.delegate(e, "[data-wysihtml5-command]", "click", function (b) { var c = this.getAttribute("data-wysihtml5-command"), d = this.getAttribute("data-wysihtml5-command-value"); a.execCommand(c, d); b.preventDefault() }); c.delegate(e, "[data-wysihtml5-action]", "click", function (b) { var c = this.getAttribute("data-wysihtml5-action"); a.execAction(c); b.preventDefault() }); b.observe("focus:composer", function () {
                a.bookmark = null; clearInterval(a.interval); a.interval =
                    setInterval(function () { a._updateLinkStates() }, 500)
                }); b.observe("blur:composer", function () { clearInterval(a.interval) }); b.observe("destroy:composer", function () { clearInterval(a.interval) }); b.observe("change_view", function (b) { setTimeout(function () { a.commandsDisabled = "composer" !== b; a._updateLinkStates(); a.commandsDisabled ? c.addClass(e, "wysihtml5-commands-disabled") : c.removeClass(e, "wysihtml5-commands-disabled") }, 0) })
        }, _updateLinkStates: function () {
            var a = this.commandMapping, d = this.actionMapping, e, f, g; for (e in a) if (g =
                a[e], this.commandsDisabled ? (f = !1, c.removeClass(g.link, "wysihtml5-command-active"), g.group && c.removeClass(g.group, "wysihtml5-command-active"), g.dialog && g.dialog.hide()) : (f = this.composer.commands.state(g.name, g.value), b.lang.object(f).isArray() && (f = 1 === f.length ? f[0] : !0), c.removeClass(g.link, "wysihtml5-command-disabled"), g.group && c.removeClass(g.group, "wysihtml5-command-disabled")), g.state !== f) (g.state = f) ? (c.addClass(g.link, "wysihtml5-command-active"), g.group && c.addClass(g.group, "wysihtml5-command-active"),
                    g.dialog && ("object" === typeof f ? g.dialog.show(f) : g.dialog.hide())) : (c.removeClass(g.link, "wysihtml5-command-active"), g.group && c.removeClass(g.group, "wysihtml5-command-active"), g.dialog && g.dialog.hide()); for (e in d) a = d[e], "change_view" === a.name && (a.state = this.editor.currentView === this.editor.textarea, a.state ? c.addClass(a.link, "wysihtml5-action-active") : c.removeClass(a.link, "wysihtml5-action-active"))
        }, show: function () { this.container.style.display = "" }, hide: function () { this.container.style.display = "none" }
    })
})(wysihtml5);
(function (b) {
    var c = { name: void 0, style: !0, toolbar: void 0, autoLink: !0, parserRules: { tags: { br: {}, span: {}, div: {}, p: {} }, classes: {} }, parser: b.dom.parse, composerClassName: "wysihtml5-editor", bodyClassName: "wysihtml5-supported", stylesheets: [], placeholderText: void 0, allowObjectResizing: !0, supportTouchDevices: !0 }; b.Editor = b.lang.Dispatcher.extend({
        constructor: function (a, d) {
        this.textareaElement = "string" === typeof a ? document.getElementById(a) : a; this.config = b.lang.object({}).merge(c).merge(d).get(); this.currentView =
            this.textarea = new b.views.Textarea(this, this.textareaElement, this.config); this._isCompatible = b.browser.supported(); if (!this._isCompatible || !this.config.supportTouchDevices && b.browser.isTouchDevice()) { var e = this; setTimeout(function () { e.fire("beforeload").fire("load") }, 0) } else {
                b.dom.addClass(document.body, this.config.bodyClassName); this.currentView = this.composer = new b.views.Composer(this, this.textareaElement, this.config); "function" === typeof this.config.parser && this._initParser(); this.observe("beforeload",
                    function () { this.synchronizer = new b.views.Synchronizer(this, this.textarea, this.composer); this.config.toolbar && (this.toolbar = new b.toolbar.Toolbar(this, this.config.toolbar)) }); try {  } catch (f) { }
            }
        }, isCompatible: function () { return this._isCompatible }, clear: function () { this.currentView.clear(); return this }, getValue: function (a) { return this.currentView.getValue(a) }, setValue: function (a, b) {
            if (!a) return this.clear();
            this.currentView.setValue(a, b); return this
        }, focus: function (a) { this.currentView.focus(a); return this }, disable: function () { this.currentView.disable(); return this }, enable: function () { this.currentView.enable(); return this }, isEmpty: function () { return this.currentView.isEmpty() }, hasPlaceholderSet: function () { return this.currentView.hasPlaceholderSet() }, parse: function (a) { var c = this.config.parser(a, this.config.parserRules, this.composer.sandbox.getDocument(), !0); "object" === typeof a && b.quirks.redraw(a); return c },
        _initParser: function () { this.observe("paste:composer", function () { var a = this; a.composer.selection.executeAndRestore(function () { b.quirks.cleanPastedHTML(a.composer.element); a.parse(a.composer.element) }, !0) }); this.observe("paste:textarea", function () { this.textarea.setValue(this.parse(this.textarea.getValue())) }) }
    })
})(wysihtml5);;
!function (t, a) { "use strict"; var l = { "font-styles": function (t, a) { var l = a && a.size ? " btn-" + a.size : ""; return "<li class='dropdown'><a class='btn btn-default dropdown-toggle" + l + "' data-toggle='dropdown' href='#'><i class='glyphicon glyphicon-font'></i>&nbsp;<span class='current-font'>" + t.font_styles.normal + "</span>&nbsp;<b class='caret'></b></a><ul class='dropdown-menu'><li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='div' tabindex='-1'>" + t.font_styles.normal + "</a></li><li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='h1' tabindex='-1'>" + t.font_styles.h1 + "</a></li><li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='h2' tabindex='-1'>" + t.font_styles.h2 + "</a></li><li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='h3' tabindex='-1'>" + t.font_styles.h3 + "</a></li></ul></li>" }, emphasis: function (t, a) { var l = a && a.size ? " btn-" + a.size : ""; return "<li><div class='btn-group'><a class='btn btn-default" + l + "' data-wysihtml5-command='bold' title='CTRL+B' tabindex='-1'>" + t.emphasis.bold + "</a><a class='btn btn-default" + l + "' data-wysihtml5-command='italic' title='CTRL+I' tabindex='-1'>" + t.emphasis.italic + "</a><a class='btn btn-default" + l + "' data-wysihtml5-command='underline' title='CTRL+U' tabindex='-1'>" + t.emphasis.underline + "</a></div></li>" }, lists: function (t, a) { var l = a && a.size ? " btn-" + a.size : ""; return "<li><div class='btn-group'><a class='btn btn-default" + l + "' data-wysihtml5-command='insertUnorderedList' title='" + t.lists.unordered + "' tabindex='-1'><i class='glyphicon glyphicon-list'></i></a><a class='btn btn-default" + l + "' data-wysihtml5-command='insertOrderedList' title='" + t.lists.ordered + "' tabindex='-1'><i class='glyphicon glyphicon-th-list'></i></a><a class='btn btn-default" + l + "' data-wysihtml5-command='Outdent' title='" + t.lists.outdent + "' tabindex='-1'><i class='glyphicon glyphicon-indent-right'></i></a><a class='btn btn-default" + l + "' data-wysihtml5-command='Indent' title='" + t.lists.indent + "' tabindex='-1'><i class='glyphicon glyphicon-indent-left'></i></a></div></li>" }, link: function (t, a) { var l = a && a.size ? " btn-" + a.size : ""; return "<li><div class='bootstrap-wysihtml5-insert-link-modal modal hide fade'><div class='modal-header'><a class='close' data-dismiss='modal'>&times;</a><h3>" + t.link.insert + "</h3></div><div class='modal-body'><input value='http://' class='bootstrap-wysihtml5-insert-link-url input-xlarge'></div><div class='modal-footer'><a href='#' class='btn btn-default' data-dismiss='modal'>" + t.link.cancel + "</a><a href='#' class='btn btn-primary' data-dismiss='modal'>" + t.link.insert + "</a></div></div><a class='btn btn-default" + l + "' data-wysihtml5-command='createLink' title='" + t.link.insert + "' tabindex='-1'><i class='glyphicon glyphicon-share'></i></a></li>" }, image: function (t, a) { var l = a && a.size ? " btn-" + a.size : ""; return "<li><div class='bootstrap-wysihtml5-insert-image-modal modal hide fade'><div class='modal-header'><a class='close' data-dismiss='modal'>&times;</a><h3>" + t.image.insert + "</h3></div><div class='modal-body'><input value='http://' class='bootstrap-wysihtml5-insert-image-url input-xlarge'></div><div class='modal-footer'><a href='#' class='btn btn-default' data-dismiss='modal'>" + t.image.cancel + "</a><a href='#' class='btn btn-primary' data-dismiss='modal'>" + t.image.insert + "</a></div></div><a class='btn btn-default" + l + "' data-wysihtml5-command='insertImage' title='" + t.image.insert + "' tabindex='-1'><i class='glyphicon glyphicon-picture'></i></a></li>" }, html: function (t, a) { var l = a && a.size ? " btn-" + a.size : ""; return "<li><div class='btn-group'><a class='btn btn-default" + l + "' data-wysihtml5-action='change_view' title='" + t.html.edit + "' tabindex='-1'><i class='glyphicon glyphicon-pencil'></i></a></div></li>" }, color: function (t, a) { var l = a && a.size ? " btn-" + a.size : ""; return "<li class='dropdown'><a class='btn btn-default dropdown-toggle" + l + "' data-toggle='dropdown' href='#' tabindex='-1'><span class='current-color'>" + t.colours.black + "</span>&nbsp;<b class='caret'></b></a><ul class='dropdown-menu'><li><div class='wysihtml5-colors' data-wysihtml5-command-value='black'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='black'>" + t.colours.black + "</a></li><li><div class='wysihtml5-colors' data-wysihtml5-command-value='silver'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='silver'>" + t.colours.silver + "</a></li><li><div class='wysihtml5-colors' data-wysihtml5-command-value='gray'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='gray'>" + t.colours.gray + "</a></li><li><div class='wysihtml5-colors' data-wysihtml5-command-value='maroon'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='maroon'>" + t.colours.maroon + "</a></li><li><div class='wysihtml5-colors' data-wysihtml5-command-value='red'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='red'>" + t.colours.red + "</a></li><li><div class='wysihtml5-colors' data-wysihtml5-command-value='purple'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='purple'>" + t.colours.purple + "</a></li><li><div class='wysihtml5-colors' data-wysihtml5-command-value='green'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='green'>" + t.colours.green + "</a></li><li><div class='wysihtml5-colors' data-wysihtml5-command-value='olive'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='olive'>" + t.colours.olive + "</a></li><li><div class='wysihtml5-colors' data-wysihtml5-command-value='navy'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='navy'>" + t.colours.navy + "</a></li><li><div class='wysihtml5-colors' data-wysihtml5-command-value='blue'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='blue'>" + t.colours.blue + "</a></li><li><div class='wysihtml5-colors' data-wysihtml5-command-value='orange'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='orange'>" + t.colours.orange + "</a></li></ul></li>" } }, i = function (t, a, i) { return l[t](a, i) }, s = function (a, i) { this.el = a; var s = i || e; for (var o in s.customTemplates) l[o] = s.customTemplates[o]; this.toolbar = this.createToolbar(a, s), this.editor = this.createEditor(i), window.editor = this.editor, t("iframe.wysihtml5-sandbox").each(function (a, l) { t(l.contentWindow).off("focus.wysihtml5").on({ "focus.wysihtml5": function () { t("li.dropdown").removeClass("open") } }) }) }; s.prototype = { constructor: s, createEditor: function (l) { l = l || {}, l = t.extend(!0, {}, l), l.toolbar = this.toolbar[0]; var i = new a.Editor(this.el[0], l); if (l && l.events) for (var s in l.events) i.on(s, l.events[s]); return i }, createToolbar: function (a, l) { var s = this, o = t("<ul/>", { "class": "wysihtml5-toolbar", style: "display:none" }), r = l.locale || e.locale || "en"; for (var d in e) { var c = !1; void 0 !== l[d] ? l[d] === !0 && (c = !0) : c = e[d], c === !0 && (o.append(i(d, n[r], l)), "html" === d && this.initHtml(o), "link" === d && this.initInsertLink(o), "image" === d && this.initInsertImage(o)) } if (l.toolbar) for (d in l.toolbar) o.append(l.toolbar[d]); return o.find("a[data-wysihtml5-command='formatBlock']").click(function (a) { var l = a.target || a.srcElement, i = t(l); s.toolbar.find(".current-font").text(i.html()) }), o.find("a[data-wysihtml5-command='foreColor']").click(function (a) { var l = a.target || a.srcElement, i = t(l); s.toolbar.find(".current-color").text(i.html()) }), this.el.before(o), o }, initHtml: function (t) { var a = "a[data-wysihtml5-action='change_view']"; t.find(a).click(function () { t.find("a.btn").not(a).toggleClass("disabled") }) }, initInsertImage: function (a) { var l, i = this, s = a.find(".bootstrap-wysihtml5-insert-image-modal"), o = s.find(".bootstrap-wysihtml5-insert-image-url"), e = s.find("a.btn-primary"), n = o.val(), r = function () { var t = o.val(); o.val(n), i.editor.currentView.element.focus(), l && (i.editor.composer.selection.setBookmark(l), l = null), i.editor.composer.commands.exec("insertImage", t) }; o.keypress(function (t) { 13 == t.which && (r(), s.modal("hide")) }), e.click(r), s.on("shown", function () { o.focus() }), s.on("hide", function () { i.editor.currentView.element.focus() }), a.find("a[data-wysihtml5-command=insertImage]").click(function () { var a = t(this).hasClass("wysihtml5-command-active"); return a ? !0 : (i.editor.currentView.element.focus(!1), l = i.editor.composer.selection.getBookmark(), s.appendTo("body").modal("show"), s.on("click.dismiss.modal", '[data-dismiss="modal"]', function (t) { t.stopPropagation() }), !1) }) }, initInsertLink: function (a) { var l, i = this, s = a.find(".bootstrap-wysihtml5-insert-link-modal"), o = s.find(".bootstrap-wysihtml5-insert-link-url"), e = s.find("a.btn-primary"), n = o.val(), r = function () { var t = o.val(); o.val(n), i.editor.currentView.element.focus(), l && (i.editor.composer.selection.setBookmark(l), l = null), i.editor.composer.commands.exec("createLink", { href: t, target: "_blank", rel: "nofollow" }) }; o.keypress(function (t) { 13 == t.which && (r(), s.modal("hide")) }), e.click(r), s.on("shown", function () { o.focus() }), s.on("hide", function () { i.editor.currentView.element.focus() }), a.find("a[data-wysihtml5-command=createLink]").click(function () { var a = t(this).hasClass("wysihtml5-command-active"); return a ? !0 : (i.editor.currentView.element.focus(!1), l = i.editor.composer.selection.getBookmark(), s.appendTo("body").modal("show"), s.on("click.dismiss.modal", '[data-dismiss="modal"]', function (t) { t.stopPropagation() }), !1) }) } }; var o = { resetDefaults: function () { t.fn.wysihtml5.defaultOptions = t.extend(!0, {}, t.fn.wysihtml5.defaultOptionsCache) }, bypassDefaults: function (a) { return this.each(function () { var l = t(this); l.data("wysihtml5", new s(l, a)) }) }, shallowExtend: function (a) { var l = t.extend({}, t.fn.wysihtml5.defaultOptions, a || {}), i = this; return o.bypassDefaults.apply(i, [l]) }, deepExtend: function (a) { var l = t.extend(!0, {}, t.fn.wysihtml5.defaultOptions, a || {}), i = this; return o.bypassDefaults.apply(i, [l]) }, init: function (t) { var a = this; return o.shallowExtend.apply(a, [t]) } }; t.fn.wysihtml5 = function (a) { return o[a] ? o[a].apply(this, Array.prototype.slice.call(arguments, 1)) : "object" != typeof a && a ? void t.error("Method " + a + " does not exist on jQuery.wysihtml5") : o.init.apply(this, arguments) }, t.fn.wysihtml5.Constructor = s; var e = t.fn.wysihtml5.defaultOptions = { "font-styles": !0, color: !1, emphasis: !0, lists: !0, html: !1, link: !0, image: !0, events: {}, parserRules: { classes: { "wysiwyg-color-silver": 1, "wysiwyg-color-gray": 1, "wysiwyg-color-white": 1, "wysiwyg-color-maroon": 1, "wysiwyg-color-red": 1, "wysiwyg-color-purple": 1, "wysiwyg-color-fuchsia": 1, "wysiwyg-color-green": 1, "wysiwyg-color-lime": 1, "wysiwyg-color-olive": 1, "wysiwyg-color-yellow": 1, "wysiwyg-color-navy": 1, "wysiwyg-color-blue": 1, "wysiwyg-color-teal": 1, "wysiwyg-color-aqua": 1, "wysiwyg-color-orange": 1 }, tags: { b: {}, i: {}, br: {}, ol: {}, ul: {}, li: {}, h1: {}, h2: {}, h3: {}, blockquote: {}, u: 1, img: { check_attributes: { width: "numbers", alt: "alt", src: "url", height: "numbers" } }, a: { set_attributes: { target: "_blank", rel: "nofollow" }, check_attributes: { href: "url" } }, span: 1, div: 1, code: 1, pre: 1 } }, stylesheets: ["./lib/css/wysiwyg-color.css"], locale: "en" }; void 0 === t.fn.wysihtml5.defaultOptionsCache && (t.fn.wysihtml5.defaultOptionsCache = t.extend(!0, {}, t.fn.wysihtml5.defaultOptions)); var n = t.fn.wysihtml5.locale = { en: { font_styles: { normal: "Normal text", h1: "Heading 1", h2: "Heading 2", h3: "Heading 3" }, emphasis: { bold: "Bold", italic: "Italic", underline: "Underline" }, lists: { unordered: "Unordered list", ordered: "Ordered list", outdent: "Outdent", indent: "Indent" }, link: { insert: "Insert link", cancel: "Cancel" }, image: { insert: "Insert image", cancel: "Cancel" }, html: { edit: "Edit HTML" }, colours: { black: "Black", silver: "Silver", gray: "Grey", maroon: "Maroon", red: "Red", purple: "Purple", green: "Green", olive: "Olive", navy: "Navy", blue: "Blue", orange: "Orange" } } } }(window.jQuery, window.wysihtml5);;

$(document).ready(function () {
    var cookieAlert = document.querySelector(".cookiealert");
    if (cookieAlert !== null) {
        var acceptCookies = document.querySelector(".acceptcookies");
        cookieAlert.offsetHeight;
        if (!getCookie("acceptCookies")) {
            cookieAlert.classList.add("show");
        }
        acceptCookies.addEventListener("click", function () {
            setCookie("acceptCookies", true, 60);
            cookieAlert.classList.remove("show");
        });
    }
});


function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) === 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
};
/*
 * jQuery Iframe Transport Plugin 1.6.1
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2011, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint unparam: true, nomen: true */
/*global define, window, document */

(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // Register as an anonymous AMD module:
        define(['jquery'], factory);
    } else {
        // Browser globals:
        factory(window.jQuery);
    }
}(function ($) {
    'use strict';

    // Helper variable to create unique names for the transport iframes:
    var counter = 0;

    // The iframe transport accepts three additional options:
    // options.fileInput: a jQuery collection of file input fields
    // options.paramName: the parameter name for the file form data,
    //  overrides the name property of the file input field(s),
    //  can be a string or an array of strings.
    // options.formData: an array of objects with name and value properties,
    //  equivalent to the return data of .serializeArray(), e.g.:
    //  [{name: 'a', value: 1}, {name: 'b', value: 2}]
    $.ajaxTransport('iframe', function (options) {
        if (options.async) {
            var form,
                iframe,
                addParamChar;
            return {
                send: function (_, completeCallback) {
                    form = $('<form style="display:none;"></form>');
                    form.attr('accept-charset', options.formAcceptCharset);
                    addParamChar = /\?/.test(options.url) ? '&' : '?';
                    // XDomainRequest only supports GET and POST:
                    if (options.type === 'DELETE') {
                        options.url = options.url + addParamChar + '_method=DELETE';
                        options.type = 'POST';
                    } else if (options.type === 'PUT') {
                        options.url = options.url + addParamChar + '_method=PUT';
                        options.type = 'POST';
                    } else if (options.type === 'PATCH') {
                        options.url = options.url + addParamChar + '_method=PATCH';
                        options.type = 'POST';
                    }
                    // javascript:false as initial iframe src
                    // prevents warning popups on HTTPS in IE6.
                    // IE versions below IE8 cannot set the name property of
                    // elements that have already been added to the DOM,
                    // so we set the name along with the iframe HTML markup:
                    iframe = $(
                        '<iframe src="javascript:false;" name="iframe-transport-' +
                            (counter += 1) + '"></iframe>'
                    ).bind('load', function () {
                        var fileInputClones,
                            paramNames = $.isArray(options.paramName) ?
                                    options.paramName : [options.paramName];
                        iframe
                            .unbind('load')
                            .bind('load', function () {
                                var response;
                                // Wrap in a try/catch block to catch exceptions thrown
                                // when trying to access cross-domain iframe contents:
                                try {
                                    response = iframe.contents();
                                    // Google Chrome and Firefox do not throw an
                                    // exception when calling iframe.contents() on
                                    // cross-domain requests, so we unify the response:
                                    if (!response.length || !response[0].firstChild) {
                                        throw new Error();
                                    }
                                } catch (e) {
                                    response = undefined;
                                }
                                // The complete callback returns the
                                // iframe content document as response object:
                                completeCallback(
                                    200,
                                    'success',
                                    {'iframe': response}
                                );
                                // Fix for IE endless progress bar activity bug
                                // (happens on form submits to iframe targets):
                                $('<iframe src="javascript:false;"></iframe>')
                                    .appendTo(form);
                                form.remove();
                            });
                        form
                            .prop('target', iframe.prop('name'))
                            .prop('action', options.url)
                            .prop('method', options.type);
                        if (options.formData) {
                            $.each(options.formData, function (index, field) {
                                $('<input type="hidden"/>')
                                    .prop('name', field.name)
                                    .val(field.value)
                                    .appendTo(form);
                            });
                        }
                        if (options.fileInput && options.fileInput.length &&
                                options.type === 'POST') {
                            fileInputClones = options.fileInput.clone();
                            // Insert a clone for each file input field:
                            options.fileInput.after(function (index) {
                                return fileInputClones[index];
                            });
                            if (options.paramName) {
                                options.fileInput.each(function (index) {
                                    $(this).prop(
                                        'name',
                                        paramNames[index] || options.paramName
                                    );
                                });
                            }
                            // Appending the file input fields to the hidden form
                            // removes them from their original location:
                            form
                                .append(options.fileInput)
                                .prop('enctype', 'multipart/form-data')
                                // enctype must be set as encoding for IE:
                                .prop('encoding', 'multipart/form-data');
                        }
                        form.submit();
                        // Insert the file input fields at their original location
                        // by replacing the clones with the originals:
                        if (fileInputClones && fileInputClones.length) {
                            options.fileInput.each(function (index, input) {
                                var clone = $(fileInputClones[index]);
                                $(input).prop('name', clone.prop('name'));
                                clone.replaceWith(input);
                            });
                        }
                    });
                    form.append(iframe).appendTo(document.body);
                },
                abort: function () {
                    if (iframe) {
                        // javascript:false as iframe src aborts the request
                        // and prevents warning popups on HTTPS in IE6.
                        // concat is used to avoid the "Script URL" JSLint error:
                        iframe
                            .unbind('load')
                            .prop('src', 'javascript'.concat(':false;'));
                    }
                    if (form) {
                        form.remove();
                    }
                }
            };
        }
    });

    // The iframe transport returns the iframe content document as response.
    // The following adds converters from iframe to text, json, html, and script:
    $.ajaxSetup({
        converters: {
            'iframe text': function (iframe) {
                return iframe && $(iframe[0].body).text();
            },
            'iframe json': function (iframe) {
                return iframe && $.parseJSON($(iframe[0].body).text());
            },
            'iframe html': function (iframe) {
                return iframe && $(iframe[0].body).html();
            },
            'iframe script': function (iframe) {
                return iframe && $.globalEval($(iframe[0].body).text());
            }
        }
    });

}));
;
/*
 * jQuery File Upload Plugin 5.28.8
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint nomen: true, unparam: true, regexp: true */
/*global define, window, document, File, Blob, FormData, location */

(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // Register as an anonymous AMD module:
        define([
            'jquery',
            'jquery.ui.widget'
        ], factory);
    } else {
        // Browser globals:
        factory(window.jQuery);
    }
}(function ($) {
    'use strict';

    // The FileReader API is not actually used, but works as feature detection,
    // as e.g. Safari supports XHR file uploads via the FormData API,
    // but not non-multipart XHR file uploads:
    $.support.xhrFileUpload = !!(window.XMLHttpRequestUpload && window.FileReader);
    $.support.xhrFormDataFileUpload = !!window.FormData;

    // The fileupload widget listens for change events on file input fields defined
    // via fileInput setting and paste or drop events of the given dropZone.
    // In addition to the default jQuery Widget methods, the fileupload widget
    // exposes the "add" and "send" methods, to add or directly send files using
    // the fileupload API.
    // By default, files added via file input selection, paste, drag & drop or
    // "add" method are uploaded immediately, but it is possible to override
    // the "add" callback option to queue file uploads.
    $.widget('blueimp.fileupload', {

        options: {
            // The drop target element(s), by the default the complete document.
            // Set to null to disable drag & drop support:
            dropZone: $(document),
            // The paste target element(s), by the default the complete document.
            // Set to null to disable paste support:
            pasteZone: $(document),
            // The file input field(s), that are listened to for change events.
            // If undefined, it is set to the file input fields inside
            // of the widget element on plugin initialization.
            // Set to null to disable the change listener.
            fileInput: undefined,
            // By default, the file input field is replaced with a clone after
            // each input field change event. This is required for iframe transport
            // queues and allows change events to be fired for the same file
            // selection, but can be disabled by setting the following option to false:
            replaceFileInput: true,
            // The parameter name for the file form data (the request argument name).
            // If undefined or empty, the name property of the file input field is
            // used, or "files[]" if the file input name property is also empty,
            // can be a string or an array of strings:
            paramName: undefined,
            // By default, each file of a selection is uploaded using an individual
            // request for XHR type uploads. Set to false to upload file
            // selections in one request each:
            singleFileUploads: true,
            // To limit the number of files uploaded with one XHR request,
            // set the following option to an integer greater than 0:
            limitMultiFileUploads: undefined,
            // Set the following option to true to issue all file upload requests
            // in a sequential order:
            sequentialUploads: false,
            // To limit the number of concurrent uploads,
            // set the following option to an integer greater than 0:
            limitConcurrentUploads: undefined,
            // Set the following option to true to force iframe transport uploads:
            forceIframeTransport: false,
            // Set the following option to the location of a redirect url on the
            // origin server, for cross-domain iframe transport uploads:
            redirect: undefined,
            // The parameter name for the redirect url, sent as part of the form
            // data and set to 'redirect' if this option is empty:
            redirectParamName: undefined,
            // Set the following option to the location of a postMessage window,
            // to enable postMessage transport uploads:
            postMessage: undefined,
            // By default, XHR file uploads are sent as multipart/form-data.
            // The iframe transport is always using multipart/form-data.
            // Set to false to enable non-multipart XHR uploads:
            multipart: true,
            // To upload large files in smaller chunks, set the following option
            // to a preferred maximum chunk size. If set to 0, null or undefined,
            // or the browser does not support the required Blob API, files will
            // be uploaded as a whole.
            maxChunkSize: undefined,
            // When a non-multipart upload or a chunked multipart upload has been
            // aborted, this option can be used to resume the upload by setting
            // it to the size of the already uploaded bytes. This option is most
            // useful when modifying the options object inside of the "add" or
            // "send" callbacks, as the options are cloned for each file upload.
            uploadedBytes: undefined,
            // By default, failed (abort or error) file uploads are removed from the
            // global progress calculation. Set the following option to false to
            // prevent recalculating the global progress data:
            recalculateProgress: true,
            // Interval in milliseconds to calculate and trigger progress events:
            progressInterval: 100,
            // Interval in milliseconds to calculate progress bitrate:
            bitrateInterval: 500,
            // By default, uploads are started automatically when adding files:
            autoUpload: true,

            // Additional form data to be sent along with the file uploads can be set
            // using this option, which accepts an array of objects with name and
            // value properties, a function returning such an array, a FormData
            // object (for XHR file uploads), or a simple object.
            // The form of the first fileInput is given as parameter to the function:
            formData: function (form) {
                return form.serializeArray();
            },

            // The add callback is invoked as soon as files are added to the fileupload
            // widget (via file input selection, drag & drop, paste or add API call).
            // If the singleFileUploads option is enabled, this callback will be
            // called once for each file in the selection for XHR file uplaods, else
            // once for each file selection.
            // The upload starts when the submit method is invoked on the data parameter.
            // The data object contains a files property holding the added files
            // and allows to override plugin options as well as define ajax settings.
            // Listeners for this callback can also be bound the following way:
            // .bind('fileuploadadd', func);
            // data.submit() returns a Promise object and allows to attach additional
            // handlers using jQuery's Deferred callbacks:
            // data.submit().done(func).fail(func).always(func);
            add: function (e, data) {

                if (data.autoUpload || (data.autoUpload !== false &&
                        ($(this).data('blueimp-fileupload') ||
                        $(this).data('fileupload')).options.autoUpload)) {
                    data.submit();
                }
            },

            // Other callbacks:

            // Callback for the submit event of each file upload:
            // submit: function (e, data) {}, // .bind('fileuploadsubmit', func);

            // Callback for the start of each file upload request:
            // send: function (e, data) {}, // .bind('fileuploadsend', func);

            // Callback for successful uploads:
            // done: function (e, data) {}, // .bind('fileuploaddone', func);

            // Callback for failed (abort or error) uploads:
            // fail: function (e, data) {}, // .bind('fileuploadfail', func);

            // Callback for completed (success, abort or error) requests:
            // always: function (e, data) {}, // .bind('fileuploadalways', func);

            // Callback for upload progress events:
            // progress: function (e, data) {}, // .bind('fileuploadprogress', func);

            // Callback for global upload progress events:
            // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);

            // Callback for uploads start, equivalent to the global ajaxStart event:
            // start: function (e) {}, // .bind('fileuploadstart', func);

            // Callback for uploads stop, equivalent to the global ajaxStop event:
            // stop: function (e) {}, // .bind('fileuploadstop', func);

            // Callback for change events of the fileInput(s):
            // change: function (e, data) {}, // .bind('fileuploadchange', func);

            // Callback for paste events to the pasteZone(s):
            // paste: function (e, data) {}, // .bind('fileuploadpaste', func);

            // Callback for drop events of the dropZone(s):
            // drop: function (e, data) {}, // .bind('fileuploaddrop', func);

            // Callback for dragover events of the dropZone(s):
            // dragover: function (e) {}, // .bind('fileuploaddragover', func);

            // Callback for the start of each chunk upload request:
            // chunksend: function (e, data) {}, // .bind('fileuploadchunksend', func);

            // Callback for successful chunk uploads:
            // chunkdone: function (e, data) {}, // .bind('fileuploadchunkdone', func);

            // Callback for failed (abort or error) chunk uploads:
            // chunkfail: function (e, data) {}, // .bind('fileuploadchunkfail', func);

            // Callback for completed (success, abort or error) chunk upload requests:
            // chunkalways: function (e, data) {}, // .bind('fileuploadchunkalways', func);

            // The plugin options are used as settings object for the ajax calls.
            // The following are jQuery ajax settings required for the file uploads:
            processData: false,
            contentType: false,
            cache: false
        },

        // A list of options that require a refresh after assigning a new value:
        _refreshOptionsList: [
            'fileInput',
            'dropZone',
            'pasteZone',
            'multipart',
            'forceIframeTransport'
        ],

        _BitrateTimer: function () {
            this.timestamp = ((Date.now) ? Date.now() : (new Date()).getTime());
            this.loaded = 0;
            this.bitrate = 0;
            this.getBitrate = function (now, loaded, interval) {
                var timeDiff = now - this.timestamp;
                if (!this.bitrate || !interval || timeDiff > interval) {
                    this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8;
                    this.loaded = loaded;
                    this.timestamp = now;
                }
                return this.bitrate;
            };
        },

        _isXHRUpload: function (options) {
            return !options.forceIframeTransport &&
                ((!options.multipart && $.support.xhrFileUpload) ||
                $.support.xhrFormDataFileUpload);
        },

        _getFormData: function (options) {
            var formData;
            if (typeof options.formData === 'function') {
                return options.formData(options.form);
            }
            if ($.isArray(options.formData)) {
                return options.formData;
            }
            if ($.type(options.formData) === 'object') {
                formData = [];
                $.each(options.formData, function (name, value) {
                    formData.push({name: name, value: value});
                });
                return formData;
            }
            return [];
        },

        _getTotal: function (files) {
            var total = 0;
            $.each(files, function (index, file) {
                total += file.size || 1;
            });
            return total;
        },

        _initProgressObject: function (obj) {
            var progress = {
                loaded: 0,
                total: 0,
                bitrate: 0
            };
            if (obj._progress) {
                $.extend(obj._progress, progress);
            } else {
                obj._progress = progress;
            }
        },

        _initResponseObject: function (obj) {
            var prop;
            if (obj._response) {
                for (prop in obj._response) {
                    if (obj._response.hasOwnProperty(prop)) {
                        delete obj._response[prop];
                    }
                }
            } else {
                obj._response = {};
            }
        },

        _onProgress: function (e, data) {
            if (e.lengthComputable) {
                var now = ((Date.now) ? Date.now() : (new Date()).getTime()),
                    loaded;
                if (data._time && data.progressInterval &&
                        (now - data._time < data.progressInterval) &&
                        e.loaded !== e.total) {
                    return;
                }
                data._time = now;
                loaded = Math.floor(
                    e.loaded / e.total * (data.chunkSize || data._progress.total)
                ) + (data.uploadedBytes || 0);
                // Add the difference from the previously loaded state
                // to the global loaded counter:
                this._progress.loaded += (loaded - data._progress.loaded);
                this._progress.bitrate = this._bitrateTimer.getBitrate(
                    now,
                    this._progress.loaded,
                    data.bitrateInterval
                );
                data._progress.loaded = data.loaded = loaded;
                data._progress.bitrate = data.bitrate = data._bitrateTimer.getBitrate(
                    now,
                    loaded,
                    data.bitrateInterval
                );
                // Trigger a custom progress event with a total data property set
                // to the file size(s) of the current upload and a loaded data
                // property calculated accordingly:
                this._trigger('progress', e, data);
                // Trigger a global progress event for all current file uploads,
                // including ajax calls queued for sequential file uploads:
                this._trigger('progressall', e, this._progress);
            }
        },

        _initProgressListener: function (options) {
            var that = this,
                xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
            // Accesss to the native XHR object is required to add event listeners
            // for the upload progress event:
            if (xhr.upload) {
                $(xhr.upload).bind('progress', function (e) {
                    var oe = e.originalEvent;
                    // Make sure the progress event properties get copied over:
                    e.lengthComputable = oe.lengthComputable;
                    e.loaded = oe.loaded;
                    e.total = oe.total;
                    that._onProgress(e, options);
                });
                options.xhr = function () {
                    return xhr;
                };
            }
        },

        _isInstanceOf: function (type, obj) {
            // Cross-frame instanceof check
            return Object.prototype.toString.call(obj) === '[object ' + type + ']';
        },

        _initXHRData: function (options) {
            var that = this,
                formData,
                file = options.files[0],
                // Ignore non-multipart setting if not supported:
                multipart = options.multipart || !$.support.xhrFileUpload,
                paramName = options.paramName[0];
            options.headers = options.headers || {};
            if (options.contentRange) {
                options.headers['Content-Range'] = options.contentRange;
            }
            if (!multipart) {
                options.headers['Content-Disposition'] = 'attachment; filename="' +
                    encodeURI(file.name) + '"';
                options.contentType = file.type;
                options.data = options.blob || file;
            } else if ($.support.xhrFormDataFileUpload) {
                if (options.postMessage) {
                    // window.postMessage does not allow sending FormData
                    // objects, so we just add the File/Blob objects to
                    // the formData array and let the postMessage window
                    // create the FormData object out of this array:
                    formData = this._getFormData(options);
                    if (options.blob) {
                        formData.push({
                            name: paramName,
                            value: options.blob
                        });
                    } else {
                        $.each(options.files, function (index, file) {
                            formData.push({
                                name: options.paramName[index] || paramName,
                                value: file
                            });
                        });
                    }
                } else {
                    if (that._isInstanceOf('FormData', options.formData)) {
                        formData = options.formData;
                    } else {
                        formData = new FormData();
                        $.each(this._getFormData(options), function (index, field) {
                            formData.append(field.name, field.value);
                        });
                    }
                    if (options.blob) {
                        options.headers['Content-Disposition'] = 'attachment; filename="' +
                            encodeURI(file.name) + '"';
                        formData.append(paramName, options.blob, file.name);
                    } else {
                        $.each(options.files, function (index, file) {
                            // This check allows the tests to run with
                            // dummy objects:
                            if (that._isInstanceOf('File', file) ||
                                    that._isInstanceOf('Blob', file)) {
                                formData.append(
                                    options.paramName[index] || paramName,
                                    file,
                                    file.name
                                );
                            }
                        });
                    }
                }
                options.data = formData;
            }
            // Blob reference is not needed anymore, free memory:
            options.blob = null;
        },

        _initIframeSettings: function (options) {
            // Setting the dataType to iframe enables the iframe transport:
            options.dataType = 'iframe ' + (options.dataType || '');
            // The iframe transport accepts a serialized array as form data:
            options.formData = this._getFormData(options);
            // Add redirect url to form data on cross-domain uploads:
            if (options.redirect && $('<a></a>').prop('href', options.url)
                    .prop('host') !== location.host) {
                options.formData.push({
                    name: options.redirectParamName || 'redirect',
                    value: options.redirect
                });
            }
        },

        _initDataSettings: function (options) {
            if (this._isXHRUpload(options)) {
                if (!this._chunkedUpload(options, true)) {
                    if (!options.data) {
                        this._initXHRData(options);
                    }
                    this._initProgressListener(options);
                }
                if (options.postMessage) {
                    // Setting the dataType to postmessage enables the
                    // postMessage transport:
                    options.dataType = 'postmessage ' + (options.dataType || '');
                }
            } else {
                this._initIframeSettings(options);
            }
        },

        _getParamName: function (options) {
            var fileInput = $(options.fileInput),
                paramName = options.paramName;
            if (!paramName) {
                paramName = [];
                fileInput.each(function () {
                    var input = $(this),
                        name = input.prop('name') || 'files[]',
                        i = (input.prop('files') || [1]).length;
                    while (i) {
                        paramName.push(name);
                        i -= 1;
                    }
                });
                if (!paramName.length) {
                    paramName = [fileInput.prop('name') || 'files[]'];
                }
            } else if (!$.isArray(paramName)) {
                paramName = [paramName];
            }
            return paramName;
        },

        _initFormSettings: function (options) {
            // Retrieve missing options from the input field and the
            // associated form, if available:
            if (!options.form || !options.form.length) {
                options.form = $(options.fileInput.prop('form'));
                // If the given file input doesn't have an associated form,
                // use the default widget file input's form:
                if (!options.form.length) {
                    options.form = $(this.options.fileInput.prop('form'));
                }
            }
            options.paramName = this._getParamName(options);
            if (!options.url) {
                options.url = options.form.prop('action') || location.href;
            }
            // The HTTP request method must be "POST" or "PUT":
            options.type = (options.type || options.form.prop('method') || '')
                .toUpperCase();
            if (options.type !== 'POST' && options.type !== 'PUT' &&
                    options.type !== 'PATCH') {
                options.type = 'POST';
            }
            if (!options.formAcceptCharset) {
                options.formAcceptCharset = options.form.attr('accept-charset');
            }
        },

        _getAJAXSettings: function (data) {
            var options = $.extend({}, this.options, data);
            this._initFormSettings(options);
            this._initDataSettings(options);
            return options;
        },

        // jQuery 1.6 doesn't provide .state(),
        // while jQuery 1.8+ removed .isRejected() and .isResolved():
        _getDeferredState: function (deferred) {
            if (deferred.state) {
                return deferred.state();
            }
            if (deferred.isResolved()) {
                return 'resolved';
            }
            if (deferred.isRejected()) {
                return 'rejected';
            }
            return 'pending';
        },

        // Maps jqXHR callbacks to the equivalent
        // methods of the given Promise object:
        _enhancePromise: function (promise) {
            promise.success = promise.done;
            promise.error = promise.fail;
            promise.complete = promise.always;
            return promise;
        },

        // Creates and returns a Promise object enhanced with
        // the jqXHR methods abort, success, error and complete:
        _getXHRPromise: function (resolveOrReject, context, args) {
            var dfd = $.Deferred(),
                promise = dfd.promise();
            context = context || this.options.context || promise;
            if (resolveOrReject === true) {
                dfd.resolveWith(context, args);
            } else if (resolveOrReject === false) {
                dfd.rejectWith(context, args);
            }
            promise.abort = dfd.promise;
            return this._enhancePromise(promise);
        },

        // Adds convenience methods to the callback arguments:
        _addConvenienceMethods: function (e, data) {
            var that = this;
            data.submit = function () {
                if (this.state() !== 'pending') {
                    data.jqXHR = this.jqXHR =
                        (that._trigger('submit', e, this) !== false) &&
                        that._onSend(e, this);
                }
                return this.jqXHR || that._getXHRPromise();
            };
            data.abort = function () {
                if (this.jqXHR) {
                    return this.jqXHR.abort();
                }
                return that._getXHRPromise();
            };
            data.state = function () {
                if (this.jqXHR) {
                    return that._getDeferredState(this.jqXHR);
                }
            };
            data.progress = function () {
                return this._progress;
            };
            data.response = function () {
                return this._response;
            };
        },

        // Parses the Range header from the server response
        // and returns the uploaded bytes:
        _getUploadedBytes: function (jqXHR) {
            var range = jqXHR.getResponseHeader('Range'),
                parts = range && range.split('-'),
                upperBytesPos = parts && parts.length > 1 &&
                    parseInt(parts[1], 10);
            return upperBytesPos && upperBytesPos + 1;
        },

        // Uploads a file in multiple, sequential requests
        // by splitting the file up in multiple blob chunks.
        // If the second parameter is true, only tests if the file
        // should be uploaded in chunks, but does not invoke any
        // upload requests:
        _chunkedUpload: function (options, testOnly) {
            var that = this,
                file = options.files[0],
                fs = file.size,
                ub = options.uploadedBytes = options.uploadedBytes || 0,
                mcs = options.maxChunkSize || fs,
                slice = file.slice || file.webkitSlice || file.mozSlice,
                dfd = $.Deferred(),
                promise = dfd.promise(),
                jqXHR,
                upload;
            if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
                    options.data) {
                return false;
            }
            if (testOnly) {
                return true;
            }
            if (ub >= fs) {
                file.error = 'Uploaded bytes exceed file size';
                return this._getXHRPromise(
                    false,
                    options.context,
                    [null, 'error', file.error]
                );
            }
            // The chunk upload method:
            upload = function () {
                // Clone the options object for each chunk upload:
                var o = $.extend({}, options),
                    currentLoaded = o._progress.loaded;
                o.blob = slice.call(
                    file,
                    ub,
                    ub + mcs,
                    file.type
                );
                // Store the current chunk size, as the blob itself
                // will be dereferenced after data processing:
                o.chunkSize = o.blob.size;
                // Expose the chunk bytes position range:
                o.contentRange = 'bytes ' + ub + '-' +
                    (ub + o.chunkSize - 1) + '/' + fs;
                // Process the upload data (the blob and potential form data):
                that._initXHRData(o);
                // Add progress listeners for this chunk upload:
                that._initProgressListener(o);
                jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) ||
                        that._getXHRPromise(false, o.context))
                    .done(function (result, textStatus, jqXHR) {
                        ub = that._getUploadedBytes(jqXHR) ||
                            (ub + o.chunkSize);
                        // Create a progress event if no final progress event
                        // with loaded equaling total has been triggered
                        // for this chunk:
                        if (o._progress.loaded === currentLoaded) {
                            that._onProgress($.Event('progress', {
                                lengthComputable: true,
                                loaded: ub - o.uploadedBytes,
                                total: ub - o.uploadedBytes
                            }), o);
                        }
                        options.uploadedBytes = o.uploadedBytes = ub;
                        o.result = result;
                        o.textStatus = textStatus;
                        o.jqXHR = jqXHR;
                        that._trigger('chunkdone', null, o);
                        that._trigger('chunkalways', null, o);
                        if (ub < fs) {
                            // File upload not yet complete,
                            // continue with the next chunk:
                            upload();
                        } else {
                            dfd.resolveWith(
                                o.context,
                                [result, textStatus, jqXHR]
                            );
                        }
                    })
                    .fail(function (jqXHR, textStatus, errorThrown) {
                        o.jqXHR = jqXHR;
                        o.textStatus = textStatus;
                        o.errorThrown = errorThrown;
                        that._trigger('chunkfail', null, o);
                        that._trigger('chunkalways', null, o);
                        dfd.rejectWith(
                            o.context,
                            [jqXHR, textStatus, errorThrown]
                        );
                    });
            };
            this._enhancePromise(promise);
            promise.abort = function () {
                return jqXHR.abort();
            };
            upload();
            return promise;
        },

        _beforeSend: function (e, data) {
            if (this._active === 0) {
                // the start callback is triggered when an upload starts
                // and no other uploads are currently running,
                // equivalent to the global ajaxStart event:
                this._trigger('start');
                // Set timer for global bitrate progress calculation:
                this._bitrateTimer = new this._BitrateTimer();
                // Reset the global progress values:
                this._progress.loaded = this._progress.total = 0;
                this._progress.bitrate = 0;
            }
            // Make sure the container objects for the .response() and
            // .progress() methods on the data object are available
            // and reset to their initial state:
            this._initResponseObject(data);
            this._initProgressObject(data);
            data._progress.loaded = data.loaded = data.uploadedBytes || 0;
            data._progress.total = data.total = this._getTotal(data.files) || 1;
            data._progress.bitrate = data.bitrate = 0;
            this._active += 1;
            // Initialize the global progress values:
            this._progress.loaded += data.loaded;
            this._progress.total += data.total;
        },

        _onDone: function (result, textStatus, jqXHR, options) {
            var total = options._progress.total,
                response = options._response;
            if (options._progress.loaded < total) {
                // Create a progress event if no final progress event
                // with loaded equaling total has been triggered:
                this._onProgress($.Event('progress', {
                    lengthComputable: true,
                    loaded: total,
                    total: total
                }), options);
            }
            response.result = options.result = result;
            response.textStatus = options.textStatus = textStatus;
            response.jqXHR = options.jqXHR = jqXHR;
            this._trigger('done', null, options);
        },

        _onFail: function (jqXHR, textStatus, errorThrown, options) {
            var response = options._response;
            if (options.recalculateProgress) {
                // Remove the failed (error or abort) file upload from
                // the global progress calculation:
                this._progress.loaded -= options._progress.loaded;
                this._progress.total -= options._progress.total;
            }
            response.jqXHR = options.jqXHR = jqXHR;
            response.textStatus = options.textStatus = textStatus;
            response.errorThrown = options.errorThrown = errorThrown;
            this._trigger('fail', null, options);
        },

        _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
            // jqXHRorResult, textStatus and jqXHRorError are added to the
            // options object via done and fail callbacks
            this._trigger('always', null, options);
        },

        _onSend: function (e, data) {
            if (!data.submit) {
                this._addConvenienceMethods(e, data);
            }
            var that = this,
                jqXHR,
                aborted,
                slot,
                pipe,
                options = that._getAJAXSettings(data),
                send = function () {
                    that._sending += 1;
                    // Set timer for bitrate progress calculation:
                    options._bitrateTimer = new that._BitrateTimer();
                    jqXHR = jqXHR || (
                        ((aborted || that._trigger('send', e, options) === false) &&
                        that._getXHRPromise(false, options.context, aborted)) ||
                        that._chunkedUpload(options) || $.ajax(options)
                    ).done(function (result, textStatus, jqXHR) {
                        that._onDone(result, textStatus, jqXHR, options);
                    }).fail(function (jqXHR, textStatus, errorThrown) {
                        that._onFail(jqXHR, textStatus, errorThrown, options);
                    }).always(function (jqXHRorResult, textStatus, jqXHRorError) {
                        that._onAlways(
                            jqXHRorResult,
                            textStatus,
                            jqXHRorError,
                            options
                        );
                        that._sending -= 1;
                        that._active -= 1;
                        if (options.limitConcurrentUploads &&
                                options.limitConcurrentUploads > that._sending) {
                            // Start the next queued upload,
                            // that has not been aborted:
                            var nextSlot = that._slots.shift();
                            while (nextSlot) {
                                if (that._getDeferredState(nextSlot) === 'pending') {
                                    nextSlot.resolve();
                                    break;
                                }
                                nextSlot = that._slots.shift();
                            }
                        }
                        if (that._active === 0) {
                            // The stop callback is triggered when all uploads have
                            // been completed, equivalent to the global ajaxStop event:
                            that._trigger('stop');
                        }
                    });
                    return jqXHR;
                };
            this._beforeSend(e, options);
            if (this.options.sequentialUploads ||
                    (this.options.limitConcurrentUploads &&
                    this.options.limitConcurrentUploads <= this._sending)) {
                if (this.options.limitConcurrentUploads > 1) {
                    slot = $.Deferred();
                    this._slots.push(slot);
                    pipe = slot.pipe(send);
                } else {
                    pipe = (this._sequence = this._sequence.pipe(send, send));
                }
                // Return the piped Promise object, enhanced with an abort method,
                // which is delegated to the jqXHR object of the current upload,
                // and jqXHR callbacks mapped to the equivalent Promise methods:
                pipe.abort = function () {
                    aborted = [undefined, 'abort', 'abort'];
                    if (!jqXHR) {
                        if (slot) {
                            slot.rejectWith(options.context, aborted);
                        }
                        return send();
                    }
                    return jqXHR.abort();
                };
                return this._enhancePromise(pipe);
            }
            return send();
        },

        _onAdd: function (e, data) {
            var that = this,
                result = true,
                options = $.extend({}, this.options, data),
                limit = options.limitMultiFileUploads,
                paramName = this._getParamName(options),
                paramNameSet,
                paramNameSlice,
                fileSet,
                i;
            if (!(options.singleFileUploads || limit) ||
                    !this._isXHRUpload(options)) {
                fileSet = [data.files];
                paramNameSet = [paramName];
            } else if (!options.singleFileUploads && limit) {
                fileSet = [];
                paramNameSet = [];
                for (i = 0; i < data.files.length; i += limit) {
                    fileSet.push(data.files.slice(i, i + limit));
                    paramNameSlice = paramName.slice(i, i + limit);
                    if (!paramNameSlice.length) {
                        paramNameSlice = paramName;
                    }
                    paramNameSet.push(paramNameSlice);
                }
            } else {
                paramNameSet = paramName;
            }
            data.originalFiles = data.files;
            $.each(fileSet || data.files, function (index, element) {
                var newData = $.extend({}, data);
                newData.files = fileSet ? element : [element];
                newData.paramName = paramNameSet[index];
                that._initResponseObject(newData);
                that._initProgressObject(newData);
                that._addConvenienceMethods(e, newData);
                result = that._trigger('add', e, newData);
                return result;
            });
            return result;
        },

        _replaceFileInput: function (input) {
            var inputClone = input.clone(true);
            $('<form></form>').append(inputClone)[0].reset();
            // Detaching allows to insert the fileInput on another form
            // without loosing the file input value:
            input.after(inputClone).detach();
            // Avoid memory leaks with the detached file input:
            $.cleanData(input.unbind('remove'));
            // Replace the original file input element in the fileInput
            // elements set with the clone, which has been copied including
            // event handlers:
            this.options.fileInput = this.options.fileInput.map(function (i, el) {
                if (el === input[0]) {
                    return inputClone[0];
                }
                return el;
            });
            // If the widget has been initialized on the file input itself,
            // override this.element with the file input clone:
            if (input[0] === this.element[0]) {
                this.element = inputClone;
            }
        },

        _handleFileTreeEntry: function (entry, path) {
            var that = this,
                dfd = $.Deferred(),
                errorHandler = function (e) {
                    if (e && !e.entry) {
                        e.entry = entry;
                    }
                    // Since $.when returns immediately if one
                    // Deferred is rejected, we use resolve instead.
                    // This allows valid files and invalid items
                    // to be returned together in one set:
                    dfd.resolve([e]);
                },
                dirReader;
            path = path || '';
            if (entry.isFile) {
                if (entry._file) {
                    // Workaround for Chrome bug #149735
                    entry._file.relativePath = path;
                    dfd.resolve(entry._file);
                } else {
                    entry.file(function (file) {
                        file.relativePath = path;
                        dfd.resolve(file);
                    }, errorHandler);
                }
            } else if (entry.isDirectory) {
                dirReader = entry.createReader();
                dirReader.readEntries(function (entries) {
                    that._handleFileTreeEntries(
                        entries,
                        path + entry.name + '/'
                    ).done(function (files) {
                        dfd.resolve(files);
                    }).fail(errorHandler);
                }, errorHandler);
            } else {
                // Return an empy list for file system items
                // other than files or directories:
                dfd.resolve([]);
            }
            return dfd.promise();
        },

        _handleFileTreeEntries: function (entries, path) {
            var that = this;
            return $.when.apply(
                $,
                $.map(entries, function (entry) {
                    return that._handleFileTreeEntry(entry, path);
                })
            ).pipe(function () {
                return Array.prototype.concat.apply(
                    [],
                    arguments
                );
            });
        },

        _getDroppedFiles: function (dataTransfer) {
            dataTransfer = dataTransfer || {};
            var items = dataTransfer.items;
            if (items && items.length && (items[0].webkitGetAsEntry ||
                    items[0].getAsEntry)) {
                return this._handleFileTreeEntries(
                    $.map(items, function (item) {
                        var entry;
                        if (item.webkitGetAsEntry) {
                            entry = item.webkitGetAsEntry();
                            if (entry) {
                                // Workaround for Chrome bug #149735:
                                entry._file = item.getAsFile();
                            }
                            return entry;
                        }
                        return item.getAsEntry();
                    })
                );
            }
            return $.Deferred().resolve(
                $.makeArray(dataTransfer.files)
            ).promise();
        },

        _getSingleFileInputFiles: function (fileInput) {
            fileInput = $(fileInput);
            var entries = fileInput.prop('webkitEntries') ||
                    fileInput.prop('entries'),
                files,
                value;
            if (entries && entries.length) {
                return this._handleFileTreeEntries(entries);
            }
            files = $.makeArray(fileInput.prop('files'));
            if (!files.length) {
                value = fileInput.prop('value');
                if (!value) {
                    return $.Deferred().resolve([]).promise();
                }
                // If the files property is not available, the browser does not
                // support the File API and we add a pseudo File object with
                // the input value as name with path information removed:
                files = [{name: value.replace(/^.*\\/, '')}];
            } else if (files[0].name === undefined && files[0].fileName) {
                // File normalization for Safari 4 and Firefox 3:
                $.each(files, function (index, file) {
                    file.name = file.fileName;
                    file.size = file.fileSize;
                });
            }
            return $.Deferred().resolve(files).promise();
        },

        _getFileInputFiles: function (fileInput) {
            if (!(fileInput instanceof $) || fileInput.length === 1) {
                return this._getSingleFileInputFiles(fileInput);
            }
            return $.when.apply(
                $,
                $.map(fileInput, this._getSingleFileInputFiles)
            ).pipe(function () {
                return Array.prototype.concat.apply(
                    [],
                    arguments
                );
            });
        },

        _onChange: function (e) {
            var that = this,
                data = {
                    fileInput: $(e.target),
                    form: $(e.target.form)
                };
            this._getFileInputFiles(data.fileInput).always(function (files) {
                data.files = files;
                if (that.options.replaceFileInput) {
                    that._replaceFileInput(data.fileInput);
                }
                if (that._trigger('change', e, data) !== false) {
                    that._onAdd(e, data);
                }
            });
        },

        _onPaste: function (e) {
            var items = e.originalEvent && e.originalEvent.clipboardData &&
                    e.originalEvent.clipboardData.items,
                data = {files: []};
            if (items && items.length) {
                $.each(items, function (index, item) {
                    var file = item.getAsFile && item.getAsFile();
                    if (file) {
                        data.files.push(file);
                    }
                });
                if (this._trigger('paste', e, data) === false ||
                        this._onAdd(e, data) === false) {
                    return false;
                }
            }
        },

        _onDrop: function (e) {
            var that = this,
                dataTransfer = e.dataTransfer = e.originalEvent &&
                    e.originalEvent.dataTransfer,
                data = {};
            if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
                e.preventDefault();
                this._getDroppedFiles(dataTransfer).always(function (files) {
                    data.files = files;
                    if (that._trigger('drop', e, data) !== false) {
                        that._onAdd(e, data);
                    }
                });
            }
        },

        _onDragOver: function (e) {
            var dataTransfer = e.dataTransfer = e.originalEvent &&
                e.originalEvent.dataTransfer;
            if (dataTransfer) {
                if (this._trigger('dragover', e) === false) {
                    return false;
                }
                if ($.inArray('Files', dataTransfer.types) !== -1) {
                    dataTransfer.dropEffect = 'copy';
                    e.preventDefault();
                }
            }
        },

        _initEventHandlers: function () {
            if (this._isXHRUpload(this.options)) {
                this._on(this.options.dropZone, {
                    dragover: this._onDragOver,
                    drop: this._onDrop
                });
                this._on(this.options.pasteZone, {
                    paste: this._onPaste
                });
            }
            this._on(this.options.fileInput, {
                change: this._onChange
            });
        },

        _destroyEventHandlers: function () {
            this._off(this.options.dropZone, 'dragover drop');
            this._off(this.options.pasteZone, 'paste');
            this._off(this.options.fileInput, 'change');
        },

        _setOption: function (key, value) {
            var refresh = $.inArray(key, this._refreshOptionsList) !== -1;
            if (refresh) {
                this._destroyEventHandlers();
            }
            this._super(key, value);
            if (refresh) {
                this._initSpecialOptions();
                this._initEventHandlers();
            }
        },

        _initSpecialOptions: function () {
            var options = this.options;
            if (options.fileInput === undefined) {
                options.fileInput = this.element.is('input[type="file"]') ?
                        this.element : this.element.find('input[type="file"]');
            } else if (!(options.fileInput instanceof $)) {
                options.fileInput = $(options.fileInput);
            }
            if (!(options.dropZone instanceof $)) {
                options.dropZone = $(options.dropZone);
            }
            if (!(options.pasteZone instanceof $)) {
                options.pasteZone = $(options.pasteZone);
            }
        },

        _create: function () {
            var options = this.options;
            // Initialize options set via HTML5 data-attributes:
            $.extend(options, $(this.element[0].cloneNode(false)).data());
            this._initSpecialOptions();
            this._slots = [];
            this._sequence = this._getXHRPromise(true);
            this._sending = this._active = 0;
            this._initProgressObject(this);
            this._initEventHandlers();
        },

        // This method is exposed to the widget API and allows to query
        // the number of active uploads:
        active: function () {
            return this._active;
        },

        // This method is exposed to the widget API and allows to query
        // the widget upload progress.
        // It returns an object with loaded, total and bitrate properties
        // for the running uploads:
        progress: function () {
            return this._progress;
        },

        // This method is exposed to the widget API and allows adding files
        // using the fileupload API. The data parameter accepts an object which
        // must have a files property and can contain additional options:
        // .fileupload('add', {files: filesList});
        add: function (data) {
            var that = this;
            if (!data || this.options.disabled) {
                return;
            }
            if (data.fileInput && !data.files) {
                this._getFileInputFiles(data.fileInput).always(function (files) {
                    data.files = files;
                    that._onAdd(null, data);
                });
            } else {
                data.files = $.makeArray(data.files);
                this._onAdd(null, data);
            }
        },

        // This method is exposed to the widget API and allows sending files
        // using the fileupload API. The data parameter accepts an object which
        // must have a files or fileInput property and can contain additional options:
        // .fileupload('send', {files: filesList});
        // The method returns a Promise object for the file upload call.
        send: function (data) {
            if (data && !this.options.disabled) {
                if (data.fileInput && !data.files) {
                    var that = this,
                        dfd = $.Deferred(),
                        promise = dfd.promise(),
                        jqXHR,
                        aborted;
                    promise.abort = function () {
                        aborted = true;
                        if (jqXHR) {
                            return jqXHR.abort();
                        }
                        dfd.reject(null, 'abort', 'abort');
                        return promise;
                    };
                    this._getFileInputFiles(data.fileInput).always(
                        function (files) {
                            if (aborted) {
                                return;
                            }
                            data.files = files;
                            jqXHR = that._onSend(null, data).then(
                                function (result, textStatus, jqXHR) {
                                    dfd.resolve(result, textStatus, jqXHR);
                                },
                                function (jqXHR, textStatus, errorThrown) {
                                    dfd.reject(jqXHR, textStatus, errorThrown);
                                }
                            );
                        }
                    );
                    return this._enhancePromise(promise);
                }
                data.files = $.makeArray(data.files);
                if (data.files.length) {
                    return this._onSend(null, data);
                }
            }
            return this._getXHRPromise(false, data && data.context);
        }

    });

}));
;
// Spectrum Colorpicker v1.1.0
// https://github.com/bgrins/spectrum
// Author: Brian Grinstead
// License: MIT

(function (window, $, undefined) {
    var defaultOpts = {

        // Callbacks
        beforeShow: noop,
        move: noop,
        change: noop,
        show: noop,
        hide: noop,

        // Options
        color: false,
        flat: false,
        showInput: false,
        showButtons: true,
        clickoutFiresChange: false,
        showInitial: false,
        showPalette: false,
        showPaletteOnly: false,
        showSelectionPalette: true,
        localStorageKey: false,
        appendTo: "body",
        maxSelectionSize: 7,
        cancelText: "cancel",
        chooseText: "choose",
        preferredFormat: false,
        className: "",
        showAlpha: false,
        theme: "sp-light",
        palette: ['fff', '000'],
        selectionPalette: [],
        disabled: false
    },
    spectrums = [],
    IE = !!/msie/i.exec( window.navigator.userAgent ),
    rgbaSupport = (function() {
        function contains( str, substr ) {
            return !!~('' + str).indexOf(substr);
        }

        var elem = document.createElement('div');
        var style = elem.style;
        style.cssText = 'background-color:rgba(0,0,0,.5)';
        return contains(style.backgroundColor, 'rgba') || contains(style.backgroundColor, 'hsla');
    })(),
    replaceInput = [
        "<div class='sp-replacer'>",
            "<div class='sp-preview'><div class='sp-preview-inner'></div></div>",
            "<div class='sp-dd'>&#9660;</div>",
        "</div>"
    ].join(''),
    markup = (function () {

        // IE does not support gradients with multiple stops, so we need to simulate
        //  that for the rainbow slider with 8 divs that each have a single gradient
        var gradientFix = "";
        if (IE) {
            for (var i = 1; i <= 6; i++) {
                gradientFix += "<div class='sp-" + i + "'></div>";
            }
        }

        return [
            "<div class='sp-container sp-hidden'>",
                "<div class='sp-palette-container'>",
                    "<div class='sp-palette sp-thumb sp-cf'></div>",
                "</div>",
                "<div class='sp-picker-container'>",
                    "<div class='sp-top sp-cf'>",
                        "<div class='sp-fill'></div>",
                        "<div class='sp-top-inner'>",
                            "<div class='sp-color'>",
                                "<div class='sp-sat'>",
                                    "<div class='sp-val'>",
                                        "<div class='sp-dragger'></div>",
                                    "</div>",
                                "</div>",
                            "</div>",
                            "<div class='sp-hue'>",
                                "<div class='sp-slider'></div>",
                                gradientFix,
                            "</div>",
                        "</div>",
                        "<div class='sp-alpha'><div class='sp-alpha-inner'><div class='sp-alpha-handle'></div></div></div>",
                    "</div>",
                    "<div class='sp-input-container sp-cf'>",
                        "<input class='sp-input' type='text' spellcheck='false'  />",
                    "</div>",
                    "<div class='sp-initial sp-thumb sp-cf'></div>",
                    "<div class='sp-button-container sp-cf'>",
                        "<a class='sp-cancel' href='#'></a>",
                        "<button class='sp-choose'></button>",
                    "</div>",
                "</div>",
            "</div>"
        ].join("");
    })();

    function paletteTemplate (p, color, className) {
        var html = [];
        for (var i = 0; i < p.length; i++) {
            var tiny = tinycolor(p[i]);
            var c = tiny.toHsl().l < 0.5 ? "sp-thumb-el sp-thumb-dark" : "sp-thumb-el sp-thumb-light";
            c += (tinycolor.equals(color, p[i])) ? " sp-thumb-active" : "";

            var swatchStyle = rgbaSupport ? ("background-color:" + tiny.toRgbString()) : "filter:" + tiny.toFilter();
            html.push('<span title="' + tiny.toRgbString() + '" data-color="' + tiny.toRgbString() + '" class="' + c + '"><span class="sp-thumb-inner" style="' + swatchStyle + ';" /></span>');
        }
        return "<div class='sp-cf " + className + "'>" + html.join('') + "</div>";
    }

    function hideAll() {
        for (var i = 0; i < spectrums.length; i++) {
            if (spectrums[i]) {
                spectrums[i].hide();
            }
        }
    }

    function instanceOptions(o, callbackContext) {
        var opts = $.extend({}, defaultOpts, o);
        opts.callbacks = {
            'move': bind(opts.move, callbackContext),
            'change': bind(opts.change, callbackContext),
            'show': bind(opts.show, callbackContext),
            'hide': bind(opts.hide, callbackContext),
            'beforeShow': bind(opts.beforeShow, callbackContext)
        };

        return opts;
    }

    function spectrum(element, o) {

        var opts = instanceOptions(o, element),
            flat = opts.flat,
            showSelectionPalette = opts.showSelectionPalette,
            localStorageKey = opts.localStorageKey,
            theme = opts.theme,
            callbacks = opts.callbacks,
            resize = throttle(reflow, 10),
            visible = false,
            dragWidth = 0,
            dragHeight = 0,
            dragHelperHeight = 0,
            slideHeight = 0,
            slideWidth = 0,
            alphaWidth = 0,
            alphaSlideHelperWidth = 0,
            slideHelperHeight = 0,
            currentHue = 0,
            currentSaturation = 0,
            currentValue = 0,
            currentAlpha = 1,
            palette = opts.palette.slice(0),
            paletteArray = $.isArray(palette[0]) ? palette : [palette],
            selectionPalette = opts.selectionPalette.slice(0),
            maxSelectionSize = opts.maxSelectionSize,
            draggingClass = "sp-dragging";

        var doc = element.ownerDocument,
            body = doc.body,
            boundElement = $(element),
            disabled = false,
            container = $(markup, doc).addClass(theme),
            dragger = container.find(".sp-color"),
            dragHelper = container.find(".sp-dragger"),
            slider = container.find(".sp-hue"),
            slideHelper = container.find(".sp-slider"),
            alphaSliderInner = container.find(".sp-alpha-inner"),
            alphaSlider = container.find(".sp-alpha"),
            alphaSlideHelper = container.find(".sp-alpha-handle"),
            textInput = container.find(".sp-input"),
            paletteContainer = container.find(".sp-palette"),
            initialColorContainer = container.find(".sp-initial"),
            cancelButton = container.find(".sp-cancel"),
            chooseButton = container.find(".sp-choose"),
            isInput = boundElement.is("input"),
            shouldReplace = isInput && !flat,
            replacer = (shouldReplace) ? $(replaceInput).addClass(theme).addClass(opts.className) : $([]),
            offsetElement = (shouldReplace) ? replacer : boundElement,
            previewElement = replacer.find(".sp-preview-inner"),
            initialColor = opts.color || (isInput && boundElement.val()),
            colorOnShow = false,
            preferredFormat = opts.preferredFormat,
            currentPreferredFormat = preferredFormat,
            clickoutFiresChange = !opts.showButtons || opts.clickoutFiresChange;


        function applyOptions() {

            container.toggleClass("sp-flat", flat);
            container.toggleClass("sp-input-disabled", !opts.showInput);
            container.toggleClass("sp-alpha-enabled", opts.showAlpha);
            container.toggleClass("sp-buttons-disabled", !opts.showButtons || flat);
            container.toggleClass("sp-palette-disabled", !opts.showPalette);
            container.toggleClass("sp-palette-only", opts.showPaletteOnly);
            container.toggleClass("sp-initial-disabled", !opts.showInitial);
            container.addClass(opts.className);

            reflow();
        }

        function initialize() {

            if (IE) {
                container.find("*:not(input)").attr("unselectable", "on");
            }

            applyOptions();

            if (shouldReplace) {
                boundElement.after(replacer).hide();
            }

            if (flat) {
                boundElement.after(container).hide();
            }
            else {

                var appendTo = opts.appendTo === "parent" ? boundElement.parent() : $(opts.appendTo);
                if (appendTo.length !== 1) {
                    appendTo = $("body");
                }

                appendTo.append(container);
            }

            if (localStorageKey && window.localStorage) {

                // Migrate old palettes over to new format.  May want to remove this eventually.
                try {
                    var oldPalette = window.localStorage[localStorageKey].split(",#");
                    if (oldPalette.length > 1) {
                        delete window.localStorage[localStorageKey];
                        $.each(oldPalette, function(i, c) {
                             addColorToSelectionPalette(c);
                        });
                    }
                }
                catch(e) { }

                try {
                    selectionPalette = window.localStorage[localStorageKey].split(";");
                }
                catch (e) { }
            }

            offsetElement.bind("click.spectrum touchstart.spectrum", function (e) {
                if (!disabled) {
                    toggle();
                }

                e.stopPropagation();

                if (!$(e.target).is("input")) {
                    e.preventDefault();
                }
            });

            if(boundElement.is(":disabled") || (opts.disabled === true)) {
                disable();
            }

            // Prevent clicks from bubbling up to document.  This would cause it to be hidden.
            container.click(stopPropagation);

            // Handle user typed input
            textInput.change(setFromTextInput);
            textInput.bind("paste", function () {
                setTimeout(setFromTextInput, 1);
            });
            textInput.keydown(function (e) { if (e.keyCode == 13) { setFromTextInput(); } });

            cancelButton.text(opts.cancelText);
            cancelButton.bind("click.spectrum", function (e) {
                e.stopPropagation();
                e.preventDefault();
                hide("cancel");
            });

            chooseButton.text(opts.chooseText);
            chooseButton.bind("click.spectrum", function (e) {
                e.stopPropagation();
                e.preventDefault();

                if (isValid()) {
                    updateOriginalInput(true);
                    hide();
                }
            });

            draggable(alphaSlider, function (dragX, dragY, e) {
                currentAlpha = (dragX / alphaWidth);
                if (e.shiftKey) {
                    currentAlpha = Math.round(currentAlpha * 10) / 10;
                }

                move();
            });

            draggable(slider, function (dragX, dragY) {
                currentHue = parseFloat(dragY / slideHeight);
                move();
            }, dragStart, dragStop);

            draggable(dragger, function (dragX, dragY) {
                currentSaturation = parseFloat(dragX / dragWidth);
                currentValue = parseFloat((dragHeight - dragY) / dragHeight);
                move();
            }, dragStart, dragStop);

            if (!!initialColor) {
                set(initialColor);

                // In case color was black - update the preview UI and set the format
                // since the set function will not run (default color is black).
                updateUI();
                currentPreferredFormat = preferredFormat || tinycolor(initialColor).format;

                addColorToSelectionPalette(initialColor);
            }
            else {
                updateUI();
            }

            if (flat) {
                show();
            }

            function palletElementClick(e) {
                if (e.data && e.data.ignore) {
                    set($(this).data("color"));
                    move();
                }
                else {
                    set($(this).data("color"));
                    updateOriginalInput(true);
                    move();
                    hide();
                }

                return false;
            }

            var paletteEvent = IE ? "mousedown.spectrum" : "click.spectrum touchstart.spectrum";
            paletteContainer.delegate(".sp-thumb-el", paletteEvent, palletElementClick);
            initialColorContainer.delegate(".sp-thumb-el:nth-child(1)", paletteEvent, { ignore: true }, palletElementClick);
        }

        function addColorToSelectionPalette(color) {
            if (showSelectionPalette) {
                var colorRgb = tinycolor(color).toRgbString();
                if ($.inArray(colorRgb, selectionPalette) === -1) {
                    selectionPalette.push(colorRgb);
                    while(selectionPalette.length > maxSelectionSize) {
                        selectionPalette.shift();
                    }
                }

                if (localStorageKey && window.localStorage) {
                    try {
                        window.localStorage[localStorageKey] = selectionPalette.join(";");
                    }
                    catch(e) { }
                }
            }
        }

        function getUniqueSelectionPalette() {
            var unique = [];
            var p = selectionPalette;
            var paletteLookup = {};
            var rgb;

            if (opts.showPalette) {

                for (var i = 0; i < paletteArray.length; i++) {
                    for (var j = 0; j < paletteArray[i].length; j++) {
                        rgb = tinycolor(paletteArray[i][j]).toRgbString();
                        paletteLookup[rgb] = true;
                    }
                }

                for (i = 0; i < p.length; i++) {
                    rgb = tinycolor(p[i]).toRgbString();

                    if (!paletteLookup.hasOwnProperty(rgb)) {
                        unique.push(p[i]);
                        paletteLookup[rgb] = true;
                    }
                }
            }

            return unique.reverse().slice(0, opts.maxSelectionSize);
        }

        function drawPalette() {

            var currentColor = get();

            var html = $.map(paletteArray, function (palette, i) {
                return paletteTemplate(palette, currentColor, "sp-palette-row sp-palette-row-" + i);
            });

            if (selectionPalette) {
                html.push(paletteTemplate(getUniqueSelectionPalette(), currentColor, "sp-palette-row sp-palette-row-selection"));
            }

            paletteContainer.html(html.join(""));
        }

        function drawInitial() {
            if (opts.showInitial) {
                var initial = colorOnShow;
                var current = get();
                initialColorContainer.html(paletteTemplate([initial, current], current, "sp-palette-row-initial"));
            }
        }

        function dragStart() {
            if (dragHeight <= 0 || dragWidth <= 0 || slideHeight <= 0) {
                reflow();
            }
            container.addClass(draggingClass);
        }

        function dragStop() {
            container.removeClass(draggingClass);
        }

        function setFromTextInput() {
            var tiny = tinycolor(textInput.val());
            if (tiny.ok) {
                set(tiny);
            }
            else {
                textInput.addClass("sp-validation-error");
            }
        }

        function toggle() {
            if (visible) {
                hide();
            }
            else {
                show();
            }
        }

        function show() {
            var event = $.Event('beforeShow.spectrum');

            if (visible) {
                reflow();
                return;
            }

            boundElement.trigger(event, [ get() ]);

            if (callbacks.beforeShow(get()) === false || event.isDefaultPrevented()) {
                return;
            }

            hideAll();
            visible = true;

            $(doc).bind("click.spectrum", hide);
            $(window).bind("resize.spectrum", resize);
            replacer.addClass("sp-active");
            container.removeClass("sp-hidden");

            if (opts.showPalette) {
                drawPalette();
            }
            reflow();
            updateUI();

            colorOnShow = get();

            drawInitial();
            callbacks.show(colorOnShow);
            boundElement.trigger('show.spectrum', [ colorOnShow ]);
        }

        function hide(e) {

            // Return on right click
            if (e && e.type == "click" && e.button == 2) { return; }

            // Return if hiding is unnecessary
            if (!visible || flat) { return; }
            visible = false;

            $(doc).unbind("click.spectrum", hide);
            $(window).unbind("resize.spectrum", resize);

            replacer.removeClass("sp-active");
            container.addClass("sp-hidden");

            var colorHasChanged = !tinycolor.equals(get(), colorOnShow);

            if (colorHasChanged) {
                if (clickoutFiresChange && e !== "cancel") {
                    updateOriginalInput(true);
                }
                else {
                    revert();
                }
            }

            callbacks.hide(get());
            boundElement.trigger('hide.spectrum', [ get() ]);
        }

        function revert() {
            set(colorOnShow, true);
        }

        function set(color, ignoreFormatChange) {
            if (tinycolor.equals(color, get())) {
                return;
            }

            var newColor = tinycolor(color);
            var newHsv = newColor.toHsv();

            currentHue = newHsv.h;
            currentSaturation = newHsv.s;
            currentValue = newHsv.v;
            currentAlpha = newHsv.a;

            updateUI();

            if (newColor.ok && !ignoreFormatChange) {
                currentPreferredFormat = preferredFormat || newColor.format;
            }
        }

        function get(opts) {
            opts = opts || { };
            return tinycolor.fromRatio({
                h: currentHue,
                s: currentSaturation,
                v: currentValue,
                a: Math.round(currentAlpha * 100) / 100
            }, { format: opts.format || currentPreferredFormat });
        }

        function isValid() {
            return !textInput.hasClass("sp-validation-error");
        }

        function move() {
            updateUI();

            callbacks.move(get());
            boundElement.trigger('move.spectrum', [ get() ]);
        }

        function updateUI() {

            textInput.removeClass("sp-validation-error");

            updateHelperLocations();

            // Update dragger background color (gradients take care of saturation and value).
            var flatColor = tinycolor.fromRatio({ h: currentHue, s: 1, v: 1 });
            dragger.css("background-color", flatColor.toHexString());

            // Get a format that alpha will be included in (hex and names ignore alpha)
            var format = currentPreferredFormat;
            if (currentAlpha < 1) {
                if (format === "hex" || format === "hex3" || format === "hex6" || format === "name") {
                    format = "rgb";
                }
            }

            var realColor = get({ format: format }),
                realHex = realColor.toHexString(),
                realRgb = realColor.toRgbString();

            // Update the replaced elements background color (with actual selected color)
            if (rgbaSupport || realColor.alpha === 1) {
                previewElement.css("background-color", realRgb);
            }
            else {
                previewElement.css("background-color", "transparent");
                previewElement.css("filter", realColor.toFilter());
            }

            if (opts.showAlpha) {
                var rgb = realColor.toRgb();
                rgb.a = 0;
                var realAlpha = tinycolor(rgb).toRgbString();
                var gradient = "linear-gradient(left, " + realAlpha + ", " + realHex + ")";

                if (IE) {
                    alphaSliderInner.css("filter", tinycolor(realAlpha).toFilter({ gradientType: 1 }, realHex));
                }
                else {
                    alphaSliderInner.css("background", "-webkit-" + gradient);
                    alphaSliderInner.css("background", "-moz-" + gradient);
                    alphaSliderInner.css("background", "-ms-" + gradient);
                    alphaSliderInner.css("background", gradient);
                }
            }


            // Update the text entry input as it changes happen
            if (opts.showInput) {
                textInput.val(realColor.toString(format));
            }

            if (opts.showPalette) {
                drawPalette();
            }

            drawInitial();
        }

        function updateHelperLocations() {
            var s = currentSaturation;
            var v = currentValue;

            // Where to show the little circle in that displays your current selected color
            var dragX = s * dragWidth;
            var dragY = dragHeight - (v * dragHeight);
            dragX = Math.max(
                -dragHelperHeight,
                Math.min(dragWidth - dragHelperHeight, dragX - dragHelperHeight)
            );
            dragY = Math.max(
                -dragHelperHeight,
                Math.min(dragHeight - dragHelperHeight, dragY - dragHelperHeight)
            );
            dragHelper.css({
                "top": dragY,
                "left": dragX
            });

            var alphaX = currentAlpha * alphaWidth;
            alphaSlideHelper.css({
                "left": alphaX - (alphaSlideHelperWidth / 2)
            });

            // Where to show the bar that displays your current selected hue
            var slideY = (currentHue) * slideHeight;
            slideHelper.css({
                "top": slideY - slideHelperHeight
            });
        }

        function updateOriginalInput(fireCallback) {
            var color = get();

            if (isInput) {
                boundElement.val(color.toString(currentPreferredFormat)).change();
            }

            var hasChanged = !tinycolor.equals(color, colorOnShow);
            colorOnShow = color;

            // Update the selection palette with the current color
            addColorToSelectionPalette(color);
            if (fireCallback && hasChanged) {
                callbacks.change(color);
                boundElement.trigger('change.spectrum', [ color ]);
            }
        }

        function reflow() {
            dragWidth = dragger.width();
            dragHeight = dragger.height();
            dragHelperHeight = dragHelper.height();
            slideWidth = slider.width();
            slideHeight = slider.height();
            slideHelperHeight = slideHelper.height();
            alphaWidth = alphaSlider.width();
            alphaSlideHelperWidth = alphaSlideHelper.width();

            if (!flat) {
                container.css("position", "absolute");
                container.offset(getOffset(container, offsetElement));
            }

            updateHelperLocations();
        }

        function destroy() {
            boundElement.show();
            offsetElement.unbind("click.spectrum touchstart.spectrum");
            container.remove();
            replacer.remove();
            spectrums[spect.id] = null;
        }

        function option(optionName, optionValue) {
            if (optionName === undefined) {
                return $.extend({}, opts);
            }
            if (optionValue === undefined) {
                return opts[optionName];
            }

            opts[optionName] = optionValue;
            applyOptions();
        }

        function enable() {
            disabled = false;
            boundElement.attr("disabled", false);
            offsetElement.removeClass("sp-disabled");
        }

        function disable() {
            hide();
            disabled = true;
            boundElement.attr("disabled", true);
            offsetElement.addClass("sp-disabled");
        }

        initialize();

        var spect = {
            show: show,
            hide: hide,
            toggle: toggle,
            reflow: reflow,
            option: option,
            enable: enable,
            disable: disable,
            set: function (c) {
                set(c);
                updateOriginalInput();
            },
            get: get,
            destroy: destroy,
            container: container
        };

        spect.id = spectrums.push(spect) - 1;

        return spect;
    }

    /**
    * checkOffset - get the offset below/above and left/right element depending on screen position
    * Thanks https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js
    */
    function getOffset(picker, input) {
        var extraY = 0;
        var dpWidth = picker.outerWidth();
        var dpHeight = picker.outerHeight();
        var inputHeight = input.outerHeight();
        var doc = picker[0].ownerDocument;
        var docElem = doc.documentElement;
        var viewWidth = docElem.clientWidth + $(doc).scrollLeft();
        var viewHeight = docElem.clientHeight + $(doc).scrollTop();
        var offset = input.offset();
        offset.top += inputHeight;

        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 - extraY) : extraY));

        return offset;
    }

    /**
    * noop - do nothing
    */
    function noop() {

    }

    /**
    * stopPropagation - makes the code only doing this a little easier to read in line
    */
    function stopPropagation(e) {
        e.stopPropagation();
    }

    /**
    * Create a function bound to a given object
    * Thanks to underscore.js
    */
    function bind(func, obj) {
        var slice = Array.prototype.slice;
        var args = slice.call(arguments, 2);
        return function () {
            return func.apply(obj, args.concat(slice.call(arguments)));
        };
    }

    /**
    * Lightweight drag helper.  Handles containment within the element, so that
    * when dragging, the x is within [0,element.width] and y is within [0,element.height]
    */
    function draggable(element, onmove, onstart, onstop) {
        onmove = onmove || function () { };
        onstart = onstart || function () { };
        onstop = onstop || function () { };
        var doc = element.ownerDocument || document;
        var dragging = false;
        var offset = {};
        var maxHeight = 0;
        var maxWidth = 0;
        var hasTouch = ('ontouchstart' in window);

        var duringDragEvents = {};
        duringDragEvents["selectstart"] = prevent;
        duringDragEvents["dragstart"] = prevent;
        duringDragEvents[(hasTouch ? "touchmove" : "mousemove")] = move;
        duringDragEvents[(hasTouch ? "touchend" : "mouseup")] = stop;

        function prevent(e) {
            if (e.stopPropagation) {
                e.stopPropagation();
            }
            if (e.preventDefault) {
                e.preventDefault();
            }
            e.returnValue = false;
        }

        function move(e) {
            if (dragging) {
                // Mouseup happened outside of window
                if (IE && document.documentMode < 9 && !e.button) {
                    return stop();
                }

                var touches = e.originalEvent.touches;
                var pageX = touches ? touches[0].pageX : e.pageX;
                var pageY = touches ? touches[0].pageY : e.pageY;

                var dragX = Math.max(0, Math.min(pageX - offset.left, maxWidth));
                var dragY = Math.max(0, Math.min(pageY - offset.top, maxHeight));

                if (hasTouch) {
                    // Stop scrolling in iOS
                    prevent(e);
                }

                onmove.apply(element, [dragX, dragY, e]);
            }
        }
        function start(e) {
            var rightclick = (e.which) ? (e.which == 3) : (e.button == 2);
            var touches = e.originalEvent.touches;

            if (!rightclick && !dragging) {
                if (onstart.apply(element, arguments) !== false) {
                    dragging = true;
                    maxHeight = $(element).height();
                    maxWidth = $(element).width();
                    offset = $(element).offset();

                    $(doc).bind(duringDragEvents);
                    $(doc.body).addClass("sp-dragging");

                    if (!hasTouch) {
                        move(e);
                    }

                    prevent(e);
                }
            }
        }
        function stop() {
            if (dragging) {
                $(doc).unbind(duringDragEvents);
                $(doc.body).removeClass("sp-dragging");
                onstop.apply(element, arguments);
            }
            dragging = false;
        }

        $(element).bind(hasTouch ? "touchstart" : "mousedown", start);
    }

    function throttle(func, wait, debounce) {
        var timeout;
        return function () {
            var context = this, args = arguments;
            var throttler = function () {
                timeout = null;
                func.apply(context, args);
            };
            if (debounce) clearTimeout(timeout);
            if (debounce || !timeout) timeout = setTimeout(throttler, wait);
        };
    }


    /**
    * Define a jQuery plugin
    */
    var dataID = "spectrum.id";
    $.fn.spectrum = function (opts, extra) {

        if (typeof opts == "string") {

            var returnValue = this;
            var args = Array.prototype.slice.call( arguments, 1 );

            this.each(function () {
                var spect = spectrums[$(this).data(dataID)];
                if (spect) {

                    var method = spect[opts];
                    if (!method) {
                        throw new Error( "Spectrum: no such method: '" + opts + "'" );
                    }

                    if (opts == "get") {
                        returnValue = spect.get();
                    }
                    else if (opts == "container") {
                        returnValue = spect.container;
                    }
                    else if (opts == "option") {
                        returnValue = spect.option.apply(spect, args);
                    }
                    else if (opts == "destroy") {
                        spect.destroy();
                        $(this).removeData(dataID);
                    }
                    else {
                        method.apply(spect, args);
                    }
                }
            });

            return returnValue;
        }

        // Initializing a new instance of spectrum
        return this.spectrum("destroy").each(function () {
            var spect = spectrum(this, opts);
            $(this).data(dataID, spect.id);
        });
    };

    $.fn.spectrum.load = true;
    $.fn.spectrum.loadOpts = {};
    $.fn.spectrum.draggable = draggable;
    $.fn.spectrum.defaults = defaultOpts;

    $.spectrum = { };
    $.spectrum.localization = { };
    $.spectrum.palettes = { };

    $.fn.spectrum.processNativeColorInputs = function () {
        var colorInput = $("<input type='color' value='!' />")[0];
        var supportsColor = colorInput.type === "color" && colorInput.value != "!";

        if (!supportsColor) {
            $("input[type=color]").spectrum({
                preferredFormat: "hex6"
            });
        }
    };
    // TinyColor v0.9.14
    // https://github.com/bgrins/TinyColor
    // 2013-02-24, Brian Grinstead, MIT License

    (function(root) {

        var trimLeft = /^[\s,#]+/,
            trimRight = /\s+$/,
            tinyCounter = 0,
            math = Math,
            mathRound = math.round,
            mathMin = math.min,
            mathMax = math.max,
            mathRandom = math.random;

        function tinycolor (color, opts) {

            color = (color) ? color : '';
            opts = opts || { };

            // If input is already a tinycolor, return itself
            if (typeof color == "object" && color.hasOwnProperty("_tc_id")) {
               return color;
            }
            var rgb = inputToRGB(color);
            var r = rgb.r,
                g = rgb.g,
                b = rgb.b,
                a = rgb.a,
                roundA = mathRound(100*a) / 100,
                format = opts.format || rgb.format;

            // Don't let the range of [0,255] come back in [0,1].
            // Potentially lose a little bit of precision here, but will fix issues where
            // .5 gets interpreted as half of the total, instead of half of 1
            // If it was supposed to be 128, this was already taken care of by `inputToRgb`
            if (r < 1) { r = mathRound(r); }
            if (g < 1) { g = mathRound(g); }
            if (b < 1) { b = mathRound(b); }

            return {
                ok: rgb.ok,
                format: format,
                _tc_id: tinyCounter++,
                alpha: a,
                toHsv: function() {
                    var hsv = rgbToHsv(r, g, b);
                    return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: a };
                },
                toHsvString: function() {
                    var hsv = rgbToHsv(r, g, b);
                    var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
                    return (a == 1) ?
                      "hsv("  + h + ", " + s + "%, " + v + "%)" :
                      "hsva(" + h + ", " + s + "%, " + v + "%, "+ roundA + ")";
                },
                toHsl: function() {
                    var hsl = rgbToHsl(r, g, b);
                    return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: a };
                },
                toHslString: function() {
                    var hsl = rgbToHsl(r, g, b);
                    var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
                    return (a == 1) ?
                      "hsl("  + h + ", " + s + "%, " + l + "%)" :
                      "hsla(" + h + ", " + s + "%, " + l + "%, "+ roundA + ")";
                },
                toHex: function(allow3Char) {
                    return rgbToHex(r, g, b, allow3Char);
                },
                toHexString: function(allow3Char) {
                    return '#' + rgbToHex(r, g, b, allow3Char);
                },
                toRgb: function() {
                    return { r: mathRound(r), g: mathRound(g), b: mathRound(b), a: a };
                },
                toRgbString: function() {
                    return (a == 1) ?
                      "rgb("  + mathRound(r) + ", " + mathRound(g) + ", " + mathRound(b) + ")" :
                      "rgba(" + mathRound(r) + ", " + mathRound(g) + ", " + mathRound(b) + ", " + roundA + ")";
                },
                toPercentageRgb: function() {
                    return { r: mathRound(bound01(r, 255) * 100) + "%", g: mathRound(bound01(g, 255) * 100) + "%", b: mathRound(bound01(b, 255) * 100) + "%", a: a };
                },
                toPercentageRgbString: function() {
                    return (a == 1) ?
                      "rgb("  + mathRound(bound01(r, 255) * 100) + "%, " + mathRound(bound01(g, 255) * 100) + "%, " + mathRound(bound01(b, 255) * 100) + "%)" :
                      "rgba(" + mathRound(bound01(r, 255) * 100) + "%, " + mathRound(bound01(g, 255) * 100) + "%, " + mathRound(bound01(b, 255) * 100) + "%, " + roundA + ")";
                },
                toName: function() {
                    return hexNames[rgbToHex(r, g, b, true)] || false;
                },
                toFilter: function(secondColor) {
                    var hex = rgbToHex(r, g, b);
                    var secondHex = hex;
                    var alphaHex = Math.round(parseFloat(a) * 255).toString(16);
                    var secondAlphaHex = alphaHex;
                    var gradientType = opts && opts.gradientType ? "GradientType = 1, " : "";

                    if (secondColor) {
                        var s = tinycolor(secondColor);
                        secondHex = s.toHex();
                        secondAlphaHex = Math.round(parseFloat(s.alpha) * 255).toString(16);
                    }

                    return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr=#" + pad2(alphaHex) + hex + ",endColorstr=#" + pad2(secondAlphaHex) + secondHex + ")";
                },
                toString: function(format) {
                    format = format || this.format;
                    var formattedString = false;
                    if (format === "rgb") {
                        formattedString = this.toRgbString();
                    }
                    if (format === "prgb") {
                        formattedString = this.toPercentageRgbString();
                    }
                    if (format === "hex" || format === "hex6") {
                        formattedString = this.toHexString();
                    }
                    if (format === "hex3") {
                        formattedString = this.toHexString(true);
                    }
                    if (format === "name") {
                        formattedString = this.toName();
                    }
                    if (format === "hsl") {
                        formattedString = this.toHslString();
                    }
                    if (format === "hsv") {
                        formattedString = this.toHsvString();
                    }

                    return formattedString || this.toHexString();
                }
            };
        }

        // If input is an object, force 1 into "1.0" to handle ratios properly
        // String input requires "1.0" as input, so 1 will be treated as 1
        tinycolor.fromRatio = function(color, opts) {
            if (typeof color == "object") {
                var newColor = {};
                for (var i in color) {
                    if (color.hasOwnProperty(i)) {
                        if (i === "a") {
                            newColor[i] = color[i];
                        }
                        else {
                            newColor[i] = convertToPercentage(color[i]);
                        }
                    }
                }
                color = newColor;
            }

            return tinycolor(color, opts);
        };

        // Given a string or object, convert that input to RGB
        // Possible string inputs:
        //
        //     "red"
        //     "#f00" or "f00"
        //     "#ff0000" or "ff0000"
        //     "rgb 255 0 0" or "rgb (255, 0, 0)"
        //     "rgb 1.0 0 0" or "rgb (1, 0, 0)"
        //     "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
        //     "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
        //     "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
        //     "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
        //     "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
        //
        function inputToRGB(color) {

            var rgb = { r: 0, g: 0, b: 0 };
            var a = 1;
            var ok = false;
            var format = false;

            if (typeof color == "string") {
                color = stringInputToObject(color);
            }

            if (typeof color == "object") {
                if (color.hasOwnProperty("r") && color.hasOwnProperty("g") && color.hasOwnProperty("b")) {
                    rgb = rgbToRgb(color.r, color.g, color.b);
                    ok = true;
                    format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
                }
                else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("v")) {
                    color.s = convertToPercentage(color.s);
                    color.v = convertToPercentage(color.v);
                    rgb = hsvToRgb(color.h, color.s, color.v);
                    ok = true;
                    format = "hsv";
                }
                else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("l")) {
                    color.s = convertToPercentage(color.s);
                    color.l = convertToPercentage(color.l);
                    rgb = hslToRgb(color.h, color.s, color.l);
                    ok = true;
                    format = "hsl";
                }

                if (color.hasOwnProperty("a")) {
                    a = color.a;
                }
            }

            a = parseFloat(a);

            // Handle invalid alpha characters by setting to 1
            if (isNaN(a) || a < 0 || a > 1) {
                a = 1;
            }

            return {
                ok: ok,
                format: color.format || format,
                r: mathMin(255, mathMax(rgb.r, 0)),
                g: mathMin(255, mathMax(rgb.g, 0)),
                b: mathMin(255, mathMax(rgb.b, 0)),
                a: a
            };
        }



        // Conversion Functions
        // --------------------

        // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
        // <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>

        // `rgbToRgb`
        // Handle bounds / percentage checking to conform to CSS color spec
        // <http://www.w3.org/TR/css3-color/>
        // *Assumes:* r, g, b in [0, 255] or [0, 1]
        // *Returns:* { r, g, b } in [0, 255]
        function rgbToRgb(r, g, b){
            return {
                r: bound01(r, 255) * 255,
                g: bound01(g, 255) * 255,
                b: bound01(b, 255) * 255
            };
        }

        // `rgbToHsl`
        // Converts an RGB color value to HSL.
        // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
        // *Returns:* { h, s, l } in [0,1]
        function rgbToHsl(r, g, b) {

            r = bound01(r, 255);
            g = bound01(g, 255);
            b = bound01(b, 255);

            var max = mathMax(r, g, b), min = mathMin(r, g, b);
            var h, s, l = (max + min) / 2;

            if(max == min) {
                h = s = 0; // achromatic
            }
            else {
                var d = max - min;
                s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
                switch(max) {
                    case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                    case g: h = (b - r) / d + 2; break;
                    case b: h = (r - g) / d + 4; break;
                }

                h /= 6;
            }

            return { h: h, s: s, l: l };
        }

        // `hslToRgb`
        // Converts an HSL color value to RGB.
        // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
        // *Returns:* { r, g, b } in the set [0, 255]
        function hslToRgb(h, s, l) {
            var r, g, b;

            h = bound01(h, 360);
            s = bound01(s, 100);
            l = bound01(l, 100);

            function hue2rgb(p, q, t) {
                if(t < 0) t += 1;
                if(t > 1) t -= 1;
                if(t < 1/6) return p + (q - p) * 6 * t;
                if(t < 1/2) return q;
                if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
                return p;
            }

            if(s === 0) {
                r = g = b = l; // achromatic
            }
            else {
                var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
                var p = 2 * l - q;
                r = hue2rgb(p, q, h + 1/3);
                g = hue2rgb(p, q, h);
                b = hue2rgb(p, q, h - 1/3);
            }

            return { r: r * 255, g: g * 255, b: b * 255 };
        }

        // `rgbToHsv`
        // Converts an RGB color value to HSV
        // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
        // *Returns:* { h, s, v } in [0,1]
        function rgbToHsv(r, g, b) {

            r = bound01(r, 255);
            g = bound01(g, 255);
            b = bound01(b, 255);

            var max = mathMax(r, g, b), min = mathMin(r, g, b);
            var h, s, v = max;

            var d = max - min;
            s = max === 0 ? 0 : d / max;

            if(max == min) {
                h = 0; // achromatic
            }
            else {
                switch(max) {
                    case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                    case g: h = (b - r) / d + 2; break;
                    case b: h = (r - g) / d + 4; break;
                }
                h /= 6;
            }
            return { h: h, s: s, v: v };
        }

        // `hsvToRgb`
        // Converts an HSV color value to RGB.
        // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
        // *Returns:* { r, g, b } in the set [0, 255]
         function hsvToRgb(h, s, v) {

            h = bound01(h, 360) * 6;
            s = bound01(s, 100);
            v = bound01(v, 100);

            var i = math.floor(h),
                f = h - i,
                p = v * (1 - s),
                q = v * (1 - f * s),
                t = v * (1 - (1 - f) * s),
                mod = i % 6,
                r = [v, q, p, p, t, v][mod],
                g = [t, v, v, q, p, p][mod],
                b = [p, p, t, v, v, q][mod];

            return { r: r * 255, g: g * 255, b: b * 255 };
        }

        // `rgbToHex`
        // Converts an RGB color to hex
        // Assumes r, g, and b are contained in the set [0, 255]
        // Returns a 3 or 6 character hex
        function rgbToHex(r, g, b, allow3Char) {

            var hex = [
                pad2(mathRound(r).toString(16)),
                pad2(mathRound(g).toString(16)),
                pad2(mathRound(b).toString(16))
            ];

            // Return a 3 character hex if possible
            if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
                return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
            }

            return hex.join("");
        }

        // `equals`
        // Can be called with any tinycolor input
        tinycolor.equals = function (color1, color2) {
            if (!color1 || !color2) { return false; }
            return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
        };
        tinycolor.random = function() {
            return tinycolor.fromRatio({
                r: mathRandom(),
                g: mathRandom(),
                b: mathRandom()
            });
        };


        // Modification Functions
        // ----------------------
        // Thanks to less.js for some of the basics here
        // <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>


        tinycolor.desaturate = function (color, amount) {
            var hsl = tinycolor(color).toHsl();
            hsl.s -= ((amount || 10) / 100);
            hsl.s = clamp01(hsl.s);
            return tinycolor(hsl);
        };
        tinycolor.saturate = function (color, amount) {
            var hsl = tinycolor(color).toHsl();
            hsl.s += ((amount || 10) / 100);
            hsl.s = clamp01(hsl.s);
            return tinycolor(hsl);
        };
        tinycolor.greyscale = function(color) {
            return tinycolor.desaturate(color, 100);
        };
        tinycolor.lighten = function(color, amount) {
            var hsl = tinycolor(color).toHsl();
            hsl.l += ((amount || 10) / 100);
            hsl.l = clamp01(hsl.l);
            return tinycolor(hsl);
        };
        tinycolor.darken = function (color, amount) {
            var hsl = tinycolor(color).toHsl();
            hsl.l -= ((amount || 10) / 100);
            hsl.l = clamp01(hsl.l);
            return tinycolor(hsl);
        };
        tinycolor.complement = function(color) {
            var hsl = tinycolor(color).toHsl();
            hsl.h = (hsl.h + 180) % 360;
            return tinycolor(hsl);
        };


        // Combination Functions
        // ---------------------
        // Thanks to jQuery xColor for some of the ideas behind these
        // <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>

        tinycolor.triad = function(color) {
            var hsl = tinycolor(color).toHsl();
            var h = hsl.h;
            return [
                tinycolor(color),
                tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
                tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
            ];
        };
        tinycolor.tetrad = function(color) {
            var hsl = tinycolor(color).toHsl();
            var h = hsl.h;
            return [
                tinycolor(color),
                tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
                tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
                tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
            ];
        };
        tinycolor.splitcomplement = function(color) {
            var hsl = tinycolor(color).toHsl();
            var h = hsl.h;
            return [
                tinycolor(color),
                tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
                tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
            ];
        };
        tinycolor.analogous = function(color, results, slices) {
            results = results || 6;
            slices = slices || 30;

            var hsl = tinycolor(color).toHsl();
            var part = 360 / slices;
            var ret = [tinycolor(color)];

            for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
                hsl.h = (hsl.h + part) % 360;
                ret.push(tinycolor(hsl));
            }
            return ret;
        };
        tinycolor.monochromatic = function(color, results) {
            results = results || 6;
            var hsv = tinycolor(color).toHsv();
            var h = hsv.h, s = hsv.s, v = hsv.v;
            var ret = [];
            var modification = 1 / results;

            while (results--) {
                ret.push(tinycolor({ h: h, s: s, v: v}));
                v = (v + modification) % 1;
            }

            return ret;
        };

        // Readability Functions
        // ---------------------
        // <http://www.w3.org/TR/AERT#color-contrast>

        // `readability`
        // Analyze the 2 colors and returns an object with the following properties:
        //    `brightness`: difference in brightness between the two colors
        //    `color`: difference in color/hue between the two colors
        tinycolor.readability = function(color1, color2) {
            var a = tinycolor(color1).toRgb();
            var b = tinycolor(color2).toRgb();
            var brightnessA = (a.r * 299 + a.g * 587 + a.b * 114) / 1000;
            var brightnessB = (b.r * 299 + b.g * 587 + b.b * 114) / 1000;
            var colorDiff = (
                Math.max(a.r, b.r) - Math.min(a.r, b.r) +
                Math.max(a.g, b.g) - Math.min(a.g, b.g) +
                Math.max(a.b, b.b) - Math.min(a.b, b.b)
            );

            return {
                brightness: Math.abs(brightnessA - brightnessB),
                color: colorDiff
            };
        };

        // `readable`
        // http://www.w3.org/TR/AERT#color-contrast
        // Ensure that foreground and background color combinations provide sufficient contrast.
        // *Example*
        //    tinycolor.readable("#000", "#111") => false
        tinycolor.readable = function(color1, color2) {
            var readability = tinycolor.readability(color1, color2);
            return readability.brightness > 125 && readability.color > 500;
        };

        // `mostReadable`
        // Given a base color and a list of possible foreground or background
        // colors for that base, returns the most readable color.
        // *Example*
        //    tinycolor.mostReadable("#123", ["#fff", "#000"]) => "#000"
        tinycolor.mostReadable = function(baseColor, colorList) {
            var bestColor = null;
            var bestScore = 0;
            var bestIsReadable = false;
            for (var i=0; i < colorList.length; i++) {

                // We normalize both around the "acceptable" breaking point,
                // but rank brightness constrast higher than hue.

                var readability = tinycolor.readability(baseColor, colorList[i]);
                var readable = readability.brightness > 125 && readability.color > 500;
                var score = 3 * (readability.brightness / 125) + (readability.color / 500);

                if ((readable && ! bestIsReadable) ||
                    (readable && bestIsReadable && score > bestScore) ||
                    ((! readable) && (! bestIsReadable) && score > bestScore)) {
                    bestIsReadable = readable;
                    bestScore = score;
                    bestColor = tinycolor(colorList[i]);
                }
            }
            return bestColor;
        };


        // Big List of Colors
        // ------------------
        // <http://www.w3.org/TR/css3-color/#svg-color>
        var names = tinycolor.names = {
            aliceblue: "f0f8ff",
            antiquewhite: "faebd7",
            aqua: "0ff",
            aquamarine: "7fffd4",
            azure: "f0ffff",
            beige: "f5f5dc",
            bisque: "ffe4c4",
            black: "000",
            blanchedalmond: "ffebcd",
            blue: "00f",
            blueviolet: "8a2be2",
            brown: "a52a2a",
            burlywood: "deb887",
            burntsienna: "ea7e5d",
            cadetblue: "5f9ea0",
            chartreuse: "7fff00",
            chocolate: "d2691e",
            coral: "ff7f50",
            cornflowerblue: "6495ed",
            cornsilk: "fff8dc",
            crimson: "dc143c",
            cyan: "0ff",
            darkblue: "00008b",
            darkcyan: "008b8b",
            darkgoldenrod: "b8860b",
            darkgray: "a9a9a9",
            darkgreen: "006400",
            darkgrey: "a9a9a9",
            darkkhaki: "bdb76b",
            darkmagenta: "8b008b",
            darkolivegreen: "556b2f",
            darkorange: "ff8c00",
            darkorchid: "9932cc",
            darkred: "8b0000",
            darksalmon: "e9967a",
            darkseagreen: "8fbc8f",
            darkslateblue: "483d8b",
            darkslategray: "2f4f4f",
            darkslategrey: "2f4f4f",
            darkturquoise: "00ced1",
            darkviolet: "9400d3",
            deeppink: "ff1493",
            deepskyblue: "00bfff",
            dimgray: "696969",
            dimgrey: "696969",
            dodgerblue: "1e90ff",
            firebrick: "b22222",
            floralwhite: "fffaf0",
            forestgreen: "228b22",
            fuchsia: "f0f",
            gainsboro: "dcdcdc",
            ghostwhite: "f8f8ff",
            gold: "ffd700",
            goldenrod: "daa520",
            gray: "808080",
            green: "008000",
            greenyellow: "adff2f",
            grey: "808080",
            honeydew: "f0fff0",
            hotpink: "ff69b4",
            indianred: "cd5c5c",
            indigo: "4b0082",
            ivory: "fffff0",
            khaki: "f0e68c",
            lavender: "e6e6fa",
            lavenderblush: "fff0f5",
            lawngreen: "7cfc00",
            lemonchiffon: "fffacd",
            lightblue: "add8e6",
            lightcoral: "f08080",
            lightcyan: "e0ffff",
            lightgoldenrodyellow: "fafad2",
            lightgray: "d3d3d3",
            lightgreen: "90ee90",
            lightgrey: "d3d3d3",
            lightpink: "ffb6c1",
            lightsalmon: "ffa07a",
            lightseagreen: "20b2aa",
            lightskyblue: "87cefa",
            lightslategray: "789",
            lightslategrey: "789",
            lightsteelblue: "b0c4de",
            lightyellow: "ffffe0",
            lime: "0f0",
            limegreen: "32cd32",
            linen: "faf0e6",
            magenta: "f0f",
            maroon: "800000",
            mediumaquamarine: "66cdaa",
            mediumblue: "0000cd",
            mediumorchid: "ba55d3",
            mediumpurple: "9370db",
            mediumseagreen: "3cb371",
            mediumslateblue: "7b68ee",
            mediumspringgreen: "00fa9a",
            mediumturquoise: "48d1cc",
            mediumvioletred: "c71585",
            midnightblue: "191970",
            mintcream: "f5fffa",
            mistyrose: "ffe4e1",
            moccasin: "ffe4b5",
            navajowhite: "ffdead",
            navy: "000080",
            oldlace: "fdf5e6",
            olive: "808000",
            olivedrab: "6b8e23",
            orange: "ffa500",
            orangered: "ff4500",
            orchid: "da70d6",
            palegoldenrod: "eee8aa",
            palegreen: "98fb98",
            paleturquoise: "afeeee",
            palevioletred: "db7093",
            papayawhip: "ffefd5",
            peachpuff: "ffdab9",
            peru: "cd853f",
            pink: "ffc0cb",
            plum: "dda0dd",
            powderblue: "b0e0e6",
            purple: "800080",
            red: "f00",
            rosybrown: "bc8f8f",
            royalblue: "4169e1",
            saddlebrown: "8b4513",
            salmon: "fa8072",
            sandybrown: "f4a460",
            seagreen: "2e8b57",
            seashell: "fff5ee",
            sienna: "a0522d",
            silver: "c0c0c0",
            skyblue: "87ceeb",
            slateblue: "6a5acd",
            slategray: "708090",
            slategrey: "708090",
            snow: "fffafa",
            springgreen: "00ff7f",
            steelblue: "4682b4",
            tan: "d2b48c",
            teal: "008080",
            thistle: "d8bfd8",
            tomato: "ff6347",
            turquoise: "40e0d0",
            violet: "ee82ee",
            wheat: "f5deb3",
            white: "fff",
            whitesmoke: "f5f5f5",
            yellow: "ff0",
            yellowgreen: "9acd32"
        };

        // Make it easy to access colors via `hexNames[hex]`
        var hexNames = tinycolor.hexNames = flip(names);


        // Utilities
        // ---------

        // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
        function flip(o) {
            var flipped = { };
            for (var i in o) {
                if (o.hasOwnProperty(i)) {
                    flipped[o[i]] = i;
                }
            }
            return flipped;
        }

        // Take input from [0, n] and return it as [0, 1]
        function bound01(n, max) {
            if (isOnePointZero(n)) { n = "100%"; }

            var processPercent = isPercentage(n);
            n = mathMin(max, mathMax(0, parseFloat(n)));

            // Automatically convert percentage into number
            if (processPercent) {
                n = parseInt(n * max, 10) / 100;
            }

            // Handle floating point rounding errors
            if ((math.abs(n - max) < 0.000001)) {
                return 1;
            }

            // Convert into [0, 1] range if it isn't already
            return (n % max) / parseFloat(max);
        }

        // Force a number between 0 and 1
        function clamp01(val) {
            return mathMin(1, mathMax(0, val));
        }

        // Parse an integer into hex
        function parseHex(val) {
            return parseInt(val, 16);
        }

        // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
        // <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
        function isOnePointZero(n) {
            return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
        }

        // Check to see if string passed in is a percentage
        function isPercentage(n) {
            return typeof n === "string" && n.indexOf('%') != -1;
        }

        // Force a hex value to have 2 characters
        function pad2(c) {
            return c.length == 1 ? '0' + c : '' + c;
        }

        // Replace a decimal with it's percentage value
        function convertToPercentage(n) {
            if (n <= 1) {
                n = (n * 100) + "%";
            }

            return n;
        }

        var matchers = (function() {

            // <http://www.w3.org/TR/css3-values/#integers>
            var CSS_INTEGER = "[-\\+]?\\d+%?";

            // <http://www.w3.org/TR/css3-values/#number-value>
            var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";

            // Allow positive/negative integer/number.  Don't capture the either/or, just the entire outcome.
            var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";

            // Actual matching.
            // Parentheses and commas are optional, but not required.
            // Whitespace can take the place of commas or opening paren
            var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
            var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";

            return {
                rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
                rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
                hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
                hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
                hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
                hex3: /^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
                hex6: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
            };
        })();

        // `stringInputToObject`
        // Permissive string parsing.  Take in a number of formats, and output an object
        // based on detected format.  Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
        function stringInputToObject(color) {

            color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
            var named = false;
            if (names[color]) {
                color = names[color];
                named = true;
            }
            else if (color == 'transparent') {
                return { r: 0, g: 0, b: 0, a: 0 };
            }

            // Try to match string input using regular expressions.
            // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
            // Just return an object and let the conversion functions handle that.
            // This way the result will be the same whether the tinycolor is initialized with string or object.
            var match;
            if ((match = matchers.rgb.exec(color))) {
                return { r: match[1], g: match[2], b: match[3] };
            }
            if ((match = matchers.rgba.exec(color))) {
                return { r: match[1], g: match[2], b: match[3], a: match[4] };
            }
            if ((match = matchers.hsl.exec(color))) {
                return { h: match[1], s: match[2], l: match[3] };
            }
            if ((match = matchers.hsla.exec(color))) {
                return { h: match[1], s: match[2], l: match[3], a: match[4] };
            }
            if ((match = matchers.hsv.exec(color))) {
                return { h: match[1], s: match[2], v: match[3] };
            }
            if ((match = matchers.hex6.exec(color))) {
                return {
                    r: parseHex(match[1]),
                    g: parseHex(match[2]),
                    b: parseHex(match[3]),
                    format: named ? "name" : "hex"
                };
            }
            if ((match = matchers.hex3.exec(color))) {
                return {
                    r: parseHex(match[1] + '' + match[1]),
                    g: parseHex(match[2] + '' + match[2]),
                    b: parseHex(match[3] + '' + match[3]),
                    format: named ? "name" : "hex"
                };
            }

            return false;
        }

        root.tinycolor = tinycolor;

    })(this);



    $(function () {
        if ($.fn.spectrum.load) {
            $.fn.spectrum.processNativeColorInputs();
        }
    });


    function log(){window.console&&(log=Function.prototype.bind?Function.prototype.bind.call(console.log,console):function(){Function.prototype.apply.call(console.log,console,arguments)},log.apply(this,arguments))};


})(window, jQuery);
;
/*!
 * Select2 4.0.0
 * https://select2.github.io
 *
 * Released under the MIT license
 * https://github.com/select2/select2/blob/master/LICENSE.md
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS
        factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function (jQuery) {
    // This is needed so we can catch the AMD loader configuration and use it
    // The inner file should be wrapped (by `banner.start.js`) in a function that
    // returns the AMD loader references.
    var S2 =
  (function () {
      // Restore the Select2 AMD loader so it can be used
      // Needed mostly in the language files, where the loader is not inserted
      if (jQuery && jQuery.fn && jQuery.fn.select2 && jQuery.fn.select2.amd) {
          var S2 = jQuery.fn.select2.amd;
      }
      var S2; (function () {
          if (!S2 || !S2.requirejs) {
              if (!S2) { S2 = {}; } else { require = S2; }
              /**
               * @license almond 0.2.9 Copyright (c) 2011-2014, The Dojo Foundation All Rights Reserved.
               * Available via the MIT or new BSD license.
               * see: http://github.com/jrburke/almond for details
               */
              //Going sloppy to avoid 'use strict' string cost, but strict practices should
              //be followed.
              /*jslint sloppy: true */
              /*global setTimeout: false */

              var requirejs, require, define;
              (function (undef) {
                  var main, req, makeMap, handlers,
                      defined = {},
                      waiting = {},
                      config = {},
                      defining = {},
                      hasOwn = Object.prototype.hasOwnProperty,
                      aps = [].slice,
                      jsSuffixRegExp = /\.js$/;

                  function hasProp(obj, prop) {
                      return hasOwn.call(obj, prop);
                  }

                  /**
                   * Given a relative module name, like ./something, normalize it to
                   * a real name that can be mapped to a path.
                   * @param {String} name the relative name
                   * @param {String} baseName a real name that the name arg is relative
                   * to.
                   * @returns {String} normalized name
                   */
                  function normalize(name, baseName) {
                      var nameParts, nameSegment, mapValue, foundMap, lastIndex,
                          foundI, foundStarMap, starI, i, j, part,
                          baseParts = baseName && baseName.split("/"),
                          map = config.map,
                          starMap = (map && map['*']) || {};

                      //Adjust any relative paths.
                      if (name && name.charAt(0) === ".") {
                          //If have a base name, try to normalize against it,
                          //otherwise, assume it is a top-level require that will
                          //be relative to baseUrl in the end.
                          if (baseName) {
                              //Convert baseName to array, and lop off the last part,
                              //so that . matches that "directory" and not name of the baseName's
                              //module. For instance, baseName of "one/two/three", maps to
                              //"one/two/three.js", but we want the directory, "one/two" for
                              //this normalization.
                              baseParts = baseParts.slice(0, baseParts.length - 1);
                              name = name.split('/');
                              lastIndex = name.length - 1;

                              // Node .js allowance:
                              if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
                                  name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
                              }

                              name = baseParts.concat(name);

                              //start trimDots
                              for (i = 0; i < name.length; i += 1) {
                                  part = name[i];
                                  if (part === ".") {
                                      name.splice(i, 1);
                                      i -= 1;
                                  } else if (part === "..") {
                                      if (i === 1 && (name[2] === '..' || name[0] === '..')) {
                                          //End of the line. Keep at least one non-dot
                                          //path segment at the front so it can be mapped
                                          //correctly to disk. Otherwise, there is likely
                                          //no path mapping for a path starting with '..'.
                                          //This can still fail, but catches the most reasonable
                                          //uses of ..
                                          break;
                                      } else if (i > 0) {
                                          name.splice(i - 1, 2);
                                          i -= 2;
                                      }
                                  }
                              }
                              //end trimDots

                              name = name.join("/");
                          } else if (name.indexOf('./') === 0) {
                              // No baseName, so this is ID is resolved relative
                              // to baseUrl, pull off the leading dot.
                              name = name.substring(2);
                          }
                      }

                      //Apply map config if available.
                      if ((baseParts || starMap) && map) {
                          nameParts = name.split('/');

                          for (i = nameParts.length; i > 0; i -= 1) {
                              nameSegment = nameParts.slice(0, i).join("/");

                              if (baseParts) {
                                  //Find the longest baseName segment match in the config.
                                  //So, do joins on the biggest to smallest lengths of baseParts.
                                  for (j = baseParts.length; j > 0; j -= 1) {
                                      mapValue = map[baseParts.slice(0, j).join('/')];

                                      //baseName segment has  config, find if it has one for
                                      //this name.
                                      if (mapValue) {
                                          mapValue = mapValue[nameSegment];
                                          if (mapValue) {
                                              //Match, update name to the new value.
                                              foundMap = mapValue;
                                              foundI = i;
                                              break;
                                          }
                                      }
                                  }
                              }

                              if (foundMap) {
                                  break;
                              }

                              //Check for a star map match, but just hold on to it,
                              //if there is a shorter segment match later in a matching
                              //config, then favor over this star map.
                              if (!foundStarMap && starMap && starMap[nameSegment]) {
                                  foundStarMap = starMap[nameSegment];
                                  starI = i;
                              }
                          }

                          if (!foundMap && foundStarMap) {
                              foundMap = foundStarMap;
                              foundI = starI;
                          }

                          if (foundMap) {
                              nameParts.splice(0, foundI, foundMap);
                              name = nameParts.join('/');
                          }
                      }

                      return name;
                  }

                  function makeRequire(relName, forceSync) {
                      return function () {
                          //A version of a require function that passes a moduleName
                          //value for items that may need to
                          //look up paths relative to the moduleName
                          return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync]));
                      };
                  }

                  function makeNormalize(relName) {
                      return function (name) {
                          return normalize(name, relName);
                      };
                  }

                  function makeLoad(depName) {
                      return function (value) {
                          defined[depName] = value;
                      };
                  }

                  function callDep(name) {
                      if (hasProp(waiting, name)) {
                          var args = waiting[name];
                          delete waiting[name];
                          defining[name] = true;
                          main.apply(undef, args);
                      }

                      if (!hasProp(defined, name) && !hasProp(defining, name)) {
                          throw new Error('No ' + name);
                      }
                      return defined[name];
                  }

                  //Turns a plugin!resource to [plugin, resource]
                  //with the plugin being undefined if the name
                  //did not have a plugin prefix.
                  function splitPrefix(name) {
                      var prefix,
                          index = name ? name.indexOf('!') : -1;
                      if (index > -1) {
                          prefix = name.substring(0, index);
                          name = name.substring(index + 1, name.length);
                      }
                      return [prefix, name];
                  }

                  /**
                   * Makes a name map, normalizing the name, and using a plugin
                   * for normalization if necessary. Grabs a ref to plugin
                   * too, as an optimization.
                   */
                  makeMap = function (name, relName) {
                      var plugin,
                          parts = splitPrefix(name),
                          prefix = parts[0];

                      name = parts[1];

                      if (prefix) {
                          prefix = normalize(prefix, relName);
                          plugin = callDep(prefix);
                      }

                      //Normalize according
                      if (prefix) {
                          if (plugin && plugin.normalize) {
                              name = plugin.normalize(name, makeNormalize(relName));
                          } else {
                              name = normalize(name, relName);
                          }
                      } else {
                          name = normalize(name, relName);
                          parts = splitPrefix(name);
                          prefix = parts[0];
                          name = parts[1];
                          if (prefix) {
                              plugin = callDep(prefix);
                          }
                      }

                      //Using ridiculous property names for space reasons
                      return {
                          f: prefix ? prefix + '!' + name : name, //fullName
                          n: name,
                          pr: prefix,
                          p: plugin
                      };
                  };

                  function makeConfig(name) {
                      return function () {
                          return (config && config.config && config.config[name]) || {};
                      };
                  }

                  handlers = {
                      require: function (name) {
                          return makeRequire(name);
                      },
                      exports: function (name) {
                          var e = defined[name];
                          if (typeof e !== 'undefined') {
                              return e;
                          } else {
                              return (defined[name] = {});
                          }
                      },
                      module: function (name) {
                          return {
                              id: name,
                              uri: '',
                              exports: defined[name],
                              config: makeConfig(name)
                          };
                      }
                  };

                  main = function (name, deps, callback, relName) {
                      var cjsModule, depName, ret, map, i,
                          args = [],
                          callbackType = typeof callback,
                          usingExports;

                      //Use name if no relName
                      relName = relName || name;

                      //Call the callback to define the module, if necessary.
                      if (callbackType === 'undefined' || callbackType === 'function') {
                          //Pull out the defined dependencies and pass the ordered
                          //values to the callback.
                          //Default to [require, exports, module] if no deps
                          deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
                          for (i = 0; i < deps.length; i += 1) {
                              map = makeMap(deps[i], relName);
                              depName = map.f;

                              //Fast path CommonJS standard dependencies.
                              if (depName === "require") {
                                  args[i] = handlers.require(name);
                              } else if (depName === "exports") {
                                  //CommonJS module spec 1.1
                                  args[i] = handlers.exports(name);
                                  usingExports = true;
                              } else if (depName === "module") {
                                  //CommonJS module spec 1.1
                                  cjsModule = args[i] = handlers.module(name);
                              } else if (hasProp(defined, depName) ||
                                         hasProp(waiting, depName) ||
                                         hasProp(defining, depName)) {
                                  args[i] = callDep(depName);
                              } else if (map.p) {
                                  map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
                                  args[i] = defined[depName];
                              } else {
                                  throw new Error(name + ' missing ' + depName);
                              }
                          }

                          ret = callback ? callback.apply(defined[name], args) : undefined;

                          if (name) {
                              //If setting exports via "module" is in play,
                              //favor that over return value and exports. After that,
                              //favor a non-undefined return value over exports use.
                              if (cjsModule && cjsModule.exports !== undef &&
                                      cjsModule.exports !== defined[name]) {
                                  defined[name] = cjsModule.exports;
                              } else if (ret !== undef || !usingExports) {
                                  //Use the return value from the function.
                                  defined[name] = ret;
                              }
                          }
                      } else if (name) {
                          //May just be an object definition for the module. Only
                          //worry about defining if have a module name.
                          defined[name] = callback;
                      }
                  };

                  requirejs = require = req = function (deps, callback, relName, forceSync, alt) {
                      if (typeof deps === "string") {
                          if (handlers[deps]) {
                              //callback in this case is really relName
                              return handlers[deps](callback);
                          }
                          //Just return the module wanted. In this scenario, the
                          //deps arg is the module name, and second arg (if passed)
                          //is just the relName.
                          //Normalize module name, if it contains . or ..
                          return callDep(makeMap(deps, callback).f);
                      } else if (!deps.splice) {
                          //deps is a config object, not an array.
                          config = deps;
                          if (config.deps) {
                              req(config.deps, config.callback);
                          }
                          if (!callback) {
                              return;
                          }

                          if (callback.splice) {
                              //callback is an array, which means it is a dependency list.
                              //Adjust args if there are dependencies
                              deps = callback;
                              callback = relName;
                              relName = null;
                          } else {
                              deps = undef;
                          }
                      }

                      //Support require(['a'])
                      callback = callback || function () { };

                      //If relName is a function, it is an errback handler,
                      //so remove it.
                      if (typeof relName === 'function') {
                          relName = forceSync;
                          forceSync = alt;
                      }

                      //Simulate async callback;
                      if (forceSync) {
                          main(undef, deps, callback, relName);
                      } else {
                          //Using a non-zero value because of concern for what old browsers
                          //do, and latest browsers "upgrade" to 4 if lower value is used:
                          //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout:
                          //If want a value immediately, use require('id') instead -- something
                          //that works in almond on the global level, but not guaranteed and
                          //unlikely to work in other AMD implementations.
                          setTimeout(function () {
                              main(undef, deps, callback, relName);
                          }, 4);
                      }

                      return req;
                  };

                  /**
                   * Just drops the config on the floor, but returns req in case
                   * the config return value is used.
                   */
                  req.config = function (cfg) {
                      return req(cfg);
                  };

                  /**
                   * Expose module registry for debugging and tooling
                   */
                  requirejs._defined = defined;

                  define = function (name, deps, callback) {

                      //This module may not have dependencies
                      if (!deps.splice) {
                          //deps is not an array, so probably means
                          //an object literal or factory function for
                          //the value. Adjust args.
                          callback = deps;
                          deps = [];
                      }

                      if (!hasProp(defined, name) && !hasProp(waiting, name)) {
                          waiting[name] = [name, deps, callback];
                      }
                  };

                  define.amd = {
                      jQuery: true
                  };
              }());

              S2.requirejs = requirejs; S2.require = require; S2.define = define;
          }
      }());
      S2.define("almond", function () { });

      /* global jQuery:false, $:false */
      S2.define('jquery', [], function () {
          var _$ = jQuery || $;

          if (_$ == null && console && console.error) {
              console.error(
                'Select2: An instance of jQuery or a jQuery-compatible library was not ' +
                'found. Make sure that you are including jQuery before Select2 on your ' +
                'web page.'
              );
          }

          return _$;
      });

      S2.define('select2/utils', [
        'jquery'
      ], function ($) {
          var Utils = {};

          Utils.Extend = function (ChildClass, SuperClass) {
              var __hasProp = {}.hasOwnProperty;

              function BaseConstructor() {
                  this.constructor = ChildClass;
              }

              for (var key in SuperClass) {
                  if (__hasProp.call(SuperClass, key)) {
                      ChildClass[key] = SuperClass[key];
                  }
              }

              BaseConstructor.prototype = SuperClass.prototype;
              ChildClass.prototype = new BaseConstructor();
              ChildClass.__super__ = SuperClass.prototype;

              return ChildClass;
          };

          function getMethods(theClass) {
              var proto = theClass.prototype;

              var methods = [];

              for (var methodName in proto) {
                  var m = proto[methodName];

                  if (typeof m !== 'function') {
                      continue;
                  }

                  if (methodName === 'constructor') {
                      continue;
                  }

                  methods.push(methodName);
              }

              return methods;
          }

          Utils.Decorate = function (SuperClass, DecoratorClass) {
              var decoratedMethods = getMethods(DecoratorClass);
              var superMethods = getMethods(SuperClass);

              function DecoratedClass() {
                  var unshift = Array.prototype.unshift;

                  var argCount = DecoratorClass.prototype.constructor.length;

                  var calledConstructor = SuperClass.prototype.constructor;

                  if (argCount > 0) {
                      unshift.call(arguments, SuperClass.prototype.constructor);

                      calledConstructor = DecoratorClass.prototype.constructor;
                  }

                  calledConstructor.apply(this, arguments);
              }

              DecoratorClass.displayName = SuperClass.displayName;

              function ctr() {
                  this.constructor = DecoratedClass;
              }

              DecoratedClass.prototype = new ctr();

              for (var m = 0; m < superMethods.length; m++) {
                  var superMethod = superMethods[m];

                  DecoratedClass.prototype[superMethod] =
                    SuperClass.prototype[superMethod];
              }

              var calledMethod = function (methodName) {
                  // Stub out the original method if it's not decorating an actual method
                  var originalMethod = function () { };

                  if (methodName in DecoratedClass.prototype) {
                      originalMethod = DecoratedClass.prototype[methodName];
                  }

                  var decoratedMethod = DecoratorClass.prototype[methodName];

                  return function () {
                      var unshift = Array.prototype.unshift;

                      unshift.call(arguments, originalMethod);

                      return decoratedMethod.apply(this, arguments);
                  };
              };

              for (var d = 0; d < decoratedMethods.length; d++) {
                  var decoratedMethod = decoratedMethods[d];

                  DecoratedClass.prototype[decoratedMethod] = calledMethod(decoratedMethod);
              }

              return DecoratedClass;
          };

          var Observable = function () {
              this.listeners = {};
          };

          Observable.prototype.on = function (event, callback) {
              this.listeners = this.listeners || {};

              if (event in this.listeners) {
                  this.listeners[event].push(callback);
              } else {
                  this.listeners[event] = [callback];
              }
          };

          Observable.prototype.trigger = function (event) {
              var slice = Array.prototype.slice;

              this.listeners = this.listeners || {};

              if (event in this.listeners) {
                  this.invoke(this.listeners[event], slice.call(arguments, 1));
              }

              if ('*' in this.listeners) {
                  this.invoke(this.listeners['*'], arguments);
              }
          };

          Observable.prototype.invoke = function (listeners, params) {
              for (var i = 0, len = listeners.length; i < len; i++) {
                  listeners[i].apply(this, params);
              }
          };

          Utils.Observable = Observable;

          Utils.generateChars = function (length) {
              var chars = '';

              for (var i = 0; i < length; i++) {
                  var randomChar = Math.floor(Math.random() * 36);
                  chars += randomChar.toString(36);
              }

              return chars;
          };

          Utils.bind = function (func, context) {
              return function () {
                  func.apply(context, arguments);
              };
          };

          Utils._convertData = function (data) {
              for (var originalKey in data) {
                  var keys = originalKey.split('-');

                  var dataLevel = data;

                  if (keys.length === 1) {
                      continue;
                  }

                  for (var k = 0; k < keys.length; k++) {
                      var key = keys[k];

                      // Lowercase the first letter
                      // By default, dash-separated becomes camelCase
                      key = key.substring(0, 1).toLowerCase() + key.substring(1);

                      if (!(key in dataLevel)) {
                          dataLevel[key] = {};
                      }

                      if (k == keys.length - 1) {
                          dataLevel[key] = data[originalKey];
                      }

                      dataLevel = dataLevel[key];
                  }

                  delete data[originalKey];
              }

              return data;
          };

          Utils.hasScroll = function (index, el) {
              // Adapted from the function created by @ShadowScripter
              // and adapted by @BillBarry on the Stack Exchange Code Review website.
              // The original code can be found at
              // http://codereview.stackexchange.com/q/13338
              // and was designed to be used with the Sizzle selector engine.

              var $el = $(el);
              var overflowX = el.style.overflowX;
              var overflowY = el.style.overflowY;

              //Check both x and y declarations
              if (overflowX === overflowY &&
                  (overflowY === 'hidden' || overflowY === 'visible')) {
                  return false;
              }

              if (overflowX === 'scroll' || overflowY === 'scroll') {
                  return true;
              }

              return ($el.innerHeight() < el.scrollHeight ||
                $el.innerWidth() < el.scrollWidth);
          };

          Utils.escapeMarkup = function (markup) {
              var replaceMap = {
                  '\\': '&#92;',
                  '&': '&amp;',
                  '<': '&lt;',
                  '>': '&gt;',
                  '"': '&quot;',
                  '\'': '&#39;',
                  '/': '&#47;'
              };

              // Do not try to escape the markup if it's not a string
              if (typeof markup !== 'string') {
                  return markup;
              }

              return String(markup).replace(/[&<>"'\/\\]/g, function (match) {
                  return replaceMap[match];
              });
          };

          // Append an array of jQuery nodes to a given element.
          Utils.appendMany = function ($element, $nodes) {
              // jQuery 1.7.x does not support $.fn.append() with an array
              // Fall back to a jQuery object collection using $.fn.add()
              if ($.fn.jquery.substr(0, 3) === '1.7') {
                  var $jqNodes = $();

                  $.map($nodes, function (node) {
                      $jqNodes = $jqNodes.add(node);
                  });

                  $nodes = $jqNodes;
              }

              $element.append($nodes);
          };

          return Utils;
      });

      S2.define('select2/results', [
        'jquery',
        './utils'
      ], function ($, Utils) {
          function Results($element, options, dataAdapter) {
              this.$element = $element;
              this.data = dataAdapter;
              this.options = options;

              Results.__super__.constructor.call(this);
          }

          Utils.Extend(Results, Utils.Observable);

          Results.prototype.render = function () {
              var $results = $(
                '<ul class="select2-results__options" role="tree"></ul>'
              );

              if (this.options.get('multiple')) {
                  $results.attr('aria-multiselectable', 'true');
              }

              this.$results = $results;

              return $results;
          };

          Results.prototype.clear = function () {
              this.$results.empty();
          };

          Results.prototype.displayMessage = function (params) {
              var escapeMarkup = this.options.get('escapeMarkup');

              this.clear();
              this.hideLoading();

              var $message = $(
                '<li role="treeitem" class="select2-results__option"></li>'
              );

              var message = this.options.get('translations').get(params.message);

              $message.append(
                escapeMarkup(
                  message(params.args)
                )
              );

              this.$results.append($message);
          };

          Results.prototype.append = function (data) {
              this.hideLoading();

              var $options = [];

              if (data.results == null || data.results.length === 0) {
                  if (this.$results.children().length === 0) {
                      this.trigger('results:message', {
                          message: 'noResults'
                      });
                  }

                  return;
              }

              data.results = this.sort(data.results);

              for (var d = 0; d < data.results.length; d++) {
                  var item = data.results[d];

                  var $option = this.option(item);

                  $options.push($option);
              }

              this.$results.append($options);
          };

          Results.prototype.position = function ($results, $dropdown) {
              var $resultsContainer = $dropdown.find('.select2-results');
              $resultsContainer.append($results);
          };

          Results.prototype.sort = function (data) {
              var sorter = this.options.get('sorter');

              return sorter(data);
          };

          Results.prototype.setClasses = function () {
              var self = this;

              this.data.current(function (selected) {
                  var selectedIds = $.map(selected, function (s) {
                      return s.id.toString();
                  });

                  var $options = self.$results
                    .find('.select2-results__option[aria-selected]');

                  $options.each(function () {
                      var $option = $(this);

                      var item = $.data(this, 'data');

                      // id needs to be converted to a string when comparing
                      var id = '' + item.id;

                      if ((item.element != null && item.element.selected) ||
                          (item.element == null && $.inArray(id, selectedIds) > -1)) {
                          $option.attr('aria-selected', 'true');
                      } else {
                          $option.attr('aria-selected', 'false');
                      }
                  });

                  var $selected = $options.filter('[aria-selected=true]');

                  // Check if there are any selected options
                  if ($selected.length > 0) {
                      // If there are selected options, highlight the first
                      $selected.first().trigger('mouseenter');
                  } else {
                      // If there are no selected options, highlight the first option
                      // in the dropdown
                      $options.first().trigger('mouseenter');
                  }
              });
          };

          Results.prototype.showLoading = function (params) {
              this.hideLoading();

              var loadingMore = this.options.get('translations').get('searching');

              var loading = {
                  disabled: true,
                  loading: true,
                  text: loadingMore(params)
              };
              var $loading = this.option(loading);
              $loading.className += ' loading-results';

              this.$results.prepend($loading);
          };

          Results.prototype.hideLoading = function () {
              this.$results.find('.loading-results').remove();
          };

          Results.prototype.option = function (data) {
              var option = document.createElement('li');
              option.className = 'select2-results__option';

              var attrs = {
                  'role': 'treeitem',
                  'aria-selected': 'false'
              };

              if (data.disabled) {
                  delete attrs['aria-selected'];
                  attrs['aria-disabled'] = 'true';
              }

              if (data.id == null) {
                  delete attrs['aria-selected'];
              }

              if (data._resultId != null) {
                  option.id = data._resultId;
              }

              if (data.title) {
                  option.title = data.title;
              }

              if (data.children) {
                  attrs.role = 'group';
                  attrs['aria-label'] = data.text;
                  delete attrs['aria-selected'];
              }

              for (var attr in attrs) {
                  var val = attrs[attr];

                  option.setAttribute(attr, val);
              }

              if (data.children) {
                  var $option = $(option);

                  var label = document.createElement('strong');
                  label.className = 'select2-results__group';

                  var $label = $(label);
                  this.template(data, label);

                  var $children = [];

                  for (var c = 0; c < data.children.length; c++) {
                      var child = data.children[c];

                      var $child = this.option(child);

                      $children.push($child);
                  }

                  var $childrenContainer = $('<ul></ul>', {
                      'class': 'select2-results__options select2-results__options--nested'
                  });

                  $childrenContainer.append($children);

                  $option.append(label);
                  $option.append($childrenContainer);
              } else {
                  this.template(data, option);
              }

              $.data(option, 'data', data);

              return option;
          };

          Results.prototype.bind = function (container, $container) {
              var self = this;

              var id = container.id + '-results';

              this.$results.attr('id', id);

              container.on('results:all', function (params) {
                  self.clear();
                  self.append(params.data);

                  if (container.isOpen()) {
                      self.setClasses();
                  }
              });

              container.on('results:append', function (params) {
                  self.append(params.data);

                  if (container.isOpen()) {
                      self.setClasses();
                  }
              });

              container.on('query', function (params) {
                  self.showLoading(params);
              });

              container.on('select', function () {
                  if (!container.isOpen()) {
                      return;
                  }

                  self.setClasses();
              });

              container.on('unselect', function () {
                  if (!container.isOpen()) {
                      return;
                  }

                  self.setClasses();
              });

              container.on('open', function () {
                  // When the dropdown is open, aria-expended="true"
                  self.$results.attr('aria-expanded', 'true');
                  self.$results.attr('aria-hidden', 'false');

                  self.setClasses();
                  self.ensureHighlightVisible();
              });

              container.on('close', function () {
                  // When the dropdown is closed, aria-expended="false"
                  self.$results.attr('aria-expanded', 'false');
                  self.$results.attr('aria-hidden', 'true');
                  self.$results.removeAttr('aria-activedescendant');
              });

              container.on('results:toggle', function () {
                  var $highlighted = self.getHighlightedResults();

                  if ($highlighted.length === 0) {
                      return;
                  }

                  $highlighted.trigger('mouseup');
              });

              container.on('results:select', function () {
                  var $highlighted = self.getHighlightedResults();

                  if ($highlighted.length === 0) {
                      return;
                  }

                  var data = $highlighted.data('data');

                  if ($highlighted.attr('aria-selected') == 'true') {
                      self.trigger('close');
                  } else {
                      self.trigger('select', {
                          data: data
                      });
                  }
              });

              container.on('results:previous', function () {
                  var $highlighted = self.getHighlightedResults();

                  var $options = self.$results.find('[aria-selected]');

                  var currentIndex = $options.index($highlighted);

                  // If we are already at te top, don't move further
                  if (currentIndex === 0) {
                      return;
                  }

                  var nextIndex = currentIndex - 1;

                  // If none are highlighted, highlight the first
                  if ($highlighted.length === 0) {
                      nextIndex = 0;
                  }

                  var $next = $options.eq(nextIndex);

                  $next.trigger('mouseenter');

                  var currentOffset = self.$results.offset().top;
                  var nextTop = $next.offset().top;
                  var nextOffset = self.$results.scrollTop() + (nextTop - currentOffset);

                  if (nextIndex === 0) {
                      self.$results.scrollTop(0);
                  } else if (nextTop - currentOffset < 0) {
                      self.$results.scrollTop(nextOffset);
                  }
              });

              container.on('results:next', function () {
                  var $highlighted = self.getHighlightedResults();

                  var $options = self.$results.find('[aria-selected]');

                  var currentIndex = $options.index($highlighted);

                  var nextIndex = currentIndex + 1;

                  // If we are at the last option, stay there
                  if (nextIndex >= $options.length) {
                      return;
                  }

                  var $next = $options.eq(nextIndex);

                  $next.trigger('mouseenter');

                  var currentOffset = self.$results.offset().top +
                    self.$results.outerHeight(false);
                  var nextBottom = $next.offset().top + $next.outerHeight(false);
                  var nextOffset = self.$results.scrollTop() + nextBottom - currentOffset;

                  if (nextIndex === 0) {
                      self.$results.scrollTop(0);
                  } else if (nextBottom > currentOffset) {
                      self.$results.scrollTop(nextOffset);
                  }
              });

              container.on('results:focus', function (params) {
                  params.element.addClass('select2-results__option--highlighted');
              });

              container.on('results:message', function (params) {
                  self.displayMessage(params);
              });

              if ($.fn.mousewheel) {
                  this.$results.on('mousewheel', function (e) {
                      var top = self.$results.scrollTop();

                      var bottom = (
                        self.$results.get(0).scrollHeight -
                        self.$results.scrollTop() +
                        e.deltaY
                      );

                      var isAtTop = e.deltaY > 0 && top - e.deltaY <= 0;
                      var isAtBottom = e.deltaY < 0 && bottom <= self.$results.height();

                      if (isAtTop) {
                          self.$results.scrollTop(0);

                          e.preventDefault();
                          e.stopPropagation();
                      } else if (isAtBottom) {
                          self.$results.scrollTop(
                            self.$results.get(0).scrollHeight - self.$results.height()
                          );

                          e.preventDefault();
                          e.stopPropagation();
                      }
                  });
              }

              this.$results.on('mouseup', '.select2-results__option[aria-selected]',
                function (evt) {
                    var $this = $(this);

                    var data = $this.data('data');

                    if ($this.attr('aria-selected') === 'true') {
                        if (self.options.get('multiple')) {
                            self.trigger('unselect', {
                                originalEvent: evt,
                                data: data
                            });
                        } else {
                            self.trigger('close');
                        }

                        return;
                    }

                    self.trigger('select', {
                        originalEvent: evt,
                        data: data
                    });
                });

              this.$results.on('mouseenter', '.select2-results__option[aria-selected]',
                function (evt) {
                    var data = $(this).data('data');

                    self.getHighlightedResults()
                        .removeClass('select2-results__option--highlighted');

                    self.trigger('results:focus', {
                        data: data,
                        element: $(this)
                    });
                });
          };

          Results.prototype.getHighlightedResults = function () {
              var $highlighted = this.$results
              .find('.select2-results__option--highlighted');

              return $highlighted;
          };

          Results.prototype.destroy = function () {
              this.$results.remove();
          };

          Results.prototype.ensureHighlightVisible = function () {
              var $highlighted = this.getHighlightedResults();

              if ($highlighted.length === 0) {
                  return;
              }

              var $options = this.$results.find('[aria-selected]');

              var currentIndex = $options.index($highlighted);

              var currentOffset = this.$results.offset().top;
              var nextTop = $highlighted.offset().top;
              var nextOffset = this.$results.scrollTop() + (nextTop - currentOffset);

              var offsetDelta = nextTop - currentOffset;
              nextOffset -= $highlighted.outerHeight(false) * 2;

              if (currentIndex <= 2) {
                  this.$results.scrollTop(0);
              } else if (offsetDelta > this.$results.outerHeight() || offsetDelta < 0) {
                  this.$results.scrollTop(nextOffset);
              }
          };

          Results.prototype.template = function (result, container) {
              var template = this.options.get('templateResult');
              var escapeMarkup = this.options.get('escapeMarkup');

              var content = template(result);

              if (content == null) {
                  container.style.display = 'none';
              } else if (typeof content === 'string') {
                  container.innerHTML = escapeMarkup(content);
              } else {
                  $(container).append(content);
              }
          };

          return Results;
      });

      S2.define('select2/keys', [

      ], function () {
          var KEYS = {
              BACKSPACE: 8,
              TAB: 9,
              ENTER: 13,
              SHIFT: 16,
              CTRL: 17,
              ALT: 18,
              ESC: 27,
              SPACE: 32,
              PAGE_UP: 33,
              PAGE_DOWN: 34,
              END: 35,
              HOME: 36,
              LEFT: 37,
              UP: 38,
              RIGHT: 39,
              DOWN: 40,
              DELETE: 46
          };

          return KEYS;
      });

      S2.define('select2/selection/base', [
        'jquery',
        '../utils',
        '../keys'
      ], function ($, Utils, KEYS) {
          function BaseSelection($element, options) {
              this.$element = $element;
              this.options = options;

              BaseSelection.__super__.constructor.call(this);
          }

          Utils.Extend(BaseSelection, Utils.Observable);

          BaseSelection.prototype.render = function () {
              var $selection = $(
                '<span class="select2-selection" role="combobox" ' +
                'aria-autocomplete="list" aria-haspopup="true" aria-expanded="false">' +
                '</span>'
              );

              this._tabindex = 0;

              if (this.$element.data('old-tabindex') != null) {
                  this._tabindex = this.$element.data('old-tabindex');
              } else if (this.$element.attr('tabindex') != null) {
                  this._tabindex = this.$element.attr('tabindex');
              }

              $selection.attr('title', this.$element.attr('title'));
              $selection.attr('tabindex', this._tabindex);

              this.$selection = $selection;

              return $selection;
          };

          BaseSelection.prototype.bind = function (container, $container) {
              var self = this;

              var id = container.id + '-container';
              var resultsId = container.id + '-results';

              this.container = container;

              this.$selection.on('focus', function (evt) {
                  self.trigger('focus', evt);
              });

              this.$selection.on('blur', function (evt) {
                  self._handleBlur(evt);
              });

              this.$selection.on('keydown', function (evt) {
                  self.trigger('keypress', evt);

                  if (evt.which === KEYS.SPACE) {
                      evt.preventDefault();
                  }
              });

              container.on('results:focus', function (params) {
                  self.$selection.attr('aria-activedescendant', params.data._resultId);
              });

              container.on('selection:update', function (params) {
                  self.update(params.data);
              });

              container.on('open', function () {
                  // When the dropdown is open, aria-expanded="true"
                  self.$selection.attr('aria-expanded', 'true');
                  self.$selection.attr('aria-owns', resultsId);

                  self._attachCloseHandler(container);
              });

              container.on('close', function () {
                  // When the dropdown is closed, aria-expanded="false"
                  self.$selection.attr('aria-expanded', 'false');
                  self.$selection.removeAttr('aria-activedescendant');
                  self.$selection.removeAttr('aria-owns');

                  self.$selection.focus();

                  self._detachCloseHandler(container);
              });

              container.on('enable', function () {
                  self.$selection.attr('tabindex', self._tabindex);
              });

              container.on('disable', function () {
                  self.$selection.attr('tabindex', '-1');
              });
          };

          BaseSelection.prototype._handleBlur = function (evt) {
              var self = this;

              // This needs to be delayed as the actve element is the body when the tab
              // key is pressed, possibly along with others.
              window.setTimeout(function () {
                  // Don't trigger `blur` if the focus is still in the selection
                  if (
                    (document.activeElement == self.$selection[0]) ||
                    ($.contains(self.$selection[0], document.activeElement))
                  ) {
                      return;
                  }

                  self.trigger('blur', evt);
              }, 1);
          };

          BaseSelection.prototype._attachCloseHandler = function (container) {
              var self = this;

              $(document.body).on('mousedown.select2.' + container.id, function (e) {
                  var $target = $(e.target);

                  var $select = $target.closest('.select2');

                  var $all = $('.select2.select2-container--open');

                  $all.each(function () {
                      var $this = $(this);

                      if (this == $select[0]) {
                          return;
                      }

                      var $element = $this.data('element');

                      $element.select2('close');
                  });
              });
          };

          BaseSelection.prototype._detachCloseHandler = function (container) {
              $(document.body).off('mousedown.select2.' + container.id);
          };

          BaseSelection.prototype.position = function ($selection, $container) {
              var $selectionContainer = $container.find('.selection');
              $selectionContainer.append($selection);
          };

          BaseSelection.prototype.destroy = function () {
              this._detachCloseHandler(this.container);
          };

          BaseSelection.prototype.update = function (data) {
              throw new Error('The `update` method must be defined in child classes.');
          };

          return BaseSelection;
      });

      S2.define('select2/selection/single', [
        'jquery',
        './base',
        '../utils',
        '../keys'
      ], function ($, BaseSelection, Utils, KEYS) {
          function SingleSelection() {
              SingleSelection.__super__.constructor.apply(this, arguments);
          }

          Utils.Extend(SingleSelection, BaseSelection);

          SingleSelection.prototype.render = function () {
              var $selection = SingleSelection.__super__.render.call(this);

              $selection.addClass('select2-selection--single');

              $selection.html(
                '<span class="select2-selection__rendered"></span>' +
                '<span class="select2-selection__arrow" role="presentation">' +
                  '<b role="presentation"></b>' +
                '</span>'
              );

              return $selection;
          };

          SingleSelection.prototype.bind = function (container, $container) {
              var self = this;

              SingleSelection.__super__.bind.apply(this, arguments);

              var id = container.id + '-container';

              this.$selection.find('.select2-selection__rendered').attr('id', id);
              this.$selection.attr('aria-labelledby', id);

              this.$selection.on('mousedown', function (evt) {
                  // Only respond to left clicks
                  if (evt.which !== 1) {
                      return;
                  }

                  self.trigger('toggle', {
                      originalEvent: evt
                  });
              });

              this.$selection.on('focus', function (evt) {
                  // User focuses on the container
              });

              this.$selection.on('blur', function (evt) {
                  // User exits the container
              });

              container.on('selection:update', function (params) {
                  self.update(params.data);
              });
          };

          SingleSelection.prototype.clear = function () {
              this.$selection.find('.select2-selection__rendered').empty();
          };

          SingleSelection.prototype.display = function (data, container) {
              var template = this.options.get('templateSelection');
              var escapeMarkup = this.options.get('escapeMarkup');

              return escapeMarkup(template(data, container));
          };

          SingleSelection.prototype.selectionContainer = function () {
              return $('<span></span>');
          };

          SingleSelection.prototype.update = function (data) {
              if (data.length === 0) {
                  this.clear();
                  return;
              }

              var selection = data[0];

              var $rendered = this.$selection.find('.select2-selection__rendered');
              var formatted = this.display(selection, $rendered);

              $rendered.empty().append(formatted);
              $rendered.prop('title', selection.title || selection.text);
          };

          return SingleSelection;
      });

      S2.define('select2/selection/multiple', [
        'jquery',
        './base',
        '../utils'
      ], function ($, BaseSelection, Utils) {
          function MultipleSelection($element, options) {
              MultipleSelection.__super__.constructor.apply(this, arguments);
          }

          Utils.Extend(MultipleSelection, BaseSelection);

          MultipleSelection.prototype.render = function () {
              var $selection = MultipleSelection.__super__.render.call(this);

              $selection.addClass('select2-selection--multiple');

              $selection.html(
                '<ul class="select2-selection__rendered"></ul>'
              );

              return $selection;
          };

          MultipleSelection.prototype.bind = function (container, $container) {
              var self = this;

              MultipleSelection.__super__.bind.apply(this, arguments);

              this.$selection.on('click', function (evt) {
                  self.trigger('toggle', {
                      originalEvent: evt
                  });
              });

              this.$selection.on('click', '.select2-selection__choice__remove',
                function (evt) {
                    var $remove = $(this);
                    var $selection = $remove.parent();

                    var data = $selection.data('data');

                    self.trigger('unselect', {
                        originalEvent: evt,
                        data: data
                    });
                });
          };

          MultipleSelection.prototype.clear = function () {
              this.$selection.find('.select2-selection__rendered').empty();
          };

          MultipleSelection.prototype.display = function (data, container) {
              var template = this.options.get('templateSelection');
              var escapeMarkup = this.options.get('escapeMarkup');

              return escapeMarkup(template(data, container));
          };

          MultipleSelection.prototype.selectionContainer = function () {
              var $container = $(
                '<li class="select2-selection__choice">' +
                  '<span class="select2-selection__choice__remove" role="presentation">' +
                    '&times;' +
                  '</span>' +
                '</li>'
              );

              return $container;
          };

          MultipleSelection.prototype.update = function (data) {
              this.clear();

              if (data.length === 0) {
                  return;
              }

              var $selections = [];

              for (var d = 0; d < data.length; d++) {
                  var selection = data[d];

                  var $selection = this.selectionContainer();
                  var formatted = this.display(selection, $selection);

                  $selection.append(formatted);
                  $selection.prop('title', selection.title || selection.text);

                  $selection.data('data', selection);

                  $selections.push($selection);
              }

              var $rendered = this.$selection.find('.select2-selection__rendered');

              Utils.appendMany($rendered, $selections);
          };

          return MultipleSelection;
      });

      S2.define('select2/selection/placeholder', [
        '../utils'
      ], function (Utils) {
          function Placeholder(decorated, $element, options) {
              this.placeholder = this.normalizePlaceholder(options.get('placeholder'));

              decorated.call(this, $element, options);
          }

          Placeholder.prototype.normalizePlaceholder = function (_, placeholder) {
              if (typeof placeholder === 'string') {
                  placeholder = {
                      id: '',
                      text: placeholder
                  };
              }

              return placeholder;
          };

          Placeholder.prototype.createPlaceholder = function (decorated, placeholder) {
              var $placeholder = this.selectionContainer();

              $placeholder.html(this.display(placeholder));
              $placeholder.addClass('select2-selection__placeholder')
                          .removeClass('select2-selection__choice');

              return $placeholder;
          };

          Placeholder.prototype.update = function (decorated, data) {
              var singlePlaceholder = (
                data.length == 1 && data[0].id != this.placeholder.id
              );
              var multipleSelections = data.length > 1;

              if (multipleSelections || singlePlaceholder) {
                  return decorated.call(this, data);
              }

              this.clear();

              var $placeholder = this.createPlaceholder(this.placeholder);

              this.$selection.find('.select2-selection__rendered').append($placeholder);
          };

          return Placeholder;
      });

      S2.define('select2/selection/allowClear', [
        'jquery',
        '../keys'
      ], function ($, KEYS) {
          function AllowClear() { }

          AllowClear.prototype.bind = function (decorated, container, $container) {
              var self = this;

              decorated.call(this, container, $container);

              if (this.placeholder == null) {
                  if (this.options.get('debug') && window.console && console.error) {
                      console.error(
                        'Select2: The `allowClear` option should be used in combination ' +
                        'with the `placeholder` option.'
                      );
                  }
              }

              this.$selection.on('mousedown', '.select2-selection__clear',
                function (evt) {
                    self._handleClear(evt);
                });

              container.on('keypress', function (evt) {
                  self._handleKeyboardClear(evt, container);
              });
          };

          AllowClear.prototype._handleClear = function (_, evt) {
              // Ignore the event if it is disabled
              if (this.options.get('disabled')) {
                  return;
              }

              var $clear = this.$selection.find('.select2-selection__clear');

              // Ignore the event if nothing has been selected
              if ($clear.length === 0) {
                  return;
              }

              evt.stopPropagation();

              var data = $clear.data('data');

              for (var d = 0; d < data.length; d++) {
                  var unselectData = {
                      data: data[d]
                  };

                  // Trigger the `unselect` event, so people can prevent it from being
                  // cleared.
                  this.trigger('unselect', unselectData);

                  // If the event was prevented, don't clear it out.
                  if (unselectData.prevented) {
                      return;
                  }
              }

              this.$element.val(this.placeholder.id).trigger('change');

              this.trigger('toggle');
          };

          AllowClear.prototype._handleKeyboardClear = function (_, evt, container) {
              if (container.isOpen()) {
                  return;
              }

              if (evt.which == KEYS.DELETE || evt.which == KEYS.BACKSPACE) {
                  this._handleClear(evt);
              }
          };

          AllowClear.prototype.update = function (decorated, data) {
              decorated.call(this, data);

              if (this.$selection.find('.select2-selection__placeholder').length > 0 ||
                  data.length === 0) {
                  return;
              }

              var $remove = $(
                '<span class="select2-selection__clear">' +
                  '&times;' +
                '</span>'
              );
              $remove.data('data', data);

              this.$selection.find('.select2-selection__rendered').prepend($remove);
          };

          return AllowClear;
      });

      S2.define('select2/selection/search', [
        'jquery',
        '../utils',
        '../keys'
      ], function ($, Utils, KEYS) {
          function Search(decorated, $element, options) {
              decorated.call(this, $element, options);
          }

          Search.prototype.render = function (decorated) {
              var $search = $(
                '<li class="select2-search select2-search--inline">' +
                  '<input class="select2-search__field" type="search" tabindex="-1"' +
                  ' autocomplete="off" autocorrect="off" autocapitalize="off"' +
                  ' spellcheck="false" role="textbox" />' +
                '</li>'
              );

              this.$searchContainer = $search;
              this.$search = $search.find('input');

              var $rendered = decorated.call(this);

              this._transferTabIndex();

              return $rendered;
          };

          Search.prototype.bind = function (decorated, container, $container) {
              var self = this;

              decorated.call(this, container, $container);

              container.on('open', function () {
                  self.$search.trigger('focus');
              });

              container.on('close', function () {
                  self.$search.val('');
                  self.$search.trigger('focus');
              });

              container.on('enable', function () {
                  self.$search.prop('disabled', false);

                  self._transferTabIndex();
              });

              container.on('disable', function () {
                  self.$search.prop('disabled', true);
              });

              container.on('focus', function (evt) {
                  self.$search.trigger('focus');
              });

              this.$selection.on('focusin', '.select2-search--inline', function (evt) {
                  self.trigger('focus', evt);
              });

              this.$selection.on('focusout', '.select2-search--inline', function (evt) {
                  self._handleBlur(evt);
              });

              this.$selection.on('keydown', '.select2-search--inline', function (evt) {
                  evt.stopPropagation();

                  self.trigger('keypress', evt);

                  self._keyUpPrevented = evt.isDefaultPrevented();

                  var key = evt.which;

                  if (key === KEYS.BACKSPACE && self.$search.val() === '') {
                      var $previousChoice = self.$searchContainer
                        .prev('.select2-selection__choice');

                      if ($previousChoice.length > 0) {
                          var item = $previousChoice.data('data');

                          self.searchRemoveChoice(item);

                          evt.preventDefault();
                      }
                  }
              });

              // Workaround for browsers which do not support the `input` event
              // This will prevent double-triggering of events for browsers which support
              // both the `keyup` and `input` events.
              this.$selection.on('input', '.select2-search--inline', function (evt) {
                  // Unbind the duplicated `keyup` event
                  self.$selection.off('keyup.search');
              });

              this.$selection.on('keyup.search input', '.select2-search--inline',
                  function (evt) {
                      var key = evt.which;

                      // We can freely ignore events from modifier keys
                      if (key == KEYS.SHIFT || key == KEYS.CTRL || key == KEYS.ALT) {
                          return;
                      }

                      // Tabbing will be handled during the `keydown` phase
                      if (key == KEYS.TAB) {
                          return;
                      }

                      self.handleSearch(evt);
                  });
          };

          /**
           * This method will transfer the tabindex attribute from the rendered
           * selection to the search box. This allows for the search box to be used as
           * the primary focus instead of the selection container.
           *
           * @private
           */
          Search.prototype._transferTabIndex = function (decorated) {
              this.$search.attr('tabindex', this.$selection.attr('tabindex'));
              this.$selection.attr('tabindex', '-1');
          };

          Search.prototype.createPlaceholder = function (decorated, placeholder) {
              this.$search.attr('placeholder', placeholder.text);
          };

          Search.prototype.update = function (decorated, data) {
              var searchHadFocus = this.$search[0] == document.activeElement;

              this.$search.attr('placeholder', '');

              decorated.call(this, data);

              this.$selection.find('.select2-selection__rendered')
                             .append(this.$searchContainer);

              this.resizeSearch();
              if (searchHadFocus) {
                  this.$search.focus();
              }
          };

          Search.prototype.handleSearch = function () {
              this.resizeSearch();

              if (!this._keyUpPrevented) {
                  var input = this.$search.val();

                  this.trigger('query', {
                      term: input
                  });
              }

              this._keyUpPrevented = false;
          };

          Search.prototype.searchRemoveChoice = function (decorated, item) {
              this.trigger('unselect', {
                  data: item
              });

              this.trigger('open');

              this.$search.val(item.text + ' ');
          };

          Search.prototype.resizeSearch = function () {
              this.$search.css('width', '25px');

              var width = '';

              if (this.$search.attr('placeholder') !== '') {
                  width = this.$selection.find('.select2-selection__rendered').innerWidth();
              } else {
                  var minimumWidth = this.$search.val().length + 1;

                  width = (minimumWidth * 0.75) + 'em';
              }

              this.$search.css('width', width);
          };

          return Search;
      });

      S2.define('select2/selection/eventRelay', [
        'jquery'
      ], function ($) {
          function EventRelay() { }

          EventRelay.prototype.bind = function (decorated, container, $container) {
              var self = this;
              var relayEvents = [
                'open', 'opening',
                'close', 'closing',
                'select', 'selecting',
                'unselect', 'unselecting'
              ];

              var preventableEvents = ['opening', 'closing', 'selecting', 'unselecting'];

              decorated.call(this, container, $container);

              container.on('*', function (name, params) {
                  // Ignore events that should not be relayed
                  if ($.inArray(name, relayEvents) === -1) {
                      return;
                  }

                  // The parameters should always be an object
                  params = params || {};

                  // Generate the jQuery event for the Select2 event
                  var evt = $.Event('select2:' + name, {
                      params: params
                  });

                  self.$element.trigger(evt);

                  // Only handle preventable events if it was one
                  if ($.inArray(name, preventableEvents) === -1) {
                      return;
                  }

                  params.prevented = evt.isDefaultPrevented();
              });
          };

          return EventRelay;
      });

      S2.define('select2/translation', [
        'jquery',
        'require'
      ], function ($, require) {
          function Translation(dict) {
              this.dict = dict || {};
          }

          Translation.prototype.all = function () {
              return this.dict;
          };

          Translation.prototype.get = function (key) {
              return this.dict[key];
          };

          Translation.prototype.extend = function (translation) {
              this.dict = $.extend({}, translation.all(), this.dict);
          };

          // Static functions

          Translation._cache = {};

          Translation.loadPath = function (path) {
              if (!(path in Translation._cache)) {
                  var translations = require(path);

                  Translation._cache[path] = translations;
              }

              return new Translation(Translation._cache[path]);
          };

          return Translation;
      });

      S2.define('select2/diacritics', [

      ], function () {
          var diacritics = {
              '\u24B6': 'A',
              '\uFF21': 'A',
              '\u00C0': 'A',
              '\u00C1': 'A',
              '\u00C2': 'A',
              '\u1EA6': 'A',
              '\u1EA4': 'A',
              '\u1EAA': 'A',
              '\u1EA8': 'A',
              '\u00C3': 'A',
              '\u0100': 'A',
              '\u0102': 'A',
              '\u1EB0': 'A',
              '\u1EAE': 'A',
              '\u1EB4': 'A',
              '\u1EB2': 'A',
              '\u0226': 'A',
              '\u01E0': 'A',
              '\u00C4': 'A',
              '\u01DE': 'A',
              '\u1EA2': 'A',
              '\u00C5': 'A',
              '\u01FA': 'A',
              '\u01CD': 'A',
              '\u0200': 'A',
              '\u0202': 'A',
              '\u1EA0': 'A',
              '\u1EAC': 'A',
              '\u1EB6': 'A',
              '\u1E00': 'A',
              '\u0104': 'A',
              '\u023A': 'A',
              '\u2C6F': 'A',
              '\uA732': 'AA',
              '\u00C6': 'AE',
              '\u01FC': 'AE',
              '\u01E2': 'AE',
              '\uA734': 'AO',
              '\uA736': 'AU',
              '\uA738': 'AV',
              '\uA73A': 'AV',
              '\uA73C': 'AY',
              '\u24B7': 'B',
              '\uFF22': 'B',
              '\u1E02': 'B',
              '\u1E04': 'B',
              '\u1E06': 'B',
              '\u0243': 'B',
              '\u0182': 'B',
              '\u0181': 'B',
              '\u24B8': 'C',
              '\uFF23': 'C',
              '\u0106': 'C',
              '\u0108': 'C',
              '\u010A': 'C',
              '\u010C': 'C',
              '\u00C7': 'C',
              '\u1E08': 'C',
              '\u0187': 'C',
              '\u023B': 'C',
              '\uA73E': 'C',
              '\u24B9': 'D',
              '\uFF24': 'D',
              '\u1E0A': 'D',
              '\u010E': 'D',
              '\u1E0C': 'D',
              '\u1E10': 'D',
              '\u1E12': 'D',
              '\u1E0E': 'D',
              '\u0110': 'D',
              '\u018B': 'D',
              '\u018A': 'D',
              '\u0189': 'D',
              '\uA779': 'D',
              '\u01F1': 'DZ',
              '\u01C4': 'DZ',
              '\u01F2': 'Dz',
              '\u01C5': 'Dz',
              '\u24BA': 'E',
              '\uFF25': 'E',
              '\u00C8': 'E',
              '\u00C9': 'E',
              '\u00CA': 'E',
              '\u1EC0': 'E',
              '\u1EBE': 'E',
              '\u1EC4': 'E',
              '\u1EC2': 'E',
              '\u1EBC': 'E',
              '\u0112': 'E',
              '\u1E14': 'E',
              '\u1E16': 'E',
              '\u0114': 'E',
              '\u0116': 'E',
              '\u00CB': 'E',
              '\u1EBA': 'E',
              '\u011A': 'E',
              '\u0204': 'E',
              '\u0206': 'E',
              '\u1EB8': 'E',
              '\u1EC6': 'E',
              '\u0228': 'E',
              '\u1E1C': 'E',
              '\u0118': 'E',
              '\u1E18': 'E',
              '\u1E1A': 'E',
              '\u0190': 'E',
              '\u018E': 'E',
              '\u24BB': 'F',
              '\uFF26': 'F',
              '\u1E1E': 'F',
              '\u0191': 'F',
              '\uA77B': 'F',
              '\u24BC': 'G',
              '\uFF27': 'G',
              '\u01F4': 'G',
              '\u011C': 'G',
              '\u1E20': 'G',
              '\u011E': 'G',
              '\u0120': 'G',
              '\u01E6': 'G',
              '\u0122': 'G',
              '\u01E4': 'G',
              '\u0193': 'G',
              '\uA7A0': 'G',
              '\uA77D': 'G',
              '\uA77E': 'G',
              '\u24BD': 'H',
              '\uFF28': 'H',
              '\u0124': 'H',
              '\u1E22': 'H',
              '\u1E26': 'H',
              '\u021E': 'H',
              '\u1E24': 'H',
              '\u1E28': 'H',
              '\u1E2A': 'H',
              '\u0126': 'H',
              '\u2C67': 'H',
              '\u2C75': 'H',
              '\uA78D': 'H',
              '\u24BE': 'I',
              '\uFF29': 'I',
              '\u00CC': 'I',
              '\u00CD': 'I',
              '\u00CE': 'I',
              '\u0128': 'I',
              '\u012A': 'I',
              '\u012C': 'I',
              '\u0130': 'I',
              '\u00CF': 'I',
              '\u1E2E': 'I',
              '\u1EC8': 'I',
              '\u01CF': 'I',
              '\u0208': 'I',
              '\u020A': 'I',
              '\u1ECA': 'I',
              '\u012E': 'I',
              '\u1E2C': 'I',
              '\u0197': 'I',
              '\u24BF': 'J',
              '\uFF2A': 'J',
              '\u0134': 'J',
              '\u0248': 'J',
              '\u24C0': 'K',
              '\uFF2B': 'K',
              '\u1E30': 'K',
              '\u01E8': 'K',
              '\u1E32': 'K',
              '\u0136': 'K',
              '\u1E34': 'K',
              '\u0198': 'K',
              '\u2C69': 'K',
              '\uA740': 'K',
              '\uA742': 'K',
              '\uA744': 'K',
              '\uA7A2': 'K',
              '\u24C1': 'L',
              '\uFF2C': 'L',
              '\u013F': 'L',
              '\u0139': 'L',
              '\u013D': 'L',
              '\u1E36': 'L',
              '\u1E38': 'L',
              '\u013B': 'L',
              '\u1E3C': 'L',
              '\u1E3A': 'L',
              '\u0141': 'L',
              '\u023D': 'L',
              '\u2C62': 'L',
              '\u2C60': 'L',
              '\uA748': 'L',
              '\uA746': 'L',
              '\uA780': 'L',
              '\u01C7': 'LJ',
              '\u01C8': 'Lj',
              '\u24C2': 'M',
              '\uFF2D': 'M',
              '\u1E3E': 'M',
              '\u1E40': 'M',
              '\u1E42': 'M',
              '\u2C6E': 'M',
              '\u019C': 'M',
              '\u24C3': 'N',
              '\uFF2E': 'N',
              '\u01F8': 'N',
              '\u0143': 'N',
              '\u00D1': 'N',
              '\u1E44': 'N',
              '\u0147': 'N',
              '\u1E46': 'N',
              '\u0145': 'N',
              '\u1E4A': 'N',
              '\u1E48': 'N',
              '\u0220': 'N',
              '\u019D': 'N',
              '\uA790': 'N',
              '\uA7A4': 'N',
              '\u01CA': 'NJ',
              '\u01CB': 'Nj',
              '\u24C4': 'O',
              '\uFF2F': 'O',
              '\u00D2': 'O',
              '\u00D3': 'O',
              '\u00D4': 'O',
              '\u1ED2': 'O',
              '\u1ED0': 'O',
              '\u1ED6': 'O',
              '\u1ED4': 'O',
              '\u00D5': 'O',
              '\u1E4C': 'O',
              '\u022C': 'O',
              '\u1E4E': 'O',
              '\u014C': 'O',
              '\u1E50': 'O',
              '\u1E52': 'O',
              '\u014E': 'O',
              '\u022E': 'O',
              '\u0230': 'O',
              '\u00D6': 'O',
              '\u022A': 'O',
              '\u1ECE': 'O',
              '\u0150': 'O',
              '\u01D1': 'O',
              '\u020C': 'O',
              '\u020E': 'O',
              '\u01A0': 'O',
              '\u1EDC': 'O',
              '\u1EDA': 'O',
              '\u1EE0': 'O',
              '\u1EDE': 'O',
              '\u1EE2': 'O',
              '\u1ECC': 'O',
              '\u1ED8': 'O',
              '\u01EA': 'O',
              '\u01EC': 'O',
              '\u00D8': 'O',
              '\u01FE': 'O',
              '\u0186': 'O',
              '\u019F': 'O',
              '\uA74A': 'O',
              '\uA74C': 'O',
              '\u01A2': 'OI',
              '\uA74E': 'OO',
              '\u0222': 'OU',
              '\u24C5': 'P',
              '\uFF30': 'P',
              '\u1E54': 'P',
              '\u1E56': 'P',
              '\u01A4': 'P',
              '\u2C63': 'P',
              '\uA750': 'P',
              '\uA752': 'P',
              '\uA754': 'P',
              '\u24C6': 'Q',
              '\uFF31': 'Q',
              '\uA756': 'Q',
              '\uA758': 'Q',
              '\u024A': 'Q',
              '\u24C7': 'R',
              '\uFF32': 'R',
              '\u0154': 'R',
              '\u1E58': 'R',
              '\u0158': 'R',
              '\u0210': 'R',
              '\u0212': 'R',
              '\u1E5A': 'R',
              '\u1E5C': 'R',
              '\u0156': 'R',
              '\u1E5E': 'R',
              '\u024C': 'R',
              '\u2C64': 'R',
              '\uA75A': 'R',
              '\uA7A6': 'R',
              '\uA782': 'R',
              '\u24C8': 'S',
              '\uFF33': 'S',
              '\u1E9E': 'S',
              '\u015A': 'S',
              '\u1E64': 'S',
              '\u015C': 'S',
              '\u1E60': 'S',
              '\u0160': 'S',
              '\u1E66': 'S',
              '\u1E62': 'S',
              '\u1E68': 'S',
              '\u0218': 'S',
              '\u015E': 'S',
              '\u2C7E': 'S',
              '\uA7A8': 'S',
              '\uA784': 'S',
              '\u24C9': 'T',
              '\uFF34': 'T',
              '\u1E6A': 'T',
              '\u0164': 'T',
              '\u1E6C': 'T',
              '\u021A': 'T',
              '\u0162': 'T',
              '\u1E70': 'T',
              '\u1E6E': 'T',
              '\u0166': 'T',
              '\u01AC': 'T',
              '\u01AE': 'T',
              '\u023E': 'T',
              '\uA786': 'T',
              '\uA728': 'TZ',
              '\u24CA': 'U',
              '\uFF35': 'U',
              '\u00D9': 'U',
              '\u00DA': 'U',
              '\u00DB': 'U',
              '\u0168': 'U',
              '\u1E78': 'U',
              '\u016A': 'U',
              '\u1E7A': 'U',
              '\u016C': 'U',
              '\u00DC': 'U',
              '\u01DB': 'U',
              '\u01D7': 'U',
              '\u01D5': 'U',
              '\u01D9': 'U',
              '\u1EE6': 'U',
              '\u016E': 'U',
              '\u0170': 'U',
              '\u01D3': 'U',
              '\u0214': 'U',
              '\u0216': 'U',
              '\u01AF': 'U',
              '\u1EEA': 'U',
              '\u1EE8': 'U',
              '\u1EEE': 'U',
              '\u1EEC': 'U',
              '\u1EF0': 'U',
              '\u1EE4': 'U',
              '\u1E72': 'U',
              '\u0172': 'U',
              '\u1E76': 'U',
              '\u1E74': 'U',
              '\u0244': 'U',
              '\u24CB': 'V',
              '\uFF36': 'V',
              '\u1E7C': 'V',
              '\u1E7E': 'V',
              '\u01B2': 'V',
              '\uA75E': 'V',
              '\u0245': 'V',
              '\uA760': 'VY',
              '\u24CC': 'W',
              '\uFF37': 'W',
              '\u1E80': 'W',
              '\u1E82': 'W',
              '\u0174': 'W',
              '\u1E86': 'W',
              '\u1E84': 'W',
              '\u1E88': 'W',
              '\u2C72': 'W',
              '\u24CD': 'X',
              '\uFF38': 'X',
              '\u1E8A': 'X',
              '\u1E8C': 'X',
              '\u24CE': 'Y',
              '\uFF39': 'Y',
              '\u1EF2': 'Y',
              '\u00DD': 'Y',
              '\u0176': 'Y',
              '\u1EF8': 'Y',
              '\u0232': 'Y',
              '\u1E8E': 'Y',
              '\u0178': 'Y',
              '\u1EF6': 'Y',
              '\u1EF4': 'Y',
              '\u01B3': 'Y',
              '\u024E': 'Y',
              '\u1EFE': 'Y',
              '\u24CF': 'Z',
              '\uFF3A': 'Z',
              '\u0179': 'Z',
              '\u1E90': 'Z',
              '\u017B': 'Z',
              '\u017D': 'Z',
              '\u1E92': 'Z',
              '\u1E94': 'Z',
              '\u01B5': 'Z',
              '\u0224': 'Z',
              '\u2C7F': 'Z',
              '\u2C6B': 'Z',
              '\uA762': 'Z',
              '\u24D0': 'a',
              '\uFF41': 'a',
              '\u1E9A': 'a',
              '\u00E0': 'a',
              '\u00E1': 'a',
              '\u00E2': 'a',
              '\u1EA7': 'a',
              '\u1EA5': 'a',
              '\u1EAB': 'a',
              '\u1EA9': 'a',
              '\u00E3': 'a',
              '\u0101': 'a',
              '\u0103': 'a',
              '\u1EB1': 'a',
              '\u1EAF': 'a',
              '\u1EB5': 'a',
              '\u1EB3': 'a',
              '\u0227': 'a',
              '\u01E1': 'a',
              '\u00E4': 'a',
              '\u01DF': 'a',
              '\u1EA3': 'a',
              '\u00E5': 'a',
              '\u01FB': 'a',
              '\u01CE': 'a',
              '\u0201': 'a',
              '\u0203': 'a',
              '\u1EA1': 'a',
              '\u1EAD': 'a',
              '\u1EB7': 'a',
              '\u1E01': 'a',
              '\u0105': 'a',
              '\u2C65': 'a',
              '\u0250': 'a',
              '\uA733': 'aa',
              '\u00E6': 'ae',
              '\u01FD': 'ae',
              '\u01E3': 'ae',
              '\uA735': 'ao',
              '\uA737': 'au',
              '\uA739': 'av',
              '\uA73B': 'av',
              '\uA73D': 'ay',
              '\u24D1': 'b',
              '\uFF42': 'b',
              '\u1E03': 'b',
              '\u1E05': 'b',
              '\u1E07': 'b',
              '\u0180': 'b',
              '\u0183': 'b',
              '\u0253': 'b',
              '\u24D2': 'c',
              '\uFF43': 'c',
              '\u0107': 'c',
              '\u0109': 'c',
              '\u010B': 'c',
              '\u010D': 'c',
              '\u00E7': 'c',
              '\u1E09': 'c',
              '\u0188': 'c',
              '\u023C': 'c',
              '\uA73F': 'c',
              '\u2184': 'c',
              '\u24D3': 'd',
              '\uFF44': 'd',
              '\u1E0B': 'd',
              '\u010F': 'd',
              '\u1E0D': 'd',
              '\u1E11': 'd',
              '\u1E13': 'd',
              '\u1E0F': 'd',
              '\u0111': 'd',
              '\u018C': 'd',
              '\u0256': 'd',
              '\u0257': 'd',
              '\uA77A': 'd',
              '\u01F3': 'dz',
              '\u01C6': 'dz',
              '\u24D4': 'e',
              '\uFF45': 'e',
              '\u00E8': 'e',
              '\u00E9': 'e',
              '\u00EA': 'e',
              '\u1EC1': 'e',
              '\u1EBF': 'e',
              '\u1EC5': 'e',
              '\u1EC3': 'e',
              '\u1EBD': 'e',
              '\u0113': 'e',
              '\u1E15': 'e',
              '\u1E17': 'e',
              '\u0115': 'e',
              '\u0117': 'e',
              '\u00EB': 'e',
              '\u1EBB': 'e',
              '\u011B': 'e',
              '\u0205': 'e',
              '\u0207': 'e',
              '\u1EB9': 'e',
              '\u1EC7': 'e',
              '\u0229': 'e',
              '\u1E1D': 'e',
              '\u0119': 'e',
              '\u1E19': 'e',
              '\u1E1B': 'e',
              '\u0247': 'e',
              '\u025B': 'e',
              '\u01DD': 'e',
              '\u24D5': 'f',
              '\uFF46': 'f',
              '\u1E1F': 'f',
              '\u0192': 'f',
              '\uA77C': 'f',
              '\u24D6': 'g',
              '\uFF47': 'g',
              '\u01F5': 'g',
              '\u011D': 'g',
              '\u1E21': 'g',
              '\u011F': 'g',
              '\u0121': 'g',
              '\u01E7': 'g',
              '\u0123': 'g',
              '\u01E5': 'g',
              '\u0260': 'g',
              '\uA7A1': 'g',
              '\u1D79': 'g',
              '\uA77F': 'g',
              '\u24D7': 'h',
              '\uFF48': 'h',
              '\u0125': 'h',
              '\u1E23': 'h',
              '\u1E27': 'h',
              '\u021F': 'h',
              '\u1E25': 'h',
              '\u1E29': 'h',
              '\u1E2B': 'h',
              '\u1E96': 'h',
              '\u0127': 'h',
              '\u2C68': 'h',
              '\u2C76': 'h',
              '\u0265': 'h',
              '\u0195': 'hv',
              '\u24D8': 'i',
              '\uFF49': 'i',
              '\u00EC': 'i',
              '\u00ED': 'i',
              '\u00EE': 'i',
              '\u0129': 'i',
              '\u012B': 'i',
              '\u012D': 'i',
              '\u00EF': 'i',
              '\u1E2F': 'i',
              '\u1EC9': 'i',
              '\u01D0': 'i',
              '\u0209': 'i',
              '\u020B': 'i',
              '\u1ECB': 'i',
              '\u012F': 'i',
              '\u1E2D': 'i',
              '\u0268': 'i',
              '\u0131': 'i',
              '\u24D9': 'j',
              '\uFF4A': 'j',
              '\u0135': 'j',
              '\u01F0': 'j',
              '\u0249': 'j',
              '\u24DA': 'k',
              '\uFF4B': 'k',
              '\u1E31': 'k',
              '\u01E9': 'k',
              '\u1E33': 'k',
              '\u0137': 'k',
              '\u1E35': 'k',
              '\u0199': 'k',
              '\u2C6A': 'k',
              '\uA741': 'k',
              '\uA743': 'k',
              '\uA745': 'k',
              '\uA7A3': 'k',
              '\u24DB': 'l',
              '\uFF4C': 'l',
              '\u0140': 'l',
              '\u013A': 'l',
              '\u013E': 'l',
              '\u1E37': 'l',
              '\u1E39': 'l',
              '\u013C': 'l',
              '\u1E3D': 'l',
              '\u1E3B': 'l',
              '\u017F': 'l',
              '\u0142': 'l',
              '\u019A': 'l',
              '\u026B': 'l',
              '\u2C61': 'l',
              '\uA749': 'l',
              '\uA781': 'l',
              '\uA747': 'l',
              '\u01C9': 'lj',
              '\u24DC': 'm',
              '\uFF4D': 'm',
              '\u1E3F': 'm',
              '\u1E41': 'm',
              '\u1E43': 'm',
              '\u0271': 'm',
              '\u026F': 'm',
              '\u24DD': 'n',
              '\uFF4E': 'n',
              '\u01F9': 'n',
              '\u0144': 'n',
              '\u00F1': 'n',
              '\u1E45': 'n',
              '\u0148': 'n',
              '\u1E47': 'n',
              '\u0146': 'n',
              '\u1E4B': 'n',
              '\u1E49': 'n',
              '\u019E': 'n',
              '\u0272': 'n',
              '\u0149': 'n',
              '\uA791': 'n',
              '\uA7A5': 'n',
              '\u01CC': 'nj',
              '\u24DE': 'o',
              '\uFF4F': 'o',
              '\u00F2': 'o',
              '\u00F3': 'o',
              '\u00F4': 'o',
              '\u1ED3': 'o',
              '\u1ED1': 'o',
              '\u1ED7': 'o',
              '\u1ED5': 'o',
              '\u00F5': 'o',
              '\u1E4D': 'o',
              '\u022D': 'o',
              '\u1E4F': 'o',
              '\u014D': 'o',
              '\u1E51': 'o',
              '\u1E53': 'o',
              '\u014F': 'o',
              '\u022F': 'o',
              '\u0231': 'o',
              '\u00F6': 'o',
              '\u022B': 'o',
              '\u1ECF': 'o',
              '\u0151': 'o',
              '\u01D2': 'o',
              '\u020D': 'o',
              '\u020F': 'o',
              '\u01A1': 'o',
              '\u1EDD': 'o',
              '\u1EDB': 'o',
              '\u1EE1': 'o',
              '\u1EDF': 'o',
              '\u1EE3': 'o',
              '\u1ECD': 'o',
              '\u1ED9': 'o',
              '\u01EB': 'o',
              '\u01ED': 'o',
              '\u00F8': 'o',
              '\u01FF': 'o',
              '\u0254': 'o',
              '\uA74B': 'o',
              '\uA74D': 'o',
              '\u0275': 'o',
              '\u01A3': 'oi',
              '\u0223': 'ou',
              '\uA74F': 'oo',
              '\u24DF': 'p',
              '\uFF50': 'p',
              '\u1E55': 'p',
              '\u1E57': 'p',
              '\u01A5': 'p',
              '\u1D7D': 'p',
              '\uA751': 'p',
              '\uA753': 'p',
              '\uA755': 'p',
              '\u24E0': 'q',
              '\uFF51': 'q',
              '\u024B': 'q',
              '\uA757': 'q',
              '\uA759': 'q',
              '\u24E1': 'r',
              '\uFF52': 'r',
              '\u0155': 'r',
              '\u1E59': 'r',
              '\u0159': 'r',
              '\u0211': 'r',
              '\u0213': 'r',
              '\u1E5B': 'r',
              '\u1E5D': 'r',
              '\u0157': 'r',
              '\u1E5F': 'r',
              '\u024D': 'r',
              '\u027D': 'r',
              '\uA75B': 'r',
              '\uA7A7': 'r',
              '\uA783': 'r',
              '\u24E2': 's',
              '\uFF53': 's',
              '\u00DF': 's',
              '\u015B': 's',
              '\u1E65': 's',
              '\u015D': 's',
              '\u1E61': 's',
              '\u0161': 's',
              '\u1E67': 's',
              '\u1E63': 's',
              '\u1E69': 's',
              '\u0219': 's',
              '\u015F': 's',
              '\u023F': 's',
              '\uA7A9': 's',
              '\uA785': 's',
              '\u1E9B': 's',
              '\u24E3': 't',
              '\uFF54': 't',
              '\u1E6B': 't',
              '\u1E97': 't',
              '\u0165': 't',
              '\u1E6D': 't',
              '\u021B': 't',
              '\u0163': 't',
              '\u1E71': 't',
              '\u1E6F': 't',
              '\u0167': 't',
              '\u01AD': 't',
              '\u0288': 't',
              '\u2C66': 't',
              '\uA787': 't',
              '\uA729': 'tz',
              '\u24E4': 'u',
              '\uFF55': 'u',
              '\u00F9': 'u',
              '\u00FA': 'u',
              '\u00FB': 'u',
              '\u0169': 'u',
              '\u1E79': 'u',
              '\u016B': 'u',
              '\u1E7B': 'u',
              '\u016D': 'u',
              '\u00FC': 'u',
              '\u01DC': 'u',
              '\u01D8': 'u',
              '\u01D6': 'u',
              '\u01DA': 'u',
              '\u1EE7': 'u',
              '\u016F': 'u',
              '\u0171': 'u',
              '\u01D4': 'u',
              '\u0215': 'u',
              '\u0217': 'u',
              '\u01B0': 'u',
              '\u1EEB': 'u',
              '\u1EE9': 'u',
              '\u1EEF': 'u',
              '\u1EED': 'u',
              '\u1EF1': 'u',
              '\u1EE5': 'u',
              '\u1E73': 'u',
              '\u0173': 'u',
              '\u1E77': 'u',
              '\u1E75': 'u',
              '\u0289': 'u',
              '\u24E5': 'v',
              '\uFF56': 'v',
              '\u1E7D': 'v',
              '\u1E7F': 'v',
              '\u028B': 'v',
              '\uA75F': 'v',
              '\u028C': 'v',
              '\uA761': 'vy',
              '\u24E6': 'w',
              '\uFF57': 'w',
              '\u1E81': 'w',
              '\u1E83': 'w',
              '\u0175': 'w',
              '\u1E87': 'w',
              '\u1E85': 'w',
              '\u1E98': 'w',
              '\u1E89': 'w',
              '\u2C73': 'w',
              '\u24E7': 'x',
              '\uFF58': 'x',
              '\u1E8B': 'x',
              '\u1E8D': 'x',
              '\u24E8': 'y',
              '\uFF59': 'y',
              '\u1EF3': 'y',
              '\u00FD': 'y',
              '\u0177': 'y',
              '\u1EF9': 'y',
              '\u0233': 'y',
              '\u1E8F': 'y',
              '\u00FF': 'y',
              '\u1EF7': 'y',
              '\u1E99': 'y',
              '\u1EF5': 'y',
              '\u01B4': 'y',
              '\u024F': 'y',
              '\u1EFF': 'y',
              '\u24E9': 'z',
              '\uFF5A': 'z',
              '\u017A': 'z',
              '\u1E91': 'z',
              '\u017C': 'z',
              '\u017E': 'z',
              '\u1E93': 'z',
              '\u1E95': 'z',
              '\u01B6': 'z',
              '\u0225': 'z',
              '\u0240': 'z',
              '\u2C6C': 'z',
              '\uA763': 'z',
              '\u0386': '\u0391',
              '\u0388': '\u0395',
              '\u0389': '\u0397',
              '\u038A': '\u0399',
              '\u03AA': '\u0399',
              '\u038C': '\u039F',
              '\u038E': '\u03A5',
              '\u03AB': '\u03A5',
              '\u038F': '\u03A9',
              '\u03AC': '\u03B1',
              '\u03AD': '\u03B5',
              '\u03AE': '\u03B7',
              '\u03AF': '\u03B9',
              '\u03CA': '\u03B9',
              '\u0390': '\u03B9',
              '\u03CC': '\u03BF',
              '\u03CD': '\u03C5',
              '\u03CB': '\u03C5',
              '\u03B0': '\u03C5',
              '\u03C9': '\u03C9',
              '\u03C2': '\u03C3'
          };

          return diacritics;
      });

      S2.define('select2/data/base', [
        '../utils'
      ], function (Utils) {
          function BaseAdapter($element, options) {
              BaseAdapter.__super__.constructor.call(this);
          }

          Utils.Extend(BaseAdapter, Utils.Observable);

          BaseAdapter.prototype.current = function (callback) {
              throw new Error('The `current` method must be defined in child classes.');
          };

          BaseAdapter.prototype.query = function (params, callback) {
              throw new Error('The `query` method must be defined in child classes.');
          };

          BaseAdapter.prototype.bind = function (container, $container) {
              // Can be implemented in subclasses
          };

          BaseAdapter.prototype.destroy = function () {
              // Can be implemented in subclasses
          };

          BaseAdapter.prototype.generateResultId = function (container, data) {
              var id = container.id + '-result-';

              id += Utils.generateChars(4);

              if (data.id != null) {
                  id += '-' + data.id.toString();
              } else {
                  id += '-' + Utils.generateChars(4);
              }
              return id;
          };

          return BaseAdapter;
      });

      S2.define('select2/data/select', [
        './base',
        '../utils',
        'jquery'
      ], function (BaseAdapter, Utils, $) {
          function SelectAdapter($element, options) {
              this.$element = $element;
              this.options = options;

              SelectAdapter.__super__.constructor.call(this);
          }

          Utils.Extend(SelectAdapter, BaseAdapter);

          SelectAdapter.prototype.current = function (callback) {
              var data = [];
              var self = this;

              this.$element.find(':selected').each(function () {
                  var $option = $(this);

                  var option = self.item($option);

                  data.push(option);
              });

              callback(data);
          };

          SelectAdapter.prototype.select = function (data) {
              var self = this;

              data.selected = true;

              // If data.element is a DOM node, use it instead
              if ($(data.element).is('option')) {
                  data.element.selected = true;

                  this.$element.trigger('change');

                  return;
              }

              if (this.$element.prop('multiple')) {
                  this.current(function (currentData) {
                      var val = [];

                      data = [data];
                      data.push.apply(data, currentData);

                      for (var d = 0; d < data.length; d++) {
                          var id = data[d].id;

                          if ($.inArray(id, val) === -1) {
                              val.push(id);
                          }
                      }

                      self.$element.val(val);
                      self.$element.trigger('change');
                  });
              } else {
                  var val = data.id;

                  this.$element.val(val);
                  this.$element.trigger('change');
              }
          };

          SelectAdapter.prototype.unselect = function (data) {
              var self = this;

              if (!this.$element.prop('multiple')) {
                  return;
              }

              data.selected = false;

              if ($(data.element).is('option')) {
                  data.element.selected = false;

                  this.$element.trigger('change');

                  return;
              }

              this.current(function (currentData) {
                  var val = [];

                  for (var d = 0; d < currentData.length; d++) {
                      var id = currentData[d].id;

                      if (id !== data.id && $.inArray(id, val) === -1) {
                          val.push(id);
                      }
                  }

                  self.$element.val(val);

                  self.$element.trigger('change');
              });
          };

          SelectAdapter.prototype.bind = function (container, $container) {
              var self = this;

              this.container = container;

              container.on('select', function (params) {
                  self.select(params.data);
              });

              container.on('unselect', function (params) {
                  self.unselect(params.data);
              });
          };

          SelectAdapter.prototype.destroy = function () {
              // Remove anything added to child elements
              this.$element.find('*').each(function () {
                  // Remove any custom data set by Select2
                  $.removeData(this, 'data');
              });
          };

          SelectAdapter.prototype.query = function (params, callback) {
              var data = [];
              var self = this;

              var $options = this.$element.children();

              $options.each(function () {
                  var $option = $(this);

                  if (!$option.is('option') && !$option.is('optgroup')) {
                      return;
                  }

                  var option = self.item($option);

                  var matches = self.matches(params, option);

                  if (matches !== null) {
                      data.push(matches);
                  }
              });

              callback({
                  results: data
              });
          };

          SelectAdapter.prototype.addOptions = function ($options) {
              Utils.appendMany(this.$element, $options);
          };

          SelectAdapter.prototype.option = function (data) {
              var option;

              if (data.children) {
                  option = document.createElement('optgroup');
                  option.label = data.text;
              } else {
                  option = document.createElement('option');

                  if (option.textContent !== undefined) {
                      option.textContent = data.text;
                  } else {
                      option.innerText = data.text;
                  }
              }

              if (data.id) {
                  option.value = data.id;
              }

              if (data.disabled) {
                  option.disabled = true;
              }

              if (data.selected) {
                  option.selected = true;
              }

              if (data.title) {
                  option.title = data.title;
              }

              var $option = $(option);

              var normalizedData = this._normalizeItem(data);
              normalizedData.element = option;

              // Override the option's data with the combined data
              $.data(option, 'data', normalizedData);

              return $option;
          };

          SelectAdapter.prototype.item = function ($option) {
              var data = {};

              data = $.data($option[0], 'data');

              if (data != null) {
                  return data;
              }

              if ($option.is('option')) {
                  data = {
                      id: $option.val(),
                      text: $option.text(),
                      disabled: $option.prop('disabled'),
                      selected: $option.prop('selected'),
                      title: $option.prop('title')
                  };
              } else if ($option.is('optgroup')) {
                  data = {
                      text: $option.prop('label'),
                      children: [],
                      title: $option.prop('title')
                  };

                  var $children = $option.children('option');
                  var children = [];

                  for (var c = 0; c < $children.length; c++) {
                      var $child = $($children[c]);

                      var child = this.item($child);

                      children.push(child);
                  }

                  data.children = children;
              }

              data = this._normalizeItem(data);
              data.element = $option[0];

              $.data($option[0], 'data', data);

              return data;
          };

          SelectAdapter.prototype._normalizeItem = function (item) {
              if (!$.isPlainObject(item)) {
                  item = {
                      id: item,
                      text: item
                  };
              }

              item = $.extend({}, {
                  text: ''
              }, item);

              var defaults = {
                  selected: false,
                  disabled: false
              };

              if (item.id != null) {
                  item.id = item.id.toString();
              }

              if (item.text != null) {
                  item.text = item.text.toString();
              }

              if (item._resultId == null && item.id && this.container != null) {
                  item._resultId = this.generateResultId(this.container, item);
              }

              return $.extend({}, defaults, item);
          };

          SelectAdapter.prototype.matches = function (params, data) {
              var matcher = this.options.get('matcher');

              return matcher(params, data);
          };

          return SelectAdapter;
      });

      S2.define('select2/data/array', [
        './select',
        '../utils',
        'jquery'
      ], function (SelectAdapter, Utils, $) {
          function ArrayAdapter($element, options) {
              var data = options.get('data') || [];

              ArrayAdapter.__super__.constructor.call(this, $element, options);

              this.addOptions(this.convertToOptions(data));
          }

          Utils.Extend(ArrayAdapter, SelectAdapter);

          ArrayAdapter.prototype.select = function (data) {
              var $option = this.$element.find('option').filter(function (i, elm) {
                  return elm.value == data.id.toString();
              });

              if ($option.length === 0) {
                  $option = this.option(data);

                  this.addOptions($option);
              }

              ArrayAdapter.__super__.select.call(this, data);
          };

          ArrayAdapter.prototype.convertToOptions = function (data) {
              var self = this;

              var $existing = this.$element.find('option');
              var existingIds = $existing.map(function () {
                  return self.item($(this)).id;
              }).get();

              var $options = [];

              // Filter out all items except for the one passed in the argument
              function onlyItem(item) {
                  return function () {
                      return $(this).val() == item.id;
                  };
              }

              for (var d = 0; d < data.length; d++) {
                  var item = this._normalizeItem(data[d]);

                  // Skip items which were pre-loaded, only merge the data
                  if ($.inArray(item.id, existingIds) >= 0) {
                      var $existingOption = $existing.filter(onlyItem(item));

                      var existingData = this.item($existingOption);
                      var newData = $.extend(true, {}, existingData, item);

                      var $newOption = this.option(existingData);

                      $existingOption.replaceWith($newOption);

                      continue;
                  }

                  var $option = this.option(item);

                  if (item.children) {
                      var $children = this.convertToOptions(item.children);

                      Utils.appendMany($option, $children);
                  }

                  $options.push($option);
              }

              return $options;
          };

          return ArrayAdapter;
      });

      S2.define('select2/data/ajax', [
        './array',
        '../utils',
        'jquery'
      ], function (ArrayAdapter, Utils, $) {
          function AjaxAdapter($element, options) {
              this.ajaxOptions = this._applyDefaults(options.get('ajax'));

              if (this.ajaxOptions.processResults != null) {
                  this.processResults = this.ajaxOptions.processResults;
              }

              AjaxAdapter.__super__.constructor.call(this, $element, options);
          }

          Utils.Extend(AjaxAdapter, ArrayAdapter);

          AjaxAdapter.prototype._applyDefaults = function (options) {
              var defaults = {
                  data: function (params) {
                      return {
                          q: params.term
                      };
                  },
                  transport: function (params, success, failure) {
                      var $request = $.ajax(params);

                      $request.then(success);
                      $request.fail(failure);

                      return $request;
                  }
              };

              return $.extend({}, defaults, options, true);
          };

          AjaxAdapter.prototype.processResults = function (results) {
              return results;
          };

          AjaxAdapter.prototype.query = function (params, callback) {
              var matches = [];
              var self = this;

              if (this._request != null) {
                  // JSONP requests cannot always be aborted
                  if ($.isFunction(this._request.abort)) {
                      this._request.abort();
                  }

                  this._request = null;
              }

              var options = $.extend({
                  type: 'GET'
              }, this.ajaxOptions);

              if (typeof options.url === 'function') {
                  options.url = options.url(params);
              }

              if (typeof options.data === 'function') {
                  options.data = options.data(params);
              }

              function request() {
                  var $request = options.transport(options, function (data) {
                      var results = self.processResults(data, params);

                      if (self.options.get('debug') && window.console && console.error) {
                          // Check to make sure that the response included a `results` key.
                          if (!results || !results.results || !$.isArray(results.results)) {
                              console.error(
                                'Select2: The AJAX results did not return an array in the ' +
                                '`results` key of the response.'
                              );
                          }
                      }

                      callback(results);
                  }, function () {
                      // TODO: Handle AJAX errors
                  });

                  self._request = $request;
              }

              if (this.ajaxOptions.delay && params.term !== '') {
                  if (this._queryTimeout) {
                      window.clearTimeout(this._queryTimeout);
                  }

                  this._queryTimeout = window.setTimeout(request, this.ajaxOptions.delay);
              } else {
                  request();
              }
          };

          return AjaxAdapter;
      });

      S2.define('select2/data/tags', [
        'jquery'
      ], function ($) {
          function Tags(decorated, $element, options) {
              var tags = options.get('tags');

              var createTag = options.get('createTag');

              if (createTag !== undefined) {
                  this.createTag = createTag;
              }

              decorated.call(this, $element, options);

              if ($.isArray(tags)) {
                  for (var t = 0; t < tags.length; t++) {
                      var tag = tags[t];
                      var item = this._normalizeItem(tag);

                      var $option = this.option(item);

                      this.$element.append($option);
                  }
              }
          }

          Tags.prototype.query = function (decorated, params, callback) {
              var self = this;

              this._removeOldTags();

              if (params.term == null || params.page != null) {
                  decorated.call(this, params, callback);
                  return;
              }

              function wrapper(obj, child) {
                  var data = obj.results;

                  for (var i = 0; i < data.length; i++) {
                      var option = data[i];

                      var checkChildren = (
                        option.children != null &&
                        !wrapper({
                            results: option.children
                        }, true)
                      );

                      var checkText = option.text === params.term;

                      if (checkText || checkChildren) {
                          if (child) {
                              return false;
                          }

                          obj.data = data;
                          callback(obj);

                          return;
                      }
                  }

                  if (child) {
                      return true;
                  }

                  var tag = self.createTag(params);

                  if (tag != null) {
                      var $option = self.option(tag);
                      $option.attr('data-select2-tag', true);

                      self.addOptions([$option]);

                      self.insertTag(data, tag);
                  }

                  obj.results = data;

                  callback(obj);
              }

              decorated.call(this, params, wrapper);
          };

          Tags.prototype.createTag = function (decorated, params) {
              var term = $.trim(params.term);

              if (term === '') {
                  return null;
              }

              return {
                  id: term,
                  text: term
              };
          };

          Tags.prototype.insertTag = function (_, data, tag) {
              data.unshift(tag);
          };

          Tags.prototype._removeOldTags = function (_) {
              var tag = this._lastTag;

              var $options = this.$element.find('option[data-select2-tag]');

              $options.each(function () {
                  if (this.selected) {
                      return;
                  }

                  $(this).remove();
              });
          };

          return Tags;
      });

      S2.define('select2/data/tokenizer', [
        'jquery'
      ], function ($) {
          function Tokenizer(decorated, $element, options) {
              var tokenizer = options.get('tokenizer');

              if (tokenizer !== undefined) {
                  this.tokenizer = tokenizer;
              }

              decorated.call(this, $element, options);
          }

          Tokenizer.prototype.bind = function (decorated, container, $container) {
              decorated.call(this, container, $container);

              this.$search = container.dropdown.$search || container.selection.$search ||
                $container.find('.select2-search__field');
          };

          Tokenizer.prototype.query = function (decorated, params, callback) {
              var self = this;

              function select(data) {
                  self.select(data);
              }

              params.term = params.term || '';

              var tokenData = this.tokenizer(params, this.options, select);

              if (tokenData.term !== params.term) {
                  // Replace the search term if we have the search box
                  if (this.$search.length) {
                      this.$search.val(tokenData.term);
                      this.$search.focus();
                  }

                  params.term = tokenData.term;
              }

              decorated.call(this, params, callback);
          };

          Tokenizer.prototype.tokenizer = function (_, params, options, callback) {
              var separators = options.get('tokenSeparators') || [];
              var term = params.term;
              var i = 0;

              var createTag = this.createTag || function (params) {
                  return {
                      id: params.term,
                      text: params.term
                  };
              };

              while (i < term.length) {
                  var termChar = term[i];

                  if ($.inArray(termChar, separators) === -1) {
                      i++;

                      continue;
                  }

                  var part = term.substr(0, i);
                  var partParams = $.extend({}, params, {
                      term: part
                  });

                  var data = createTag(partParams);

                  callback(data);

                  // Reset the term to not include the tokenized portion
                  term = term.substr(i + 1) || '';
                  i = 0;
              }

              return {
                  term: term
              };
          };

          return Tokenizer;
      });

      S2.define('select2/data/minimumInputLength', [

      ], function () {
          function MinimumInputLength(decorated, $e, options) {
              this.minimumInputLength = options.get('minimumInputLength');

              decorated.call(this, $e, options);
          }

          MinimumInputLength.prototype.query = function (decorated, params, callback) {
              params.term = params.term || '';

              if (params.term.length < this.minimumInputLength) {
                  this.trigger('results:message', {
                      message: 'inputTooShort',
                      args: {
                          minimum: this.minimumInputLength,
                          input: params.term,
                          params: params
                      }
                  });

                  return;
              }

              decorated.call(this, params, callback);
          };

          return MinimumInputLength;
      });

      S2.define('select2/data/maximumInputLength', [

      ], function () {
          function MaximumInputLength(decorated, $e, options) {
              this.maximumInputLength = options.get('maximumInputLength');

              decorated.call(this, $e, options);
          }

          MaximumInputLength.prototype.query = function (decorated, params, callback) {
              params.term = params.term || '';

              if (this.maximumInputLength > 0 &&
                  params.term.length > this.maximumInputLength) {
                  this.trigger('results:message', {
                      message: 'inputTooLong',
                      args: {
                          maximum: this.maximumInputLength,
                          input: params.term,
                          params: params
                      }
                  });

                  return;
              }

              decorated.call(this, params, callback);
          };

          return MaximumInputLength;
      });

      S2.define('select2/data/maximumSelectionLength', [

      ], function () {
          function MaximumSelectionLength(decorated, $e, options) {
              this.maximumSelectionLength = options.get('maximumSelectionLength');

              decorated.call(this, $e, options);
          }

          MaximumSelectionLength.prototype.query =
            function (decorated, params, callback) {
                var self = this;

                this.current(function (currentData) {
                    var count = currentData != null ? currentData.length : 0;
                    if (self.maximumSelectionLength > 0 &&
                      count >= self.maximumSelectionLength) {
                        self.trigger('results:message', {
                            message: 'maximumSelected',
                            args: {
                                maximum: self.maximumSelectionLength
                            }
                        });
                        return;
                    }
                    decorated.call(self, params, callback);
                });
            };

          return MaximumSelectionLength;
      });

      S2.define('select2/dropdown', [
        'jquery',
        './utils'
      ], function ($, Utils) {
          function Dropdown($element, options) {
              this.$element = $element;
              this.options = options;

              Dropdown.__super__.constructor.call(this);
          }

          Utils.Extend(Dropdown, Utils.Observable);

          Dropdown.prototype.render = function () {
              var $dropdown = $(
                '<span class="select2-dropdown">' +
                  '<span class="select2-results"></span>' +
                '</span>'
              );

              $dropdown.attr('dir', this.options.get('dir'));

              this.$dropdown = $dropdown;

              return $dropdown;
          };

          Dropdown.prototype.position = function ($dropdown, $container) {
              // Should be implmented in subclasses
          };

          Dropdown.prototype.destroy = function () {
              // Remove the dropdown from the DOM
              this.$dropdown.remove();
          };

          return Dropdown;
      });

      S2.define('select2/dropdown/search', [
        'jquery',
        '../utils'
      ], function ($, Utils) {
          function Search() { }

          Search.prototype.render = function (decorated) {
              var $rendered = decorated.call(this);

              var $search = $(
                '<span class="select2-search select2-search--dropdown">' +
                  '<input class="select2-search__field" type="search" tabindex="-1"' +
                  ' autocomplete="off" autocorrect="off" autocapitalize="off"' +
                  ' spellcheck="false" role="textbox" />' +
                '</span>'
              );

              this.$searchContainer = $search;
              this.$search = $search.find('input');

              $rendered.prepend($search);

              return $rendered;
          };

          Search.prototype.bind = function (decorated, container, $container) {
              var self = this;

              decorated.call(this, container, $container);

              this.$search.on('keydown', function (evt) {
                  self.trigger('keypress', evt);

                  self._keyUpPrevented = evt.isDefaultPrevented();
              });

              // Workaround for browsers which do not support the `input` event
              // This will prevent double-triggering of events for browsers which support
              // both the `keyup` and `input` events.
              this.$search.on('input', function (evt) {
                  // Unbind the duplicated `keyup` event
                  $(this).off('keyup');
              });

              this.$search.on('keyup input', function (evt) {
                  self.handleSearch(evt);
              });

              container.on('open', function () {
                  self.$search.attr('tabindex', 0);

                  self.$search.focus();

                  window.setTimeout(function () {
                      self.$search.focus();
                  }, 0);
              });

              container.on('close', function () {
                  self.$search.attr('tabindex', -1);

                  self.$search.val('');
              });

              container.on('results:all', function (params) {
                  if (params.query.term == null || params.query.term === '') {
                      var showSearch = self.showSearch(params);

                      if (showSearch) {
                          self.$searchContainer.removeClass('select2-search--hide');
                      } else {
                          self.$searchContainer.addClass('select2-search--hide');
                      }
                  }
              });
          };

          Search.prototype.handleSearch = function (evt) {
              if (!this._keyUpPrevented) {
                  var input = this.$search.val();

                  this.trigger('query', {
                      term: input
                  });
              }

              this._keyUpPrevented = false;
          };

          Search.prototype.showSearch = function (_, params) {
              return true;
          };

          return Search;
      });

      S2.define('select2/dropdown/hidePlaceholder', [

      ], function () {
          function HidePlaceholder(decorated, $element, options, dataAdapter) {
              this.placeholder = this.normalizePlaceholder(options.get('placeholder'));

              decorated.call(this, $element, options, dataAdapter);
          }

          HidePlaceholder.prototype.append = function (decorated, data) {
              data.results = this.removePlaceholder(data.results);

              decorated.call(this, data);
          };

          HidePlaceholder.prototype.normalizePlaceholder = function (_, placeholder) {
              if (typeof placeholder === 'string') {
                  placeholder = {
                      id: '',
                      text: placeholder
                  };
              }

              return placeholder;
          };

          HidePlaceholder.prototype.removePlaceholder = function (_, data) {
              var modifiedData = data.slice(0);

              for (var d = data.length - 1; d >= 0; d--) {
                  var item = data[d];

                  if (this.placeholder.id === item.id) {
                      modifiedData.splice(d, 1);
                  }
              }

              return modifiedData;
          };

          return HidePlaceholder;
      });

      S2.define('select2/dropdown/infiniteScroll', [
        'jquery'
      ], function ($) {
          function InfiniteScroll(decorated, $element, options, dataAdapter) {
              this.lastParams = {};

              decorated.call(this, $element, options, dataAdapter);

              this.$loadingMore = this.createLoadingMore();
              this.loading = false;
          }

          InfiniteScroll.prototype.append = function (decorated, data) {
              this.$loadingMore.remove();
              this.loading = false;

              decorated.call(this, data);

              if (this.showLoadingMore(data)) {
                  this.$results.append(this.$loadingMore);
              }
          };

          InfiniteScroll.prototype.bind = function (decorated, container, $container) {
              var self = this;

              decorated.call(this, container, $container);

              container.on('query', function (params) {
                  self.lastParams = params;
                  self.loading = true;
              });

              container.on('query:append', function (params) {
                  self.lastParams = params;
                  self.loading = true;
              });

              this.$results.on('scroll', function () {
                  var isLoadMoreVisible = $.contains(
                    document.documentElement,
                    self.$loadingMore[0]
                  );

                  if (self.loading || !isLoadMoreVisible) {
                      return;
                  }

                  var currentOffset = self.$results.offset().top +
                    self.$results.outerHeight(false);
                  var loadingMoreOffset = self.$loadingMore.offset().top +
                    self.$loadingMore.outerHeight(false);

                  if (currentOffset + 50 >= loadingMoreOffset) {
                      self.loadMore();
                  }
              });
          };

          InfiniteScroll.prototype.loadMore = function () {
              this.loading = true;

              var params = $.extend({}, { page: 1 }, this.lastParams);

              params.page++;

              this.trigger('query:append', params);
          };

          InfiniteScroll.prototype.showLoadingMore = function (_, data) {
              return data.pagination && data.pagination.more;
          };

          InfiniteScroll.prototype.createLoadingMore = function () {
              var $option = $(
                '<li class="option load-more" role="treeitem"></li>'
              );

              var message = this.options.get('translations').get('loadingMore');

              $option.html(message(this.lastParams));

              return $option;
          };

          return InfiniteScroll;
      });

      S2.define('select2/dropdown/attachBody', [
        'jquery',
        '../utils'
      ], function ($, Utils) {
          function AttachBody(decorated, $element, options) {
              this.$dropdownParent = options.get('dropdownParent') || document.body;

              decorated.call(this, $element, options);
          }

          AttachBody.prototype.bind = function (decorated, container, $container) {
              var self = this;

              var setupResultsEvents = false;

              decorated.call(this, container, $container);

              container.on('open', function () {
                  self._showDropdown();
                  self._attachPositioningHandler(container);

                  if (!setupResultsEvents) {
                      setupResultsEvents = true;

                      container.on('results:all', function () {
                          self._positionDropdown();
                          self._resizeDropdown();
                      });

                      container.on('results:append', function () {
                          self._positionDropdown();
                          self._resizeDropdown();
                      });
                  }
              });

              container.on('close', function () {
                  self._hideDropdown();
                  self._detachPositioningHandler(container);
              });

              this.$dropdownContainer.on('mousedown', function (evt) {
                  evt.stopPropagation();
              });
          };

          AttachBody.prototype.position = function (decorated, $dropdown, $container) {
              // Clone all of the container classes
              $dropdown.attr('class', $container.attr('class'));

              $dropdown.removeClass('select2');
              $dropdown.addClass('select2-container--open');

              $dropdown.css({
                  position: 'absolute',
                  top: -999999
              });

              this.$container = $container;
          };

          AttachBody.prototype.render = function (decorated) {
              var $container = $('<span></span>');

              var $dropdown = decorated.call(this);
              $container.append($dropdown);

              this.$dropdownContainer = $container;

              return $container;
          };

          AttachBody.prototype._hideDropdown = function (decorated) {
              this.$dropdownContainer.detach();
          };

          AttachBody.prototype._attachPositioningHandler = function (container) {
              var self = this;

              var scrollEvent = 'scroll.select2.' + container.id;
              var resizeEvent = 'resize.select2.' + container.id;
              var orientationEvent = 'orientationchange.select2.' + container.id;

              var $watchers = this.$container.parents().filter(Utils.hasScroll);
              $watchers.each(function () {
                  $(this).data('select2-scroll-position', {
                      x: $(this).scrollLeft(),
                      y: $(this).scrollTop()
                  });
              });

              $watchers.on(scrollEvent, function (ev) {
                  var position = $(this).data('select2-scroll-position');
                  $(this).scrollTop(position.y);
              });

              $(window).on(scrollEvent + ' ' + resizeEvent + ' ' + orientationEvent,
                function (e) {
                    self._positionDropdown();
                    self._resizeDropdown();
                });
          };

          AttachBody.prototype._detachPositioningHandler = function (container) {
              var scrollEvent = 'scroll.select2.' + container.id;
              var resizeEvent = 'resize.select2.' + container.id;
              var orientationEvent = 'orientationchange.select2.' + container.id;

              var $watchers = this.$container.parents().filter(Utils.hasScroll);
              $watchers.off(scrollEvent);

              $(window).off(scrollEvent + ' ' + resizeEvent + ' ' + orientationEvent);
          };

          AttachBody.prototype._positionDropdown = function () {
              var $window = $(window);

              var isCurrentlyAbove = this.$dropdown.hasClass('select2-dropdown--above');
              var isCurrentlyBelow = this.$dropdown.hasClass('select2-dropdown--below');

              var newDirection = null;

              var position = this.$container.position();
              var offset = this.$container.offset();

              offset.bottom = offset.top + this.$container.outerHeight(false);

              var container = {
                  height: this.$container.outerHeight(false)
              };

              container.top = offset.top;
              container.bottom = offset.top + container.height;

              var dropdown = {
                  height: this.$dropdown.outerHeight(false)
              };

              var viewport = {
                  top: $window.scrollTop(),
                  bottom: $window.scrollTop() + $window.height()
              };

              var enoughRoomAbove = viewport.top < (offset.top - dropdown.height);
              var enoughRoomBelow = viewport.bottom > (offset.bottom + dropdown.height);

              var css = {
                  left: offset.left,
                  top: container.bottom
              };

              if (!isCurrentlyAbove && !isCurrentlyBelow) {
                  newDirection = 'below';
              }

              if (!enoughRoomBelow && enoughRoomAbove && !isCurrentlyAbove) {
                  newDirection = 'above';
              } else if (!enoughRoomAbove && enoughRoomBelow && isCurrentlyAbove) {
                  newDirection = 'below';
              }

              if (newDirection == 'above' ||
                (isCurrentlyAbove && newDirection !== 'below')) {
                  css.top = container.top - dropdown.height;
              }

              if (newDirection != null) {
                  this.$dropdown
                    .removeClass('select2-dropdown--below select2-dropdown--above')
                    .addClass('select2-dropdown--' + newDirection);
                  this.$container
                    .removeClass('select2-container--below select2-container--above')
                    .addClass('select2-container--' + newDirection);
              }

              this.$dropdownContainer.css(css);
          };

          AttachBody.prototype._resizeDropdown = function () {
              this.$dropdownContainer.width();

              var css = {
                  width: this.$container.outerWidth(false) + 'px'
              };

              if (this.options.get('dropdownAutoWidth')) {
                  css.minWidth = css.width;
                  css.width = 'auto';
              }

              this.$dropdown.css(css);
          };

          AttachBody.prototype._showDropdown = function (decorated) {
              this.$dropdownContainer.appendTo(this.$dropdownParent);

              this._positionDropdown();
              this._resizeDropdown();
          };

          return AttachBody;
      });

      S2.define('select2/dropdown/minimumResultsForSearch', [

      ], function () {
          function countResults(data) {
              var count = 0;

              for (var d = 0; d < data.length; d++) {
                  var item = data[d];

                  if (item.children) {
                      count += countResults(item.children);
                  } else {
                      count++;
                  }
              }

              return count;
          }

          function MinimumResultsForSearch(decorated, $element, options, dataAdapter) {
              this.minimumResultsForSearch = options.get('minimumResultsForSearch');

              if (this.minimumResultsForSearch < 0) {
                  this.minimumResultsForSearch = Infinity;
              }

              decorated.call(this, $element, options, dataAdapter);
          }

          MinimumResultsForSearch.prototype.showSearch = function (decorated, params) {
              if (countResults(params.data.results) < this.minimumResultsForSearch) {
                  return false;
              }

              return decorated.call(this, params);
          };

          return MinimumResultsForSearch;
      });

      S2.define('select2/dropdown/selectOnClose', [

      ], function () {
          function SelectOnClose() { }

          SelectOnClose.prototype.bind = function (decorated, container, $container) {
              var self = this;

              decorated.call(this, container, $container);

              container.on('close', function () {
                  self._handleSelectOnClose();
              });
          };

          SelectOnClose.prototype._handleSelectOnClose = function () {
              var $highlightedResults = this.getHighlightedResults();

              if ($highlightedResults.length < 1) {
                  return;
              }

              this.trigger('select', {
                  data: $highlightedResults.data('data')
              });
          };

          return SelectOnClose;
      });

      S2.define('select2/dropdown/closeOnSelect', [

      ], function () {
          function CloseOnSelect() { }

          CloseOnSelect.prototype.bind = function (decorated, container, $container) {
              var self = this;

              decorated.call(this, container, $container);

              container.on('select', function (evt) {
                  self._selectTriggered(evt);
              });

              container.on('unselect', function (evt) {
                  self._selectTriggered(evt);
              });
          };

          CloseOnSelect.prototype._selectTriggered = function (_, evt) {
              var originalEvent = evt.originalEvent;

              // Don't close if the control key is being held
              if (originalEvent && originalEvent.ctrlKey) {
                  return;
              }

              this.trigger('close');
          };

          return CloseOnSelect;
      });

      S2.define('select2/i18n/en', [], function () {
          // English
          return {
              errorLoading: function () {
                  return 'The results could not be loaded.';
              },
              inputTooLong: function (args) {
                  var overChars = args.input.length - args.maximum;

                  var message = 'Please delete ' + overChars + ' character';

                  if (overChars != 1) {
                      message += 's';
                  }

                  return message;
              },
              inputTooShort: function (args) {
                  var remainingChars = args.minimum - args.input.length;

                  var message = 'Please enter ' + remainingChars + ' or more characters';

                  return message;
              },
              loadingMore: function () {
                  return 'Loading more results�';
              },
              maximumSelected: function (args) {
                  var message = 'You can only select ' + args.maximum + ' item';

                  if (args.maximum != 1) {
                      message += 's';
                  }

                  return message;
              },
              noResults: function () {
                  return 'No results found';
              },
              searching: function () {
                  return 'Searching�';
              }
          };
      });

      S2.define('select2/defaults', [
        'jquery',
        'require',

        './results',

        './selection/single',
        './selection/multiple',
        './selection/placeholder',
        './selection/allowClear',
        './selection/search',
        './selection/eventRelay',

        './utils',
        './translation',
        './diacritics',

        './data/select',
        './data/array',
        './data/ajax',
        './data/tags',
        './data/tokenizer',
        './data/minimumInputLength',
        './data/maximumInputLength',
        './data/maximumSelectionLength',

        './dropdown',
        './dropdown/search',
        './dropdown/hidePlaceholder',
        './dropdown/infiniteScroll',
        './dropdown/attachBody',
        './dropdown/minimumResultsForSearch',
        './dropdown/selectOnClose',
        './dropdown/closeOnSelect',

        './i18n/en'
      ], function ($, require,

                   ResultsList,

                   SingleSelection, MultipleSelection, Placeholder, AllowClear,
                   SelectionSearch, EventRelay,

                   Utils, Translation, DIACRITICS,

                   SelectData, ArrayData, AjaxData, Tags, Tokenizer,
                   MinimumInputLength, MaximumInputLength, MaximumSelectionLength,

                   Dropdown, DropdownSearch, HidePlaceholder, InfiniteScroll,
                   AttachBody, MinimumResultsForSearch, SelectOnClose, CloseOnSelect,

                   EnglishTranslation) {
          function Defaults() {
              this.reset();
          }

          Defaults.prototype.apply = function (options) {
              options = $.extend({}, this.defaults, options);

              if (options.dataAdapter == null) {
                  if (options.ajax != null) {
                      options.dataAdapter = AjaxData;
                  } else if (options.data != null) {
                      options.dataAdapter = ArrayData;
                  } else {
                      options.dataAdapter = SelectData;
                  }

                  if (options.minimumInputLength > 0) {
                      options.dataAdapter = Utils.Decorate(
                        options.dataAdapter,
                        MinimumInputLength
                      );
                  }

                  if (options.maximumInputLength > 0) {
                      options.dataAdapter = Utils.Decorate(
                        options.dataAdapter,
                        MaximumInputLength
                      );
                  }

                  if (options.maximumSelectionLength > 0) {
                      options.dataAdapter = Utils.Decorate(
                        options.dataAdapter,
                        MaximumSelectionLength
                      );
                  }

                  if (options.tags) {
                      options.dataAdapter = Utils.Decorate(options.dataAdapter, Tags);
                  }

                  if (options.tokenSeparators != null || options.tokenizer != null) {
                      options.dataAdapter = Utils.Decorate(
                        options.dataAdapter,
                        Tokenizer
                      );
                  }

                  if (options.query != null) {
                      var Query = require(options.amdBase + 'compat/query');

                      options.dataAdapter = Utils.Decorate(
                        options.dataAdapter,
                        Query
                      );
                  }

                  if (options.initSelection != null) {
                      var InitSelection = require(options.amdBase + 'compat/initSelection');

                      options.dataAdapter = Utils.Decorate(
                        options.dataAdapter,
                        InitSelection
                      );
                  }
              }

              if (options.resultsAdapter == null) {
                  options.resultsAdapter = ResultsList;

                  if (options.ajax != null) {
                      options.resultsAdapter = Utils.Decorate(
                        options.resultsAdapter,
                        InfiniteScroll
                      );
                  }

                  if (options.placeholder != null) {
                      options.resultsAdapter = Utils.Decorate(
                        options.resultsAdapter,
                        HidePlaceholder
                      );
                  }

                  if (options.selectOnClose) {
                      options.resultsAdapter = Utils.Decorate(
                        options.resultsAdapter,
                        SelectOnClose
                      );
                  }
              }

              if (options.dropdownAdapter == null) {
                  if (options.multiple) {
                      options.dropdownAdapter = Dropdown;
                  } else {
                      var SearchableDropdown = Utils.Decorate(Dropdown, DropdownSearch);

                      options.dropdownAdapter = SearchableDropdown;
                  }

                  if (options.minimumResultsForSearch !== 0) {
                      options.dropdownAdapter = Utils.Decorate(
                        options.dropdownAdapter,
                        MinimumResultsForSearch
                      );
                  }

                  if (options.closeOnSelect) {
                      options.dropdownAdapter = Utils.Decorate(
                        options.dropdownAdapter,
                        CloseOnSelect
                      );
                  }

                  if (
                    options.dropdownCssClass != null ||
                    options.dropdownCss != null ||
                    options.adaptDropdownCssClass != null
                  ) {
                      var DropdownCSS = require(options.amdBase + 'compat/dropdownCss');

                      options.dropdownAdapter = Utils.Decorate(
                        options.dropdownAdapter,
                        DropdownCSS
                      );
                  }

                  options.dropdownAdapter = Utils.Decorate(
                    options.dropdownAdapter,
                    AttachBody
                  );
              }

              if (options.selectionAdapter == null) {
                  if (options.multiple) {
                      options.selectionAdapter = MultipleSelection;
                  } else {
                      options.selectionAdapter = SingleSelection;
                  }

                  // Add the placeholder mixin if a placeholder was specified
                  if (options.placeholder != null) {
                      options.selectionAdapter = Utils.Decorate(
                        options.selectionAdapter,
                        Placeholder
                      );
                  }

                  if (options.allowClear) {
                      options.selectionAdapter = Utils.Decorate(
                        options.selectionAdapter,
                        AllowClear
                      );
                  }

                  if (options.multiple) {
                      options.selectionAdapter = Utils.Decorate(
                        options.selectionAdapter,
                        SelectionSearch
                      );
                  }

                  if (
                    options.containerCssClass != null ||
                    options.containerCss != null ||
                    options.adaptContainerCssClass != null
                  ) {
                      var ContainerCSS = require(options.amdBase + 'compat/containerCss');

                      options.selectionAdapter = Utils.Decorate(
                        options.selectionAdapter,
                        ContainerCSS
                      );
                  }

                  options.selectionAdapter = Utils.Decorate(
                    options.selectionAdapter,
                    EventRelay
                  );
              }

              if (typeof options.language === 'string') {
                  // Check if the language is specified with a region
                  if (options.language.indexOf('-') > 0) {
                      // Extract the region information if it is included
                      var languageParts = options.language.split('-');
                      var baseLanguage = languageParts[0];

                      options.language = [options.language, baseLanguage];
                  } else {
                      options.language = [options.language];
                  }
              }

              if ($.isArray(options.language)) {
                  var languages = new Translation();
                  options.language.push('en');

                  var languageNames = options.language;

                  for (var l = 0; l < languageNames.length; l++) {
                      var name = languageNames[l];
                      var language = {};

                      try {
                          // Try to load it with the original name
                          language = Translation.loadPath(name);
                      } catch (e) {
                          try {
                              // If we couldn't load it, check if it wasn't the full path
                              name = this.defaults.amdLanguageBase + name;
                              language = Translation.loadPath(name);
                          } catch (ex) {
                              // The translation could not be loaded at all. Sometimes this is
                              // because of a configuration problem, other times this can be
                              // because of how Select2 helps load all possible translation files.
                              if (options.debug && window.console && console.warn) {
                                  console.warn(
                                    'Select2: The language file for "' + name + '" could not be ' +
                                    'automatically loaded. A fallback will be used instead.'
                                  );
                              }

                              continue;
                          }
                      }

                      languages.extend(language);
                  }

                  options.translations = languages;
              } else {
                  var baseTranslation = Translation.loadPath(
                    this.defaults.amdLanguageBase + 'en'
                  );
                  var customTranslation = new Translation(options.language);

                  customTranslation.extend(baseTranslation);

                  options.translations = customTranslation;
              }

              return options;
          };

          Defaults.prototype.reset = function () {
              function stripDiacritics(text) {
                  // Used 'uni range + named function' from http://jsperf.com/diacritics/18
                  function match(a) {
                      return DIACRITICS[a] || a;
                  }

                  return text.replace(/[^\u0000-\u007E]/g, match);
              }

              function matcher(params, data) {
                  // Always return the object if there is nothing to compare
                  if ($.trim(params.term) === '') {
                      return data;
                  }

                  // Do a recursive check for options with children
                  if (data.children && data.children.length > 0) {
                      // Clone the data object if there are children
                      // This is required as we modify the object to remove any non-matches
                      var match = $.extend(true, {}, data);

                      // Check each child of the option
                      for (var c = data.children.length - 1; c >= 0; c--) {
                          var child = data.children[c];

                          var matches = matcher(params, child);

                          // If there wasn't a match, remove the object in the array
                          if (matches == null) {
                              match.children.splice(c, 1);
                          }
                      }

                      // If any children matched, return the new object
                      if (match.children.length > 0) {
                          return match;
                      }

                      // If there were no matching children, check just the plain object
                      return matcher(params, match);
                  }

                  var original = stripDiacritics(data.text).toUpperCase();
                  var term = stripDiacritics(params.term).toUpperCase();

                  // Check if the text contains the term
                  if (original.indexOf(term) > -1) {
                      return data;
                  }

                  // If it doesn't contain the term, don't return anything
                  return null;
              }

              this.defaults = {
                  amdBase: './',
                  amdLanguageBase: './i18n/',
                  closeOnSelect: true,
                  debug: false,
                  dropdownAutoWidth: false,
                  escapeMarkup: Utils.escapeMarkup,
                  language: EnglishTranslation,
                  matcher: matcher,
                  minimumInputLength: 0,
                  maximumInputLength: 0,
                  maximumSelectionLength: 0,
                  minimumResultsForSearch: 0,
                  selectOnClose: false,
                  sorter: function (data) {
                      return data;
                  },
                  templateResult: function (result) {
                      return result.text;
                  },
                  templateSelection: function (selection) {
                      return selection.text;
                  },
                  theme: 'default',
                  width: 'resolve'
              };
          };

          Defaults.prototype.set = function (key, value) {
              var camelKey = $.camelCase(key);

              var data = {};
              data[camelKey] = value;

              var convertedData = Utils._convertData(data);

              $.extend(this.defaults, convertedData);
          };

          var defaults = new Defaults();

          return defaults;
      });

      S2.define('select2/options', [
        'require',
        'jquery',
        './defaults',
        './utils'
      ], function (require, $, Defaults, Utils) {
          function Options(options, $element) {
              this.options = options;

              if ($element != null) {
                  this.fromElement($element);
              }

              this.options = Defaults.apply(this.options);

              if ($element && $element.is('input')) {
                  var InputCompat = require(this.get('amdBase') + 'compat/inputData');

                  this.options.dataAdapter = Utils.Decorate(
                    this.options.dataAdapter,
                    InputCompat
                  );
              }
          }

          Options.prototype.fromElement = function ($e) {
              var excludedData = ['select2'];

              if (this.options.multiple == null) {
                  this.options.multiple = $e.prop('multiple');
              }

              if (this.options.disabled == null) {
                  this.options.disabled = $e.prop('disabled');
              }

              if (this.options.language == null) {
                  if ($e.prop('lang')) {
                      this.options.language = $e.prop('lang').toLowerCase();
                  } else if ($e.closest('[lang]').prop('lang')) {
                      this.options.language = $e.closest('[lang]').prop('lang');
                  }
              }

              if (this.options.dir == null) {
                  if ($e.prop('dir')) {
                      this.options.dir = $e.prop('dir');
                  } else if ($e.closest('[dir]').prop('dir')) {
                      this.options.dir = $e.closest('[dir]').prop('dir');
                  } else {
                      this.options.dir = 'ltr';
                  }
              }

              $e.prop('disabled', this.options.disabled);
              $e.prop('multiple', this.options.multiple);

              if ($e.data('select2Tags')) {
                  if (this.options.debug && window.console && console.warn) {
                      console.warn(
                        'Select2: The `data-select2-tags` attribute has been changed to ' +
                        'use the `data-data` and `data-tags="true"` attributes and will be ' +
                        'removed in future versions of Select2.'
                      );
                  }

                  $e.data('data', $e.data('select2Tags'));
                  $e.data('tags', true);
              }

              if ($e.data('ajaxUrl')) {
                  if (this.options.debug && window.console && console.warn) {
                      console.warn(
                        'Select2: The `data-ajax-url` attribute has been changed to ' +
                        '`data-ajax--url` and support for the old attribute will be removed' +
                        ' in future versions of Select2.'
                      );
                  }

                  $e.attr('ajax--url', $e.data('ajaxUrl'));
                  $e.data('ajax--url', $e.data('ajaxUrl'));
              }

              var dataset = {};

              // Prefer the element's `dataset` attribute if it exists
              // jQuery 1.x does not correctly handle data attributes with multiple dashes
              if ($.fn.jquery && $.fn.jquery.substr(0, 2) == '1.' && $e[0].dataset) {
                  dataset = $.extend(true, {}, $e[0].dataset, $e.data());
              } else {
                  dataset = $e.data();
              }

              var data = $.extend(true, {}, dataset);

              data = Utils._convertData(data);

              for (var key in data) {
                  if ($.inArray(key, excludedData) > -1) {
                      continue;
                  }

                  if ($.isPlainObject(this.options[key])) {
                      $.extend(this.options[key], data[key]);
                  } else {
                      this.options[key] = data[key];
                  }
              }

              return this;
          };

          Options.prototype.get = function (key) {
              return this.options[key];
          };

          Options.prototype.set = function (key, val) {
              this.options[key] = val;
          };

          return Options;
      });

      S2.define('select2/core', [
        'jquery',
        './options',
        './utils',
        './keys'
      ], function ($, Options, Utils, KEYS) {
          var Select2 = function ($element, options) {
              if ($element.data('select2') != null) {
                  $element.data('select2').destroy();
              }

              this.$element = $element;

              this.id = this._generateId($element);

              options = options || {};

              this.options = new Options(options, $element);

              Select2.__super__.constructor.call(this);

              // Set up the tabindex

              var tabindex = $element.attr('tabindex') || 0;
              $element.data('old-tabindex', tabindex);
              $element.attr('tabindex', '-1');

              // Set up containers and adapters

              var DataAdapter = this.options.get('dataAdapter');
              this.dataAdapter = new DataAdapter($element, this.options);

              var $container = this.render();

              this._placeContainer($container);

              var SelectionAdapter = this.options.get('selectionAdapter');
              this.selection = new SelectionAdapter($element, this.options);
              this.$selection = this.selection.render();

              this.selection.position(this.$selection, $container);

              var DropdownAdapter = this.options.get('dropdownAdapter');
              this.dropdown = new DropdownAdapter($element, this.options);
              this.$dropdown = this.dropdown.render();

              this.dropdown.position(this.$dropdown, $container);

              var ResultsAdapter = this.options.get('resultsAdapter');
              this.results = new ResultsAdapter($element, this.options, this.dataAdapter);
              this.$results = this.results.render();

              this.results.position(this.$results, this.$dropdown);

              // Bind events

              var self = this;

              // Bind the container to all of the adapters
              this._bindAdapters();

              // Register any DOM event handlers
              this._registerDomEvents();

              // Register any internal event handlers
              this._registerDataEvents();
              this._registerSelectionEvents();
              this._registerDropdownEvents();
              this._registerResultsEvents();
              this._registerEvents();

              // Set the initial state
              this.dataAdapter.current(function (initialData) {
                  self.trigger('selection:update', {
                      data: initialData
                  });
              });

              // Hide the original select
              $element.addClass('select2-hidden-accessible');
              $element.attr('aria-hidden', 'true');

              // Synchronize any monitored attributes
              this._syncAttributes();

              $element.data('select2', this);
          };

          Utils.Extend(Select2, Utils.Observable);

          Select2.prototype._generateId = function ($element) {
              var id = '';

              if ($element.attr('id') != null) {
                  id = $element.attr('id');
              } else if ($element.attr('name') != null) {
                  id = $element.attr('name') + '-' + Utils.generateChars(2);
              } else {
                  id = Utils.generateChars(4);
              }

              id = 'select2-' + id;

              return id;
          };

          Select2.prototype._placeContainer = function ($container) {
              $container.insertAfter(this.$element);

              var width = this._resolveWidth(this.$element, this.options.get('width'));

              if (width != null) {
                  $container.css('width', width);
              }
          };

          Select2.prototype._resolveWidth = function ($element, method) {
              var WIDTH = /^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i;

              if (method == 'resolve') {
                  var styleWidth = this._resolveWidth($element, 'style');

                  if (styleWidth != null) {
                      return styleWidth;
                  }

                  return this._resolveWidth($element, 'element');
              }

              if (method == 'element') {
                  var elementWidth = $element.outerWidth(false);

                  if (elementWidth <= 0) {
                      return 'auto';
                  }

                  return elementWidth + 'px';
              }

              if (method == 'style') {
                  var style = $element.attr('style');

                  if (typeof (style) !== 'string') {
                      return null;
                  }

                  var attrs = style.split(';');

                  for (var i = 0, l = attrs.length; i < l; i = i + 1) {
                      var attr = attrs[i].replace(/\s/g, '');
                      var matches = attr.match(WIDTH);

                      if (matches !== null && matches.length >= 1) {
                          return matches[1];
                      }
                  }

                  return null;
              }

              return method;
          };

          Select2.prototype._bindAdapters = function () {
              this.dataAdapter.bind(this, this.$container);
              this.selection.bind(this, this.$container);

              this.dropdown.bind(this, this.$container);
              this.results.bind(this, this.$container);
          };

          Select2.prototype._registerDomEvents = function () {
              var self = this;

              this.$element.on('change.select2', function () {
                  self.dataAdapter.current(function (data) {
                      self.trigger('selection:update', {
                          data: data
                      });
                  });
              });

              this._sync = Utils.bind(this._syncAttributes, this);

              if (this.$element[0].attachEvent) {
                  this.$element[0].attachEvent('onpropertychange', this._sync);
              }

              var observer = window.MutationObserver ||
                window.WebKitMutationObserver ||
                window.MozMutationObserver
              ;

              if (observer != null) {
                  this._observer = new observer(function (mutations) {
                      $.each(mutations, self._sync);
                  });
                  this._observer.observe(this.$element[0], {
                      attributes: true,
                      subtree: false
                  });
              } else if (this.$element[0].addEventListener) {
                  this.$element[0].addEventListener('DOMAttrModified', self._sync, false);
              }
          };

          Select2.prototype._registerDataEvents = function () {
              var self = this;

              this.dataAdapter.on('*', function (name, params) {
                  self.trigger(name, params);
              });
          };

          Select2.prototype._registerSelectionEvents = function () {
              var self = this;
              var nonRelayEvents = ['toggle', 'focus'];

              this.selection.on('toggle', function () {
                  self.toggleDropdown();
              });

              this.selection.on('focus', function (params) {
                  self.focus(params);
              });

              this.selection.on('*', function (name, params) {
                  if ($.inArray(name, nonRelayEvents) !== -1) {
                      return;
                  }

                  self.trigger(name, params);
              });
          };

          Select2.prototype._registerDropdownEvents = function () {
              var self = this;

              this.dropdown.on('*', function (name, params) {
                  self.trigger(name, params);
              });
          };

          Select2.prototype._registerResultsEvents = function () {
              var self = this;

              this.results.on('*', function (name, params) {
                  self.trigger(name, params);
              });
          };

          Select2.prototype._registerEvents = function () {
              var self = this;

              this.on('open', function () {
                  self.$container.addClass('select2-container--open');
              });

              this.on('close', function () {
                  self.$container.removeClass('select2-container--open');
              });

              this.on('enable', function () {
                  self.$container.removeClass('select2-container--disabled');
              });

              this.on('disable', function () {
                  self.$container.addClass('select2-container--disabled');
              });

              this.on('blur', function () {
                  self.$container.removeClass('select2-container--focus');
              });

              this.on('query', function (params) {
                  if (!self.isOpen()) {
                      self.trigger('open');
                  }

                  this.dataAdapter.query(params, function (data) {
                      self.trigger('results:all', {
                          data: data,
                          query: params
                      });
                  });
              });

              this.on('query:append', function (params) {
                  this.dataAdapter.query(params, function (data) {
                      self.trigger('results:append', {
                          data: data,
                          query: params
                      });
                  });
              });

              this.on('keypress', function (evt) {
                  var key = evt.which;

                  if (self.isOpen()) {
                      if (key === KEYS.ESC || key === KEYS.TAB ||
                          (key === KEYS.UP && evt.altKey)) {
                          self.close();

                          evt.preventDefault();
                      } else if (key === KEYS.ENTER) {
                          self.trigger('results:select');

                          evt.preventDefault();
                      } else if ((key === KEYS.SPACE && evt.ctrlKey)) {
                          self.trigger('results:toggle');

                          evt.preventDefault();
                      } else if (key === KEYS.UP) {
                          self.trigger('results:previous');

                          evt.preventDefault();
                      } else if (key === KEYS.DOWN) {
                          self.trigger('results:next');

                          evt.preventDefault();
                      }
                  } else {
                      if (key === KEYS.ENTER || key === KEYS.SPACE ||
                          (key === KEYS.DOWN && evt.altKey)) {
                          self.open();

                          evt.preventDefault();
                      }
                  }
              });
          };

          Select2.prototype._syncAttributes = function () {
              this.options.set('disabled', this.$element.prop('disabled'));

              if (this.options.get('disabled')) {
                  if (this.isOpen()) {
                      this.close();
                  }

                  this.trigger('disable');
              } else {
                  this.trigger('enable');
              }
          };

          /**
           * Override the trigger method to automatically trigger pre-events when
           * there are events that can be prevented.
           */
          Select2.prototype.trigger = function (name, args) {
              var actualTrigger = Select2.__super__.trigger;
              var preTriggerMap = {
                  'open': 'opening',
                  'close': 'closing',
                  'select': 'selecting',
                  'unselect': 'unselecting'
              };

              if (name in preTriggerMap) {
                  var preTriggerName = preTriggerMap[name];
                  var preTriggerArgs = {
                      prevented: false,
                      name: name,
                      args: args
                  };

                  actualTrigger.call(this, preTriggerName, preTriggerArgs);

                  if (preTriggerArgs.prevented) {
                      args.prevented = true;

                      return;
                  }
              }

              actualTrigger.call(this, name, args);
          };

          Select2.prototype.toggleDropdown = function () {
              if (this.options.get('disabled')) {
                  return;
              }

              if (this.isOpen()) {
                  this.close();
              } else {
                  this.open();
              }
          };

          Select2.prototype.open = function () {
              if (this.isOpen()) {
                  return;
              }

              this.trigger('query', {});

              this.trigger('open');
          };

          Select2.prototype.close = function () {
              if (!this.isOpen()) {
                  return;
              }

              this.trigger('close');
          };

          Select2.prototype.isOpen = function () {
              return this.$container.hasClass('select2-container--open');
          };

          Select2.prototype.hasFocus = function () {
              return this.$container.hasClass('select2-container--focus');
          };

          Select2.prototype.focus = function (data) {
              // No need to re-trigger focus events if we are already focused
              if (this.hasFocus()) {
                  return;
              }

              this.$container.addClass('select2-container--focus');
              this.trigger('focus');
          };

          Select2.prototype.enable = function (args) {
              if (this.options.get('debug') && window.console && console.warn) {
                  console.warn(
                    'Select2: The `select2("enable")` method has been deprecated and will' +
                    ' be removed in later Select2 versions. Use $element.prop("disabled")' +
                    ' instead.'
                  );
              }

              if (args == null || args.length === 0) {
                  args = [true];
              }

              var disabled = !args[0];

              this.$element.prop('disabled', disabled);
          };

          Select2.prototype.data = function () {
              if (this.options.get('debug') &&
                  arguments.length > 0 && window.console && console.warn) {
                  console.warn(
                    'Select2: Data can no longer be set using `select2("data")`. You ' +
                    'should consider setting the value instead using `$element.val()`.'
                  );
              }

              var data = [];

              this.dataAdapter.current(function (currentData) {
                  data = currentData;
              });

              return data;
          };

          Select2.prototype.val = function (args) {
              if (this.options.get('debug') && window.console && console.warn) {
                  console.warn(
                    'Select2: The `select2("val")` method has been deprecated and will be' +
                    ' removed in later Select2 versions. Use $element.val() instead.'
                  );
              }

              if (args == null || args.length === 0) {
                  return this.$element.val();
              }

              var newVal = args[0];

              if ($.isArray(newVal)) {
                  newVal = $.map(newVal, function (obj) {
                      return obj.toString();
                  });
              }

              this.$element.val(newVal).trigger('change');
          };

          Select2.prototype.destroy = function () {
              this.$container.remove();

              if (this.$element[0].detachEvent) {
                  this.$element[0].detachEvent('onpropertychange', this._sync);
              }

              if (this._observer != null) {
                  this._observer.disconnect();
                  this._observer = null;
              } else if (this.$element[0].removeEventListener) {
                  this.$element[0]
                    .removeEventListener('DOMAttrModified', this._sync, false);
              }

              this._sync = null;

              this.$element.off('.select2');
              this.$element.attr('tabindex', this.$element.data('old-tabindex'));

              this.$element.removeClass('select2-hidden-accessible');
              this.$element.attr('aria-hidden', 'false');
              this.$element.removeData('select2');

              this.dataAdapter.destroy();
              this.selection.destroy();
              this.dropdown.destroy();
              this.results.destroy();

              this.dataAdapter = null;
              this.selection = null;
              this.dropdown = null;
              this.results = null;
          };

          Select2.prototype.render = function () {
              var $container = $(
                '<span class="select2 select2-container">' +
                  '<span class="selection"></span>' +
                  '<span class="dropdown-wrapper" aria-hidden="true"></span>' +
                '</span>'
              );

              $container.attr('dir', this.options.get('dir'));

              this.$container = $container;

              this.$container.addClass('select2-container--' + this.options.get('theme'));

              $container.data('element', this.$element);

              return $container;
          };

          return Select2;
      });

      S2.define('jquery.select2', [
        'jquery',
        'require',

        './select2/core',
        './select2/defaults'
      ], function ($, require, Select2, Defaults) {
          // Force jQuery.mousewheel to be loaded if it hasn't already
          require('jquery.mousewheel');

          if ($.fn.select2 == null) {
              // All methods that should return the element
              var thisMethods = ['open', 'close', 'destroy'];

              $.fn.select2 = function (options) {
                  options = options || {};

                  if (typeof options === 'object') {
                      this.each(function () {
                          var instanceOptions = $.extend({}, options, true);

                          var instance = new Select2($(this), instanceOptions);
                      });

                      return this;
                  } else if (typeof options === 'string') {
                      var instance = this.data('select2');

                      if (instance == null && window.console && console.error) {
                          console.error(
                            'The select2(\'' + options + '\') method was called on an ' +
                            'element that is not using Select2.'
                          );
                      }

                      var args = Array.prototype.slice.call(arguments, 1);

                      var ret = instance[options](args);

                      // Check if we should be returning `this`
                      if ($.inArray(options, thisMethods) > -1) {
                          return this;
                      }

                      return ret;
                  } else {
                      throw new Error('Invalid arguments for Select2: ' + options);
                  }
              };
          }

          if ($.fn.select2.defaults == null) {
              $.fn.select2.defaults = Defaults;
          }

          return Select2;
      });

      S2.define('jquery.mousewheel', [
        'jquery'
      ], function ($) {
          // Used to shim jQuery.mousewheel for non-full builds.
          return $;
      });

      // Return the AMD loader configuration so it can be used outside of this file
      return {
          define: S2.define,
          require: S2.require
      };
  }());

    // Autoload the jQuery bindings
    // We know that all of the modules exist above this, so we're safe
    var select2 = S2.require('jquery.select2');

    // Hold the AMD module references on the jQuery function that was just loaded
    // This allows Select2 to use the internal loader outside of this file, such
    // as in the language files.
    jQuery.fn.select2.amd = S2;

    // Return the Select2 instance for anyone who is importing it.
    return select2;
}));
;
/*! Select2 4.0.0 | https://github.com/select2/select2/blob/master/LICENSE.md */

(function () { if (jQuery && jQuery.fn && jQuery.fn.select2 && jQuery.fn.select2.amd) var e = jQuery.fn.select2.amd; return e.define("select2/i18n/fr", [], function () { return { inputTooLong: function (e) { var t = e.input.length - e.maximum, n = "Supprimez " + t + " caractère"; return t !== 1 && (n += "s"), n }, inputTooShort: function (e) { var t = e.minimum - e.input.length, n = "Saisissez " + t + " caractère"; return t !== 1 && (n += "s"), n }, loadingMore: function () { return "Chargement de résultats supplémentaires…" }, maximumSelected: function (e) { var t = "Vous pouvez seulement sélectionner " + e.maximum + " élément"; return e.maximum !== 1 && (t += "s"), t }, noResults: function () { return "Aucun résultat trouvé" }, searching: function () { return "Recherche en cours…" } } }), { define: e.define, require: e.require } })();;
window.downloadFile = function (sUrl) {

    //iOS devices do not support downloading. We have to inform user about this.
    if (/(iP)/g.test(navigator.userAgent)) {
        alert('Your device does not support files downloading. Please try again in desktop browser.');
        return false;
    }

    //If in Chrome or Safari - download via virtual link click
    if (window.downloadFile.isChrome || window.downloadFile.isSafari) {
        //Creating new link node.
        var link = document.createElement('a');
        link.href = sUrl;

        if (link.download !== undefined) {
            //Set HTML5 download attribute. This will prevent file from opening if supported.
            var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
            link.download = fileName;
        }

        //Dispatching click event.
        if (document.createEvent) {
            var e = document.createEvent('MouseEvents');
            e.initEvent('click', true, true);
            link.dispatchEvent(e);
            return true;
        }
    }

    // Force file download (whether supported by server).
    if (sUrl.indexOf('?') === -1) {
        sUrl += '?download';
    }

    window.open(sUrl, '_self');
    return true;
}

window.downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
window.downloadFile.isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
window.downloadFile.isIe = navigator.userAgent.toLowerCase().indexOf('msie') > -1
                            || navigator.userAgent.toLowerCase().indexOf('trident/') > -1
                            || navigator.userAgent.toLowerCase().indexOf('edge') > -1;
;
(function ($) {
    $.fn.addOption = function (settings) {

        return this.each(function () {
            var select = $(this);
            var options = select.find("option");
            var length = options.length;
            var exist = false;
            for (var i = 0; i < length; i++) {
                var optTemp = $(options).get(i);
                if ($(optTemp).val() == settings.value) {
                    exist = true;
                    break;
                }
            }

            if (!exist) {
                select.append("<option value='" + settings.value + "'>" + settings.text + "</option>");
            }
            
        });
        return this;
    };
})(jQuery);;
(function ($) {
	$.fn.Export = function (action) {


		return this.each(function () {

			var form = $(this);
			var action = form.attr("action");

			form.attr("action", form.data("export-url"))
    
			var events = $._data(this, "events").submit;
			var nb = events.length;
			var oldSumit = $._data(this, "events").submit[nb-1];

			
			console.log("form", oldSumit);
			form.unbind("submit", oldSumit);
			form.submit();

			form.attr("action", action);
			form.bind("submit", oldSumit);
		});
		return this;
	};
})(jQuery);;
(function ($) {
    $.fn.Spinner = function (action) {

        getOverlayContainer = function (width, height) {
            var overlay = $("<div ></div>")
                .addClass("overlay load")
                .css("width", width)
                .css("height", height)
                .css("position", "absolute")
                .css("text-align", "center")
                .css("z-index", 100)
                .css("line-height", (height + 5) + "px")
                .html('<div class="loading-grid" style="margin-left:auto; margin-right:auto; width:100%;"><div class="msg"><img src="'+site.params.url+'/Content/images/loading.gif" /></div></div>');
            return overlay;
        }

		return this.each(function () {
		    var element = $(this);

		    var previous = element.prev();
		    if (previous.hasClass("select2-container")) { //si on vise un element 'select2.js'
		        var elementSelect2 = previous;
		    }

		    if (action == "show") {

		        if (element.is(":visible") && !element.hasClass("select2-offscreen")) {
		            element.css("opacity", "0.3");
		            var width = element.outerWidth();
		            var height = element.outerHeight();
		            var overlay = getOverlayContainer(width, height);
		            element.before(overlay);
		        }
		        if (previous.hasClass("select2-container")) {

		            var width = elementSelect2.outerWidth();
		            var height = elementSelect2.outerHeight();
		            var overlay = getOverlayContainer(width, height);

		            elementSelect2.before(overlay);
		        }

	
		    } else {

		        if (previous.hasClass("overlay") && !element.hasClass("select2-offscreen")) {
		            element.css("opacity", "1");
		            element.prev().remove();
		        }

		        if (previous.hasClass("select2-container")) { //si on vise un element 'select2.js'
		            elementSelect2.prev().remove();
		        }
		    }
		    
		});
		return this;
	};
})(jQuery);;
/** Trumbowyg v2.14.0 - A lightweight WYSIWYG editor - alex-d.github.io/Trumbowyg - License MIT - Author : Alexandre Demode (Alex-D) / alex-d.fr */
jQuery.trumbowyg = { langs: { en: { viewHTML: "View HTML", undo: "Undo", redo: "Redo", formatting: "Formatting", p: "Paragraph", blockquote: "Quote", code: "Code", header: "Header", bold: "Bold", italic: "Italic", strikethrough: "Stroke", underline: "Underline", strong: "Strong", em: "Emphasis", del: "Deleted", superscript: "Superscript", subscript: "Subscript", unorderedList: "Unordered list", orderedList: "Ordered list", insertImage: "Insert Image", link: "Link", createLink: "Insert link", unlink: "Remove link", justifyLeft: "Align Left", justifyCenter: "Align Center", justifyRight: "Align Right", justifyFull: "Align Justify", horizontalRule: "Insert horizontal rule", removeformat: "Remove format", fullscreen: "Fullscreen", close: "Close", submit: "Confirm", reset: "Cancel", required: "Required", description: "Description", title: "Title", text: "Text", target: "Target", width: "Width" } }, plugins: {}, svgPath:'/Scripts/Libraries/Trumbowyg/ui/icons.svg',hideButtonTexts:null},Object.defineProperty(jQuery.trumbowyg,"defaultOptions",{value:{lang:"en",fixedBtnPane:!1,fixedFullWidth:!1,autogrow:!1,autogrowOnEnter:!1,imageWidthModalEdit:!1,prefix:"trumbowyg-",semantic:!0,resetCss:!1,removeformatPasted:!1,tagsToRemove:[],tagsToKeep:["hr","img","embed","iframe","input"],btns:[["viewHTML"],["undo","redo"],["formatting"],["strong","em","del"],["superscript","subscript"],["link"],["insertImage"],["justifyLeft","justifyCenter","justifyRight","justifyFull"],["unorderedList","orderedList"],["horizontalRule"],["removeformat"],["fullscreen"]],btnsDef:{},inlineElementsSelector:"a,abbr,acronym,b,caption,cite,code,col,dfn,dir,dt,dd,em,font,hr,i,kbd,li,q,span,strikeout,strong,sub,sup,u",pasteHandlers:[],plugins:{},urlProtocol:!1,minimalLinks:!1},writable:!1,enumerable:!0,configurable:!1}),function(e,t,n,a){"use strict";var o="tbwconfirm",r="tbwcancel";a.fn.trumbowyg=function(e,t){var n="trumbowyg";if(e===Object(e)||!e)return this.each(function(){a(this).data(n)||a(this).data(n,new i(this,e))});if(1===this.length)try{var o=a(this).data(n);switch(e){case"execCmd":return o.execCmd(t.cmd,t.param,t.forceCss);case"openModal":return o.openModal(t.title,t.content);case"closeModal":return o.closeModal();case"openModalInsert":return o.openModalInsert(t.title,t.fields,t.callback);case"saveRange":return o.saveRange();case"getRange":return o.range;case"getRangeText":return o.getRangeText();case"restoreRange":return o.restoreRange();case"enable":return o.setDisabled(!1);case"disable":return o.setDisabled(!0);case"toggle":return o.toggle();case"destroy":return o.destroy();case"empty":return o.empty();case"html":return o.html(t)}}catch(r){}return!1};var i=function(o,r){var i=this,s="trumbowyg-icons",l=a.trumbowyg;i.doc=o.ownerDocument||n,i.$ta=a(o),i.$c=a(o),r=r||{},null!=r.lang||null!=l.langs[r.lang]?i.lang=a.extend(!0,{},l.langs.en,l.langs[r.lang]):i.lang=l.langs.en,i.hideButtonTexts=null!=l.hideButtonTexts?l.hideButtonTexts:r.hideButtonTexts;var d=null!=l.svgPath?l.svgPath:r.svgPath;if(i.hasSvg=d!==!1,i.svgPath=i.doc.querySelector("base")?t.location.href.split("#")[0]:"",0===a("#"+s,i.doc).length&&d!==!1){if(null==d){for(var c=n.getElementsByTagName("script"),u=0;u<c.length;u+=1){var g=c[u].src,f=g.match("trumbowyg(.min)?.js");null!=f&&(d=g.substring(0,g.indexOf(f[0]))+"ui/icons.svg")}null==d&&console.warn("You must define svgPath: https://goo.gl/CfTY9U")}var h=i.doc.createElement("div");h.id=s,i.doc.body.insertBefore(h,i.doc.body.childNodes[0]),a.ajax({async:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",dataType:"xml",crossDomain:!0,url:d,data:null,beforeSend:null,complete:null,success:function(e){h.innerHTML=(new XMLSerializer).serializeToString(e.documentElement)}})}var p=i.lang.header,m=function(){return(t.chrome||t.Intl&&Intl.v8BreakIterator)&&"CSS"in t};i.btnsDef={viewHTML:{fn:"toggle","class":"trumbowyg-not-disable"},undo:{isSupported:m,key:"Z"},redo:{isSupported:m,key:"Y"},p:{fn:"formatBlock"},blockquote:{fn:"formatBlock"},h1:{fn:"formatBlock",title:p+" 1"},h2:{fn:"formatBlock",title:p+" 2"},h3:{fn:"formatBlock",title:p+" 3"},h4:{fn:"formatBlock",title:p+" 4"},subscript:{tag:"sub"},superscript:{tag:"sup"},bold:{key:"B",tag:"b"},italic:{key:"I",tag:"i"},underline:{tag:"u"},strikethrough:{tag:"strike"},strong:{fn:"bold",key:"B"},em:{fn:"italic",key:"I"},del:{fn:"strikethrough"},createLink:{key:"K",tag:"a"},unlink:{},insertImage:{},justifyLeft:{tag:"left",forceCss:!0},justifyCenter:{tag:"center",forceCss:!0},justifyRight:{tag:"right",forceCss:!0},justifyFull:{tag:"justify",forceCss:!0},unorderedList:{fn:"insertUnorderedList",tag:"ul"},orderedList:{fn:"insertOrderedList",tag:"ol"},horizontalRule:{fn:"insertHorizontalRule"},removeformat:{},fullscreen:{"class":"trumbowyg-not-disable"},close:{fn:"destroy","class":"trumbowyg-not-disable"},formatting:{dropdown:["p","blockquote","h1","h2","h3","h4"],ico:"p"},link:{dropdown:["createLink","unlink"]}},i.o=a.extend(!0,{},l.defaultOptions,r),i.o.hasOwnProperty("imgDblClickHandler")||(i.o.imgDblClickHandler=i.getDefaultImgDblClickHandler()),i.urlPrefix=i.setupUrlPrefix(),i.disabled=i.o.disabled||"TEXTAREA"===o.nodeName&&o.disabled,r.btns?i.o.btns=r.btns:i.o.semantic||(i.o.btns[3]=["bold","italic","underline","strikethrough"]),a.each(i.o.btnsDef,function(e,t){i.addBtnDef(e,t)}),i.eventNamespace="trumbowyg-event",i.keys=[],i.tagToButton={},i.tagHandlers=[],i.pasteHandlers=[].concat(i.o.pasteHandlers),i.isIE=e.userAgent.indexOf("MSIE")!==-1||e.appVersion.indexOf("Trident/")!==-1,i.init()};i.prototype={DEFAULT_SEMANTIC_MAP:{b:"strong",i:"em",s:"del",strike:"del",div:"p"},init:function(){var e=this;e.height=e.$ta.height(),e.initPlugins();try{e.doc.execCommand("enableObjectResizing",!1,!1),e.doc.execCommand("defaultParagraphSeparator",!1,"p")}catch(t){}e.buildEditor(),e.buildBtnPane(),e.fixedBtnPaneEvents(),e.buildOverlay(),setTimeout(function(){e.disabled&&e.setDisabled(!0),e.$c.trigger("tbwinit")})},addBtnDef:function(e,t){this.btnsDef[e]=t},setupUrlPrefix:function(){var e=this.o.urlProtocol;if(e)return"string"!=typeof e?"https://":/:\/\/$/.test(e)?e:e+"://"},buildEditor:function(){var e=this,n=e.o.prefix,o="";e.$box=a("<div/>",{"class":n+"box "+n+"editor-visible "+n+e.o.lang+" trumbowyg"}),e.isTextarea=e.$ta.is("textarea"),e.isTextarea?(o=e.$ta.val(),e.$ed=a("<div/>"),e.$box.insertAfter(e.$ta).append(e.$ed,e.$ta)):(e.$ed=e.$ta,o=e.$ed.html(),e.$ta=a("<textarea/>",{name:e.$ta.attr("id"),height:e.height}).val(o),e.$box.insertAfter(e.$ed).append(e.$ta,e.$ed),e.syncCode()),e.$ta.addClass(n+"textarea").attr("tabindex",-1),e.$ed.addClass(n+"editor").attr({contenteditable:!0,dir:e.lang._dir||"ltr"}).html(o),e.o.tabindex&&e.$ed.attr("tabindex",e.o.tabindex),e.$c.is("[placeholder]")&&e.$ed.attr("placeholder",e.$c.attr("placeholder")),e.$c.is("[spellcheck]")&&e.$ed.attr("spellcheck",e.$c.attr("spellcheck")),e.o.resetCss&&e.$ed.addClass(n+"reset-css"),e.o.autogrow||e.$ta.add(e.$ed).css({height:e.height}),e.semanticCode(),e.o.autogrowOnEnter&&e.$ed.addClass(n+"autogrow-on-enter");var r,i=!1,s=!1,l="keyup";e.$ed.on("dblclick","img",e.o.imgDblClickHandler).on("keydown",function(t){if((t.ctrlKey||t.metaKey)&&!t.altKey){i=!0;var n=e.keys[String.fromCharCode(t.which).toUpperCase()];try{return e.execCmd(n.fn,n.param),!1}catch(a){}}}).on("compositionstart compositionupdate",function(){s=!0}).on(l+" compositionend",function(t){if("compositionend"===t.type)s=!1;else if(s)return;var n=t.which;if(!(n>=37&&n<=40)){if(!t.ctrlKey&&!t.metaKey||89!==n&&90!==n)if(i||17===n)"undefined"==typeof t.which&&e.semanticCode(!1,!1,!0);else{var a=!e.isIE||"compositionend"===t.type;e.semanticCode(!1,a&&13===n),e.$c.trigger("tbwchange")}else e.semanticCode(!1,!0),e.$c.trigger("tbwchange");setTimeout(function(){i=!1},50)}}).on("mouseup keydown keyup",function(t){(!t.ctrlKey&&!t.metaKey||t.altKey)&&setTimeout(function(){i=!1},50),clearTimeout(r),r=setTimeout(function(){e.updateButtonPaneStatus()},50)}).on("focus blur",function(t){if(e.$c.trigger("tbw"+t.type),"blur"===t.type&&a("."+n+"active-button",e.$btnPane).removeClass(n+"active-button "+n+"active"),e.o.autogrowOnEnter){if(e.autogrowOnEnterDontClose)return;"focus"===t.type?(e.autogrowOnEnterWasFocused=!0,e.autogrowEditorOnEnter()):e.o.autogrow||(e.$ed.css({height:e.$ed.css("min-height")}),e.$c.trigger("tbwresize"))}}).on("cut drop",function(){setTimeout(function(){e.semanticCode(!1,!0),e.$c.trigger("tbwchange")},0)}).on("paste",function(n){if(e.o.removeformatPasted){n.preventDefault(),t.getSelection&&t.getSelection().deleteFromDocument&&t.getSelection().deleteFromDocument();try{var o=t.clipboardData.getData("Text");try{e.doc.selection.createRange().pasteHTML(o)}catch(r){e.doc.getSelection().getRangeAt(0).insertNode(e.doc.createTextNode(o))}e.$c.trigger("tbwchange",n)}catch(i){e.execCmd("insertText",(n.originalEvent||n).clipboardData.getData("text/plain"))}}a.each(e.pasteHandlers,function(e,t){t(n)}),setTimeout(function(){e.semanticCode(!1,!0),e.$c.trigger("tbwpaste",n),e.$c.trigger("tbwchange")},0)}),e.$ta.on("keyup",function(){e.$c.trigger("tbwchange")}).on("paste",function(){setTimeout(function(){e.$c.trigger("tbwchange")},0)}),e.$box.on("keydown",function(t){if(27===t.which&&1===a("."+n+"modal-box",e.$box).length)return e.closeModal(),!1})},autogrowEditorOnEnter:function(){var e=this;e.$ed.removeClass("autogrow-on-enter");var t=e.$ed[0].clientHeight;e.$ed.height("auto");var n=e.$ed[0].scrollHeight;e.$ed.addClass("autogrow-on-enter"),t!==n&&(e.$ed.height(t),setTimeout(function(){e.$ed.css({height:n}),e.$c.trigger("tbwresize")},0))},buildBtnPane:function(){var e=this,t=e.o.prefix,n=e.$btnPane=a("<div/>",{"class":t+"button-pane"});a.each(e.o.btns,function(o,r){a.isArray(r)||(r=[r]);var i=a("<div/>",{"class":t+"button-group "+(r.indexOf("fullscreen")>=0?t+"right":"")});a.each(r,function(t,n){try{e.isSupportedBtn(n)&&i.append(e.buildBtn(n))}catch(a){}}),i.html().trim().length>0&&n.append(i)}),e.$box.prepend(n)},buildBtn:function(e){var t=this,n=t.o.prefix,o=t.btnsDef[e],r=o.dropdown,i=null==o.hasIcon||o.hasIcon,s=t.lang[e]||e,l=a("<button/>",{type:"button","class":n+e+"-button "+(o["class"]||"")+(i?"":" "+n+"textual-button"),html:t.hasSvg&&i?'<svg><use xlink:href="'+t.svgPath+"#"+n+(o.ico||e).replace(/([A-Z]+)/g,"-$1").toLowerCase()+'"/></svg>':t.hideButtonTexts?"":o.text||o.title||t.lang[e]||e,title:(o.title||o.text||s)+(o.key?" (Ctrl + "+o.key+")":""),tabindex:-1,mousedown:function(){return r&&!a("."+e+"-"+n+"dropdown",t.$box).is(":hidden")||a("body",t.doc).trigger("mousedown"),!((t.$btnPane.hasClass(n+"disable")||t.$box.hasClass(n+"disabled"))&&!a(this).hasClass(n+"active")&&!a(this).hasClass(n+"not-disable"))&&(t.execCmd(!!r&&"dropdown"||o.fn||e,o.param||e,o.forceCss),!1)}});if(r){l.addClass(n+"open-dropdown");var d=n+"dropdown",c={"class":d+"-"+e+" "+d+" "+n+"fixed-top"};c["data-"+d]=e;var u=a("<div/>",c);a.each(r,function(e,n){t.btnsDef[n]&&t.isSupportedBtn(n)&&u.append(t.buildSubBtn(n))}),t.$box.append(u.hide())}else o.key&&(t.keys[o.key]={fn:o.fn||e,param:o.param||e});return r||(t.tagToButton[(o.tag||e).toLowerCase()]=e),l},buildSubBtn:function(e){var t=this,n=t.o.prefix,o=t.btnsDef[e],r=null==o.hasIcon||o.hasIcon;return o.key&&(t.keys[o.key]={fn:o.fn||e,param:o.param||e}),t.tagToButton[(o.tag||e).toLowerCase()]=e,a("<button/>",{type:"button","class":n+e+"-dropdown-button"+(o.ico?" "+n+o.ico+"-button":""),html:t.hasSvg&&r?'<svg><use xlink:href="'+t.svgPath+"#"+n+(o.ico||e).replace(/([A-Z]+)/g,"-$1").toLowerCase()+'"/></svg>'+(o.text||o.title||t.lang[e]||e):o.text||o.title||t.lang[e]||e,title:o.key?" (Ctrl + "+o.key+")":null,style:o.style||null,mousedown:function(){return a("body",t.doc).trigger("mousedown"),t.execCmd(o.fn||e,o.param||e,o.forceCss),!1}})},isSupportedBtn:function(e){try{return this.btnsDef[e].isSupported()}catch(t){}return!0},buildOverlay:function(){var e=this;return e.$overlay=a("<div/>",{"class":e.o.prefix+"overlay"}).appendTo(e.$box),e.$overlay},showOverlay:function(){var e=this;a(t).trigger("scroll"),e.$overlay.fadeIn(200),e.$box.addClass(e.o.prefix+"box-blur")},hideOverlay:function(){var e=this;e.$overlay.fadeOut(50),e.$box.removeClass(e.o.prefix+"box-blur")},fixedBtnPaneEvents:function(){var e=this,n=e.o.fixedFullWidth,o=e.$box;e.o.fixedBtnPane&&(e.isFixed=!1,a(t).on("scroll."+e.eventNamespace+" resize."+e.eventNamespace,function(){if(o){e.syncCode();var r=a(t).scrollTop(),i=o.offset().top+1,s=e.$btnPane,l=s.outerHeight()-2;r-i>0&&r-i-e.height<0?(e.isFixed||(e.isFixed=!0,s.css({position:"fixed",top:0,left:n?"0":"auto",zIndex:7}),a([e.$ta,e.$ed]).css({marginTop:s.height()})),s.css({width:n?"100%":o.width()-1+"px"}),a("."+e.o.prefix+"fixed-top",o).css({position:n?"fixed":"absolute",top:n?l:l+(r-i)+"px",zIndex:15})):e.isFixed&&(e.isFixed=!1,s.removeAttr("style"),a([e.$ta,e.$ed]).css({marginTop:0}),a("."+e.o.prefix+"fixed-top",o).css({position:"absolute",top:l}))}}))},setDisabled:function(e){var t=this,n=t.o.prefix;t.disabled=e,e?t.$ta.attr("disabled",!0):t.$ta.removeAttr("disabled"),t.$box.toggleClass(n+"disabled",e),t.$ed.attr("contenteditable",!e)},destroy:function(){var e=this,n=e.o.prefix;e.isTextarea?e.$box.after(e.$ta.css({height:""}).val(e.html()).removeClass(n+"textarea").show()):e.$box.after(e.$ed.css({height:""}).removeClass(n+"editor").removeAttr("contenteditable").removeAttr("dir").html(e.html()).show()),e.$ed.off("dblclick","img"),e.destroyPlugins(),e.$box.remove(),e.$c.removeData("trumbowyg"),a("body").removeClass(n+"body-fullscreen"),e.$c.trigger("tbwclose"),a(t).off("scroll."+e.eventNamespace+" resize."+e.eventNamespace)},empty:function(){this.$ta.val(""),this.syncCode(!0)},toggle:function(){var e=this,t=e.o.prefix;e.o.autogrowOnEnter&&(e.autogrowOnEnterDontClose=!e.$box.hasClass(t+"editor-hidden")),e.semanticCode(!1,!0),setTimeout(function(){e.doc.activeElement.blur(),e.$box.toggleClass(t+"editor-hidden "+t+"editor-visible"),e.$btnPane.toggleClass(t+"disable"),a("."+t+"viewHTML-button",e.$btnPane).toggleClass(t+"active"),e.$box.hasClass(t+"editor-visible")?e.$ta.attr("tabindex",-1):e.$ta.removeAttr("tabindex"),e.o.autogrowOnEnter&&!e.autogrowOnEnterDontClose&&e.autogrowEditorOnEnter()},0)},dropdown:function(e){var n=this,o=n.doc,r=n.o.prefix,i=a("[data-"+r+"dropdown="+e+"]",n.$box),s=a("."+r+e+"-button",n.$btnPane),l=i.is(":hidden");if(a("body",o).trigger("mousedown"),l){var d=s.offset().left;s.addClass(r+"active"),i.css({position:"absolute",top:s.offset().top-n.$btnPane.offset().top+s.outerHeight(),left:n.o.fixedFullWidth&&n.isFixed?d+"px":d-n.$btnPane.offset().left+"px"}).show(),a(t).trigger("scroll"),a("body",o).on("mousedown."+n.eventNamespace,function(e){i.is(e.target)||(a("."+r+"dropdown",n.$box).hide(),a("."+r+"active",n.$btnPane).removeClass(r+"active"),a("body",o).off("mousedown."+n.eventNamespace))})}},html:function(e){var t=this;return null!=e?(t.$ta.val(e),t.syncCode(!0),t.$c.trigger("tbwchange"),t):t.$ta.val()},syncTextarea:function(){var e=this;e.$ta.val(e.$ed.text().trim().length>0||e.$ed.find(e.o.tagsToKeep.join(",")).length>0?e.$ed.html():"")},syncCode:function(e){var t=this;if(!e&&t.$ed.is(":visible"))t.syncTextarea();else{var n=a("<div>").html(t.$ta.val()),o=a("<div>").append(n);a(t.o.tagsToRemove.join(","),o).remove(),t.$ed.html(o.contents().html())}if(t.o.autogrow&&(t.height=t.$ed.height(),t.height!==t.$ta.css("height")&&(t.$ta.css({height:t.height}),t.$c.trigger("tbwresize"))),t.o.autogrowOnEnter){t.$ed.height("auto");var r=t.autogrowOnEnterWasFocused?t.$ed[0].scrollHeight:t.$ed.css("min-height");r!==t.$ta.css("height")&&(t.$ed.css({height:r}),t.$c.trigger("tbwresize"))}},semanticCode:function(e,t,n){var o=this;if(o.saveRange(),o.syncCode(e),o.o.semantic){if(o.semanticTag("b"),o.semanticTag("i"),o.semanticTag("s"),o.semanticTag("strike"),t){var r=o.o.inlineElementsSelector,i=":not("+r+")";o.$ed.contents().filter(function(){return 3===this.nodeType&&this.nodeValue.trim().length>0}).wrap("<span data-tbw/>");var s=function(e){if(0!==e.length){var t=e.nextUntil(i).addBack().wrapAll("<p/>").parent(),n=t.nextAll(r).first();t.next("br").remove(),s(n)}};s(o.$ed.children(r).first()),o.semanticTag("div",!0),o.$ed.find("p").filter(function(){return(!o.range||this!==o.range.startContainer)&&(0===a(this).text().trim().length&&0===a(this).children().not("br,span").length)}).contents().unwrap(),a("[data-tbw]",o.$ed).contents().unwrap(),o.$ed.find("p:empty").remove()}n||o.restoreRange(),o.syncTextarea()}},semanticTag:function(e,t){var n;if(null!=this.o.semantic&&"object"==typeof this.o.semantic&&this.o.semantic.hasOwnProperty(e))n=this.o.semantic[e];else{if(this.o.semantic!==!0||!this.DEFAULT_SEMANTIC_MAP.hasOwnProperty(e))return;n=this.DEFAULT_SEMANTIC_MAP[e]}a(e,this.$ed).each(function(){var e=a(this);return 0!==e.contents().length&&(e.wrap("<"+n+"/>"),t&&a.each(e.prop("attributes"),function(){e.parent().attr(this.name,this.value)}),void e.contents().unwrap())})},createLink:function(){for(var e,t,n,o=this,r=o.doc.getSelection(),i=r.focusNode,s=(new XMLSerializer).serializeToString(r.getRangeAt(0).cloneContents());["A","DIV"].indexOf(i.nodeName)<0;)i=i.parentNode;if(i&&"A"===i.nodeName){var l=a(i);s=l.text(),e=l.attr("href"),o.o.minimalLinks||(t=l.attr("title"),n=l.attr("target"));var d=o.doc.createRange();d.selectNode(i),r.removeAllRanges(),r.addRange(d)}o.saveRange();var c={url:{label:"URL",required:!0,value:e},text:{label:o.lang.text,value:s}};o.o.minimalLinks||Object.assign(c,{title:{label:o.lang.title,value:t},target:{label:o.lang.target,value:n}}),o.openModalInsert(o.lang.createLink,c,function(e){var t=o.prependUrlPrefix(e.url);if(!t.length)return!1;var n=a(['<a href="',t,'">',e.text||e.url,"</a>"].join(""));return o.o.minimalLinks||(e.title.length>0&&n.attr("title",e.title),e.target.length>0&&n.attr("target",e.target)),o.range.deleteContents(),o.range.insertNode(n[0]),o.syncCode(),o.$c.trigger("tbwchange"),!0})},prependUrlPrefix:function(e){var t=this;if(!t.urlPrefix)return e;var n=/^([a-z][-+.a-z0-9]*:|\/|#)/i;if(n.test(e))return e;var a=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return a.test(e)?"mailto:"+e:t.urlPrefix+e},unlink:function(){var e=this,t=e.doc.getSelection(),n=t.focusNode;if(t.isCollapsed){for(;["A","DIV"].indexOf(n.nodeName)<0;)n=n.parentNode;if(n&&"A"===n.nodeName){var a=e.doc.createRange();a.selectNode(n),t.removeAllRanges(),t.addRange(a)}}e.execCmd("unlink",void 0,void 0,!0)},insertImage:function(){var e=this;e.saveRange();var t={url:{label:"URL",required:!0},alt:{label:e.lang.description,value:e.getRangeText()}};e.o.imageWidthModalEdit&&(t.width={}),e.openModalInsert(e.lang.insertImage,t,function(t){e.execCmd("insertImage",t.url,!1,!0);var n=a('img[src="'+t.url+'"]:not([alt])',e.$box);return n.attr("alt",t.alt),e.o.imageWidthModalEdit&&n.attr({width:t.width}),e.syncCode(),e.$c.trigger("tbwchange"),!0})},fullscreen:function(){var e,n=this,o=n.o.prefix,r=o+"fullscreen";n.$box.toggleClass(r),e=n.$box.hasClass(r),a("body").toggleClass(o+"body-fullscreen",e),a(t).trigger("scroll"),n.$c.trigger("tbw"+(e?"open":"close")+"fullscreen")},execCmd:function(e,t,n,a){var o=this;a=!!a||"","dropdown"!==e&&o.$ed.focus();try{o.doc.execCommand("styleWithCSS",!1,n||!1)}catch(r){}try{o[e+a](t)}catch(r){try{e(t)}catch(i){"insertHorizontalRule"===e?t=void 0:"formatBlock"===e&&o.isIE&&(t="<"+t+">"),o.doc.execCommand(e,!1,t),o.syncCode(),o.semanticCode(!1,!0)}"dropdown"!==e&&(o.updateButtonPaneStatus(),o.$c.trigger("tbwchange"))}},openModal:function(e,n){var i=this,s=i.o.prefix;if(a("."+s+"modal-box",i.$box).length>0)return!1;i.o.autogrowOnEnter&&(i.autogrowOnEnterDontClose=!0),i.saveRange(),i.showOverlay(),i.$btnPane.addClass(s+"disable");var l=a("<div/>",{"class":s+"modal "+s+"fixed-top"}).css({top:i.$box.offset().top+i.$btnPane.height(),zIndex:99999}).appendTo(a(i.doc.body));i.$overlay.one("click",function(){return l.trigger(r),!1});var d=a("<form/>",{action:"",html:n}).on("submit",function(){return l.trigger(o),!1}).on("reset",function(){return l.trigger(r),!1}).on("submit reset",function(){i.o.autogrowOnEnter&&(i.autogrowOnEnterDontClose=!1)}),c=a("<div/>",{"class":s+"modal-box",html:d}).css({top:"-"+i.$btnPane.outerHeight()+"px",opacity:0}).appendTo(l).animate({top:0,opacity:1},100);return a("<span/>",{text:e,"class":s+"modal-title"}).prependTo(c),l.height(c.outerHeight()+10),a("input:first",c).focus(),i.buildModalBtn("submit",c),i.buildModalBtn("reset",c),a(t).trigger("scroll"),l},buildModalBtn:function(e,t){var n=this,o=n.o.prefix;return a("<button/>",{"class":o+"modal-button "+o+"modal-"+e,type:e,text:n.lang[e]||e}).appendTo(a("form",t))},closeModal:function(){var e=this,t=e.o.prefix;e.$btnPane.removeClass(t+"disable"),e.$overlay.off();var o=a("."+t+"modal-box",a(n.body));o.animate({top:"-"+o.height()},100,function(){o.parent().remove(),e.hideOverlay()}),e.restoreRange()},openModalInsert:function(e,t,n){var i=this,s=i.o.prefix,l=i.lang,d="";return a.each(t,function(e,t){var n=t.label||e,a=t.name||e,o=t.attributes||{},r=Object.keys(o).map(function(e){return e+'="'+o[e]+'"'}).join(" ");d+='<label><input type="'+(t.type||"text")+'" name="'+a+'"'+("checkbox"===t.type&&t.value?' checked="checked"':' value="'+(t.value||"").replace(/"/g,"&quot;"))+'"'+r+'><span class="'+s+'input-infos"><span>'+(l[n]?l[n]:n)+"</span></span></label>"}),i.openModal(e,d).on(o,function(){var e=a("form",a(this)),r=!0,s={};a.each(t,function(t,n){var o=n.name||t,l=a('input[name="'+o+'"]',e),d=l.attr("type");switch(d.toLowerCase()){case"checkbox":s[o]=l.is(":checked");break;case"radio":s[o]=l.filter(":checked").val();break;default:s[o]=a.trim(l.val())}n.required&&""===s[o]?(r=!1,i.addErrorOnModalField(l,i.lang.required)):n.pattern&&!n.pattern.test(s[o])&&(r=!1,i.addErrorOnModalField(l,n.patternError))}),r&&(i.restoreRange(),n(s,t)&&(i.syncCode(),i.$c.trigger("tbwchange"),i.closeModal(),a(this).off(o)))}).one(r,function(){a(this).off(o),i.closeModal()})},addErrorOnModalField:function(e,t){var n=this.o.prefix,o=e.parent();e.on("change keyup",function(){o.removeClass(n+"input-error")}),o.addClass(n+"input-error").find("input+span").append(a("<span/>",{"class":n+"msg-error",text:t}))},getDefaultImgDblClickHandler:function(){var e=this;return function(){var t=a(this),n=t.attr("src"),o="(Base64)";0===n.indexOf("data:image")&&(n=o);var r={url:{label:"URL",value:n,required:!0},alt:{label:e.lang.description,value:t.attr("alt")}};return e.o.imageWidthModalEdit&&(r.width={value:t.attr("width")?t.attr("width"):""}),e.openModalInsert(e.lang.insertImage,r,function(n){return n.url!==o&&t.attr({src:n.url}),t.attr({alt:n.alt}),e.o.imageWidthModalEdit&&(parseInt(n.width)>0?t.attr({width:n.width}):t.removeAttr("width")),!0}),!1}},saveRange:function(){var e=this,t=e.doc.getSelection();if(e.range=null,t&&t.rangeCount){var n,a=e.range=t.getRangeAt(0),o=e.doc.createRange();o.selectNodeContents(e.$ed[0]),o.setEnd(a.startContainer,a.startOffset),n=(o+"").length,e.metaRange={start:n,end:n+(a+"").length}}},restoreRange:function(){var e,t=this,n=t.metaRange,a=t.range,o=t.doc.getSelection();if(a){if(n&&n.start!==n.end){var r,i=0,s=[t.$ed[0]],l=!1,d=!1;for(e=t.doc.createRange();!d&&(r=s.pop());)if(3===r.nodeType){var c=i+r.length;!l&&n.start>=i&&n.start<=c&&(e.setStart(r,n.start-i),l=!0),l&&n.end>=i&&n.end<=c&&(e.setEnd(r,n.end-i),d=!0),i=c}else for(var u=r.childNodes,g=u.length;g>0;)g-=1,s.push(u[g])}o.removeAllRanges(),o.addRange(e||a)}},getRangeText:function(){return this.range+""},updateButtonPaneStatus:function(){var e=this,t=e.o.prefix,n=e.getTagsRecursive(e.doc.getSelection().focusNode),o=t+"active-button "+t+"active";a("."+t+"active-button",e.$btnPane).removeClass(o),a.each(n,function(n,r){var i=e.tagToButton[r.toLowerCase()],s=a("."+t+i+"-button",e.$btnPane);if(s.length>0)s.addClass(o);else try{s=a("."+t+"dropdown ."+t+i+"-dropdown-button",e.$box);var l=s.parent().data("dropdown");a("."+t+l+"-button",e.$box).addClass(o)}catch(d){}})},getTagsRecursive:function(e,t){var n=this;if(t=t||(e&&e.tagName?[e.tagName]:[]),!e||!e.parentNode)return t;e=e.parentNode;var o=e.tagName;return"DIV"===o?t:("P"===o&&""!==e.style.textAlign&&t.push(e.style.textAlign),a.each(n.tagHandlers,function(a,o){t=t.concat(o(e,n))}),t.push(o),n.getTagsRecursive(e,t).filter(function(e){return null!=e}))},initPlugins:function(){var e=this;e.loadedPlugins=[],a.each(a.trumbowyg.plugins,function(t,n){n.shouldInit&&!n.shouldInit(e)||(n.init(e),n.tagHandler&&e.tagHandlers.push(n.tagHandler),e.loadedPlugins.push(n))})},destroyPlugins:function(){a.each(this.loadedPlugins,function(e,t){t.destroy&&t.destroy()})}}}(navigator,window,document,jQuery);;
!function(e){"use strict";var a=function(){return"undefined"!=typeof FileReader},r=function(e){return/^data:image\/[a-z]?/i.test(e)};e.extend(!0,e.trumbowyg,{langs:{en:{base64:"Image as base64",file:"File",errFileReaderNotSupported:"FileReader is not supported by your browser.",errInvalidImage:"Invalid image file."},da:{base64:"Billede som base64",file:"Fil",errFileReaderNotSupported:"FileReader er ikke understøttet af din browser.",errInvalidImage:"Ugyldig billedfil."},fr:{base64:"Image en base64",file:"Fichier"},cs:{base64:"Vložit obrázek",file:"Soubor"},zh_cn:{base64:"图片（Base64编码）",file:"文件"},nl:{base64:"Afbeelding inline",file:"Bestand",errFileReaderNotSupported:"Uw browser ondersteunt deze functionaliteit niet.",errInvalidImage:"De gekozen afbeelding is ongeldig."},ru:{base64:"Изображение как код в base64",file:"Файл",errFileReaderNotSupported:"FileReader не поддерживается вашим браузером.",errInvalidImage:"Недопустимый файл изображения."},ja:{base64:"画像 (Base64形式)",file:"ファイル",errFileReaderNotSupported:"あなたのブラウザーはFileReaderをサポートしていません",errInvalidImage:"画像形式が正しくありません"},tr:{base64:"Base64 olarak resim",file:"Dosya",errFileReaderNotSupported:"FileReader tarayıcınız tarafından desteklenmiyor.",errInvalidImage:"Geçersiz resim dosyası."},zh_tw:{base64:"圖片(base64編碼)",file:"檔案",errFileReaderNotSupported:"你的瀏覽器不支援FileReader",errInvalidImage:"不正確的檔案格式"},pt_br:{base64:"Imagem em base64",file:"Arquivo",errFileReaderNotSupported:"FileReader não é suportado pelo seu navegador.",errInvalidImage:"Arquivo de imagem inválido."}},plugins:{base64:{shouldInit:a,init:function(i){var t={isSupported:a,fn:function(){i.saveRange();var a,t=i.openModalInsert(i.lang.base64,{file:{type:"file",required:!0,attributes:{accept:"image/*"}},alt:{label:"description",value:i.getRangeText()}},function(l){var n=new FileReader;n.onloadend=function(a){r(a.target.result)?(i.execCmd("insertImage",n.result,!1,!0),e(['img[src="',n.result,'"]:not([alt])'].join(""),i.$box).attr("alt",l.alt),i.closeModal()):i.addErrorOnModalField(e("input[type=file]",t),i.lang.errInvalidImage)},n.readAsDataURL(a)});e("input[type=file]").on("change",function(e){a=e.target.files[0]})}};i.addBtnDef("base64",t)}}}})}(jQuery);;
!function(e){"use strict";var i={minSize:32,step:4},n=function(e){return e.preventDefault()};e.extend(!0,e.trumbowyg,{plugins:{resizimg:{init:function(t){function o(){t.$ed.find("img:not(.resizable)").resizable(t.o.plugins.resizimg.resizable).on("mousedown",n)}function r(){t.$ed.find("img.resizable").resizable("destroy").off("mousedown",n).removeClass("resizable"),t.syncTextarea()}t.o.plugins.resizimg=e.extend(!0,{},i,t.o.plugins.resizimg||{},{resizable:{resizeWidth:!1,onDragStart:function(e,i){var n=t.o.plugins.resizimg,o=e.pageX-i.offset().left,r=e.pageY-i.offset().top;if(o<i.width()-n.minSize||r<i.height()-n.minSize)return!1},onDrag:function(e,i,n,o){var r=t.o.plugins.resizimg;return o<r.minSize&&(o=r.minSize),o-=o%r.step,i.height(o),!1},onDragEnd:function(){t.syncCode()}}}),t.$c.on("tbwinit",o),t.$c.on("tbwfocus",o),t.$c.on("tbwchange",o),t.$c.on("tbwblur",r),t.$c.on("tbwclose",r)}}}})}(jQuery);;
